API Reference¶
The following section outlines the API of nextcord.
Note
This module uses the Python logging module to log diagnostic and errors in an output-independent way. If the logging module is not configured, these logs will not be output anywhere. See Setting Up Logging for more information on how to set up and use the logging module with nextcord.
Clients¶
Client¶
- defadd_all_application_commands
- defadd_all_cog_commands
- defadd_application_command
- defadd_application_command_check
- defadd_listener
- defadd_modal
- defadd_view
- @application_command_after_invoke
- @application_command_before_invoke
- @application_command_check
- asyncapplication_info
- asyncbefore_identify_hook
- asyncchange_presence
- asyncclear
- asyncclose
- asyncconnect
- asynccreate_application_emoji
- asynccreate_dm
- asynccreate_guild
- asyncdelete_application_commands
- asyncdelete_invite
- asyncdiscover_application_commands
- @event
- asyncfetch_application_emoji
- asyncfetch_application_emojis
- asyncfetch_channel
- asyncfetch_guild
- asyncfetch_guild_preview
- deffetch_guilds
- asyncfetch_invite
- asyncfetch_premium_sticker_packs
- asyncfetch_stage_instance
- asyncfetch_sticker
- asyncfetch_template
- asyncfetch_user
- asyncfetch_webhook
- asyncfetch_widget
- defget_all_application_commands
- defget_all_channels
- defget_all_members
- defget_application_command
- defget_application_command_from_signature
- defget_application_commands
- defget_channel
- defget_emoji
- defget_guild
- defget_interaction
- defget_partial_messageable
- defget_scheduled_event
- defget_stage_instance
- defget_sticker
- defget_user
- defis_closed
- defis_ready
- defis_ws_ratelimited
- @listen
- asynclogin
- defmessage_command
- asyncon_application_command_error
- asyncon_error
- defparse_mentions
- asyncprocess_application_commands
- asyncregister_application_commands
- asyncregister_new_application_commands
- defremove_application_command_check
- defremove_listener
- defremove_modal
- defremove_view
- defrun
- defslash_command
- asyncstart
- asyncsync_all_application_commands
- asyncsync_application_commands
- defuser_command
- defviews
- asyncwait_for
- asyncwait_until_ready
- class nextcord.Client(*, max_messages=1000, connector=None, proxy=None, proxy_auth=None, shard_id=None, shard_count=None, application_id=None, intents=<Intents value=3243773>, member_cache_flags=..., chunk_guilds_at_startup=..., status=None, activity=None, allowed_mentions=None, heartbeat_timeout=60.0, guild_ready_timeout=2.0, assume_unsync_clock=True, enable_debug_events=False, loop=None, lazy_load_commands=True, rollout_associate_known=True, rollout_delete_unknown=True, rollout_register_new=True, rollout_update_known=True, rollout_all_guilds=False, default_guild_ids=None)¶
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 inNonedisables 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.AbstractEventLoopto use for asynchronous operations. Defaults toNone, in which case the default event loop is used viaasyncio.get_running_loop()orasyncio.new_event_loop().connector (Optional[
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 at0and less thanshard_count.shard_count (Optional[
int]) – The total number of shards.application_id (Optional[
int]) – The client’s application ID.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 constructed
Intentsclass.Added in version 1.5.
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.
Added in version 1.5.
chunk_guilds_at_startup (
bool) –Indicates if
on_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 isTrueifIntents.membersisTrue.Added in version 1.5.
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.
Added in version 1.4.
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.
Added in version 1.4.
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 isFalsethen your system clock is used to calculate how long to sleep for. If this is set toFalseit is recommended to sync your system clock to Google’s NTP server.Added in version 1.3.
enable_debug_events (
bool) –Whether to enable events that are useful only for debugging gateway related information.
Right now this involves
on_socket_raw_receive()andon_socket_raw_send(). If this isFalsethen those events will not be dispatched (due to performance considerations). To enable these events, this must be set toTrue. Defaults toFalse.Added in version 2.0.
lazy_load_commands (
bool) –Whether to attempt to associate an unknown incoming application command ID with an existing application command.
If this is set to
True, the default, then the library will attempt to match up an unknown incoming application command payload to an application command in the library.rollout_associate_known (
bool) – Whether during the application command rollout to associate found Discord commands with commands added locally. Defaults toTrue.rollout_delete_unknown (
bool) – Whether during the application command rollout to delete commands from Discord that don’t correspond with a locally added command. Defaults toTrue.rollout_register_new (
bool) – Whether during the application command rollout to register new application commands that were added locally but not found on Discord. Defaults toTrue.rollout_update_known (
bool) – Whether during the application command rollout to update known applications that share the same signature but don’t quite match what is registered on Discord. Defaults toTrue.rollout_all_guilds (
bool) –Whether during the application command rollout to update to all guilds, instead of only ones with at least one command to roll out to them. Defaults to
FalseWarning: While enabling this will prevent “ghost” commands on guilds with removed code references, rolling out to ALL guilds with anything other than a very small bot will likely cause it to get rate limited.
default_guild_ids (Optional[List[
int]]) –The default guild ids for every application command set. If the application command doesn’t have any explicit guild ids set and this list is not empty, then the application command’s guild ids will be set to this. Defaults to
None.Added in version 2.3.
- ws¶
The websocket gateway the client is currently connected to. Could be
None.
- loop¶
The event loop that the client uses for asynchronous operations.
- @event¶
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,
TypeErroris raised.Example
@client.event async def on_ready(): print('Ready!')
- Raises:
TypeError – The coroutine passed is not actually a coroutine.
- @slash_command(name=None, description=None, *, name_localizations=None, description_localizations=None, guild_ids=..., nsfw=False, default_member_permissions=None, integration_types=None, contexts=None, force_global=False)¶
Creates a Slash application command from the decorated function.
- Parameters:
name (
str) – Name of the command that users will see. If not set, it defaults to the name of the callback.description (
str) – Description of the command that users will see. If not set, the docstring will be used. If no docstring is found for the command callback, it defaults to “No description provided”.name_localizations (Dict[Union[
Locale,str],str]) – Name(s) of the command for users of specific locales. The locale code should be the key, with the localized name as the value.description_localizations (Dict[Union[
Locale,str],str]) – Description(s) of the command for users of specific locales. The locale code should be the key, with the localized description as the value.guild_ids (Optional[Iterable[
int]]) – IDs ofGuild’s to add this command to. If not passed andClient.default_guild_idsis set, then those default guild ids will be used instead. If both of those are unset, then the command will be a global command.default_member_permissions (Optional[Union[
Permissions,int]]) – Permission(s) required to use the command. Inputting8orPermissions(administrator=True)for example will only allow Administrators to use the command. If set to 0, nobody will be able to use it by default. Server owners CAN override the permission requirements.nsfw (
bool) –Whether the command can only be used in age-restricted channels. Defaults to
False.Added in version 2.4.
integration_types (Optional[Iterable[Union[
IntegrationType,int]]]) –Where the command is available, only for globally-scoped commands. Defaults to
guild_install.Added in version 3.0.
contexts (Optional[Iterable[Union[
InteractionContextType,int]]]) –Where the command can be used, only for globally-scoped commands. By default, all interaction context types included for new commands.
Added in version 3.0.
force_global (
bool) – If True, will force this command to register as a global command, even ifguild_idsis set. Will still register to guilds. Has no effect ifguild_idsare never set or added to.
- @user_command(name=None, *, name_localizations=None, guild_ids=..., default_member_permissions=None, nsfw=False, integration_types=None, contexts=None, force_global=False)¶
Creates a User context command from the decorated function.
- Parameters:
name (
str) – Name of the command that users will see. If not set, it defaults to the name of the callback.name_localizations (Dict[Union[
Locale,str],str]) – Name(s) of the command for users of specific locales. The locale code should be the key, with the localized name as the valueguild_ids (Optional[Iterable[
int]]) – IDs ofGuild’s to add this command to. If not passed andClient.default_guild_idsis set, then those default guild ids will be used instead. If both of those are unset, then the command will be a global command.default_member_permissions (Optional[Union[
Permissions,int]]) – Permission(s) required to use the command. Inputting8orPermissions(administrator=True)for example will only allow Administrators to use the command. If set to 0, nobody will be able to use it by default. Server owners CAN override the permission requirements.nsfw (
bool) –Whether the command can only be used in age-restricted channels. Defaults to
False.Added in version 2.4.
integration_types (Optional[Iterable[Union[
IntegrationType,int]]]) –Where the command is available, only for globally-scoped commands. Defaults to
guild_install.Added in version 3.0.
contexts (Optional[Iterable[Union[
InteractionContextType,int]]]) –Where the command can be used, only for globally-scoped commands. By default, all interaction context types included for new commands.
Added in version 3.0.
force_global (
bool) – If True, will force this command to register as a global command, even ifguild_idsis set. Will still register to guilds. Has no effect ifguild_idsare never set or added to.
- @message_command(name=None, *, name_localizations=None, guild_ids=..., default_member_permissions=None, nsfw=False, integration_types=None, contexts=None, force_global=False)¶
Creates a Message context command from the decorated function.
- Parameters:
name (
str) – Name of the command that users will see. If not set, it defaults to the name of the callback.name_localizations (Dict[Union[
Locale,str],str]) – Name(s) of the command for users of specific locales. The locale code should be the key, with the localized name as the valueguild_ids (Optional[Iterable[
int]]) – IDs ofGuild’s to add this command to. If not passed andClient.default_guild_idsis set, then those default guild ids will be used instead. If both of those are unset, then the command will be a global command.default_member_permissions (Optional[Union[
Permissions,int]]) – Permission(s) required to use the command. Inputting8orPermissions(administrator=True)for example will only allow Administrators to use the command. If set to 0, nobody will be able to use it by default. Server owners CAN override the permission requirements.nsfw (
bool) –Whether the command can only be used in age-restricted channels. Defaults to
False.Added in version 2.4.
integration_types (Optional[Iterable[Union[
IntegrationType,int]]]) –Where the command is available, only for globally-scoped commands. Defaults to
guild_install.Added in version 3.0.
contexts (Optional[Iterable[Union[
InteractionContextType,int]]]) –Where the command can be used, only for globally-scoped commands. By default, all interaction context types included for new commands.
Added in version 3.0.
force_global (
bool) – If True, will force this command to register as a global command, even ifguild_idsis set. Will still register to guilds. Has no effect ifguild_idsare never set or added to.
- async for ... in fetch_guilds(*, limit=200, with_counts=False, before=None, after=None)¶
This function returns an async iterator.
Returns an async iterator that enables receiving your guilds.
Note
Using this, you will only receive
Guild.owner,Guild.icon,Guild.id, andGuild.nameperGuild.Note
This method is an API call. For general usage, consider
guildsinstead.Examples
Usage
async for guild in client.fetch_guilds(limit=150): print(guild.name)
All parameters are optional.
- Parameters:
limit (Optional[
int]) –The number of guilds to retrieve. If
None, it retrieves every guild you have access to. Note, however, that this would make it a slow operation. Defaults to200.Changed in version 2.0: Changed default to
200.with_counts (
bool) –Whether to include approximate member and presence counts for the guilds. Defaults to
False.Added in version 2.6.
before (Union[
abc.Snowflake,datetime.datetime]) – Retrieves guilds before this date or object. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.after (Union[
abc.Snowflake,datetime.datetime]) – Retrieve guilds after this date or object. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.
- 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.
Added in version 1.6.
- property user¶
Represents the connected client.
Noneif not logged in.- Type:
Optional[
ClientUser]
- property stickers¶
The stickers that the connected client has.
Added in version 2.0.
- Type:
List[
GuildSticker]
- property cached_messages¶
Read-only list of messages the connected client has cached.
Added 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
VoiceClientinstances.- Type:
List[
VoiceProtocol]
- property application_id¶
The client’s application ID.
If this is not passed via
__init__then this is retrieved through the gateway when an event contains the data. Usually afteron_connect()is called.Added in version 2.0.
- Type:
Optional[
int]
- property application_flags¶
The client’s application flags.
Added in version 2.0.
- Type:
- property default_guild_ids¶
List[
int] The default guild ids for all application commands.Added in version 2.3.
- 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
stderrhowever it could be overridden to have a different implementation. Checkon_error()for more details.
- await on_application_command_error(interaction, exception)¶
This function is a coroutine.
The default application command error handler provided by the bot.
By default this prints to
stderrhowever it could be overridden to have a different implementation.This only fires if you do not specify any listeners for command error.
- 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.
Added in version 1.4.
- await login(token)¶
This function is a coroutine.
Logs in the client with the specified credentials.
- 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 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 clear()¶
Clears the internal state of the bot.
After this, the bot can be considered “re-opened”, i.e.
is_closed()andis_ready()both returnFalsealong 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)¶
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()
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.
- property activity¶
The activity being used upon logging in.
- Type:
Optional[
BaseActivity]
- property allowed_mentions¶
The allowed mention configuration.
Added in version 1.4.
- Type:
Optional[
AllowedMentions]
- get_channel(id, /)¶
Returns a channel or thread with the given ID.
- Parameters:
id (
int) – The ID to search for.- Returns:
The returned channel or
Noneif not found.- Return type:
Optional[Union[
abc.GuildChannel,Thread,abc.PrivateChannel]]
- get_partial_messageable(id, *, type=None)¶
Returns a partial messageable with the given channel ID.
This is useful if you have a channel_id but don’t want to do an API call to send messages to it.
Added in version 2.0.
- Parameters:
id (
int) – The channel ID to create a partial messageable for.type (Optional[
ChannelType]) – The underlying channel type for the partial messageable.
- Returns:
The partial messageable
- Return type:
- get_stage_instance(id, /)¶
Returns a stage instance with the given stage channel ID.
Added in version 2.0.
- Parameters:
id (
int) – The ID to search for.- Returns:
The returns stage instance of
Noneif not found.- Return type:
Optional[
StageInstance]
- get_guild(id, /)¶
Returns a guild with the given ID.
- get_user(id, /)¶
Returns a user with the given ID.
- get_emoji(id, /)¶
Returns an emoji with the given ID.
- get_sticker(id, /)¶
Returns a guild sticker with the given ID.
Added in version 2.0.
Note
To retrieve standard stickers, use
fetch_sticker(). orfetch_premium_sticker_packs().- Returns:
The sticker or
Noneif not found.- Return type:
Optional[
GuildSticker]
- get_scheduled_event(id, /)¶
Returns a scheduled event with the given ID.
Added in version 2.0.
- Parameters:
id (
int) – The scheduled event’s ID to search for.- Returns:
The scheduled event or
Noneif not found.- Return type:
Optional[
ScheduledEvent]
- get_all_channels()¶
A generator that retrieves every
abc.GuildChannelthe 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.GuildChanneldoes 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’.
- get_all_members()¶
Returns a generator with every
Memberthe 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
timeoutparameter is passed ontoasyncio.wait_for(). By default, it does not timeout. Note that this does propagate theasyncio.TimeoutErrorfor you in case of timeout and is provided for ease of use.In case the event returns multiple arguments, a
tuplecontaining 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(f'Hello {msg.author}!')
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
tupleof multiple arguments that mirrors the parameters passed in the event reference.- Return type:
Any
- add_listener(func, name=...)¶
The non decorator alternative to
listen().Added in version 3.0.
- Parameters:
Example
async def on_ready(): pass async def my_message(message): pass client.add_listener(on_ready) client.add_listener(my_message, 'on_message')
- remove_listener(func, name=...)¶
Removes a listener from the pool of listeners.
Added in version 3.0.
- Parameters:
func – The function that was used as a listener to remove.
name (
str) – The name of the event we want to remove. Defaults tofunc.__name__.
- listen(name=...)¶
A decorator that registers another function as an external event listener. Basically this allows you to listen to multiple events from different places e.g. such as
on_ready()The functions being listened to must be a coroutine.
Added in version 3.0.
Example
@client.listen() async def on_message(message): print('one') # in some other file... @client.listen('on_message') async def my_message(message): print('two')
Would print one and two in an unspecified order.
- Raises:
TypeError – The function being listened to is not a coroutine.
- await change_presence(*, activity=None, status=None)¶
This function is a coroutine.
Changes the client’s presence.
Example
game = nextcord.Game("with the API") await client.change_presence(status=nextcord.Status.idle, activity=game)
Changed in version 2.0: Removed the
afkkeyword-only parameter.- Parameters:
activity (Optional[
BaseActivity]) – The activity being done.Noneif no currently active activity is done.status (Optional[
Status]) – Indicates what status to change to. IfNone, thenStatus.onlineis used.
- Raises:
.InvalidArgument – If the
activityparameter is not the proper type.
- await fetch_template(code)¶
This function is a coroutine.
Gets a
Templatefrom a discord.new URL or code.
- await fetch_guild(guild_id, /, *, with_counts=True)¶
This function is a coroutine.
Retrieves a
Guildfrom an ID.Note
Using this, you will not receive
Guild.channels,Guild.members,Member.activityandMember.voiceperMember.Note
This method is an API call. For general usage, consider
get_guild()instead.- Parameters:
guild_id (
int) – The guild’s ID to fetch from.with_counts (
bool) –Whether to include count information in the guild. This fills the
Guild.approximate_member_countandGuild.approximate_presence_countattributes without needing any privileged intents. Defaults toTrue.Added in version 2.0.
- Raises:
.Forbidden – You do not have access to the guild.
.HTTPException – Getting the guild failed.
- Returns:
The guild from the ID.
- Return type:
- await fetch_guild_preview(guild_id, /)¶
This function is a coroutine.
Fetches a
GuildPreviewfrom an ID.Note
This will only fetch guilds that the bot is in or that are discoverable.
Added in version 2.6.
- Parameters:
guild_id (
int) – The guild’s ID to fetch from.- Raises:
.NotFound – The guild provided is unknown.
- Returns:
The guild preview from the ID
- Return type:
- await create_guild(*, name, region=VoiceRegion.us_west, icon=None, code=...)¶
This function is a coroutine.
Creates a
Guild.Bot accounts in more than 10 guilds are not allowed to create guilds.
Changed in version 2.1: The
iconparameter now acceptsFile,Attachment, andAsset.- Parameters:
name (
str) – The name of the guild.region (
VoiceRegion) – The region for the voice communication server. Defaults toVoiceRegion.us_west.icon (Optional[Union[
bytes,Asset,Attachment,File]]) – The bytes-like object,File,Attachment, orAssetrepresenting the icon. SeeClientUser.edit()for more details on what is expected.code (
str) –The code for a template to create the guild with.
Added 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_stage_instance(channel_id, /)¶
This function is a coroutine.
Gets a
StageInstancefor a stage channel id.Added in version 2.0.
- Parameters:
channel_id (
int) – The stage channel ID.- Raises:
.NotFound – The stage instance or channel could not be found.
.HTTPException – Getting the stage instance failed.
- Returns:
The stage instance from the stage channel ID.
- Return type:
- await fetch_invite(url, *, with_counts=True, with_expiration=True)¶
This function is a coroutine.
Gets an
Invitefrom 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
Invitewill bePartialInviteGuildandPartialInviteChannelrespectively.- 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_countandInvite.approximate_presence_countfields.with_expiration (
bool) –Whether to include the expiration date of the invite. This fills the
Invite.expires_atfield.Added in version 2.0.
- 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_channelspermission in the associated guild to do this.
- await fetch_widget(guild_id, /)¶
This function is a coroutine.
Gets a
Widgetfrom 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
Userbased on their ID. 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
nextcord.Intents.membersand member cache enabled, considerget_user()instead.
- await fetch_channel(channel_id, /)¶
This function is a coroutine.
Retrieves a
abc.GuildChannel,abc.PrivateChannel, orThreadwith the specified ID.Note
This method is an API call. For general usage, consider
get_channel()instead.Added 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,Thread]
- await fetch_webhook(webhook_id, /)¶
This function is a coroutine.
Retrieves a
Webhookwith 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_sticker(sticker_id, /)¶
This function is a coroutine.
Retrieves a
Stickerwith the specified ID.Added in version 2.0.
- Raises:
.HTTPException – Retrieving the sticker failed.
.NotFound – Invalid sticker ID.
- Returns:
The sticker you requested.
- Return type:
Union[
StandardSticker,GuildSticker]
This function is a coroutine.
Retrieves all available premium sticker packs.
Added in version 2.0.
- Raises:
.HTTPException – Retrieving the sticker packs failed.
- Returns:
All available premium sticker packs.
- Return type:
List[
StickerPack]
- await create_dm(user)¶
This function is a coroutine.
Creates a
DMChannelwith this user.This should be rarely called, as this is done transparently for most people.
Added in version 2.0.
- add_view(view, *, message_id=None)¶
Registers a
Viewfor persistent listening or for non- persistent storage.This method should be used for when a view is comprised of components that last longer than the lifecycle of the program.
Added in version 2.0.
Changed in version 2.6: Non-persistent views can now be stored during the lifetime of the bot.
- Parameters:
view (
nextcord.ui.View) – The view to register for dispatching or to add to storage.message_id (Optional[
int]) – The message ID that the view is attached to. This is currently used to refresh the view’s state during message update events. If not given then message update events are not propagated for the view. This cannot be provided if the view is non-persistent.
- Raises:
TypeError – A view was not passed.
ValueError – The message_id parameter was passed in with a non-persistent view.
- remove_view(view, message_id=None)¶
Removes a
Viewfrom persistent listening or non-persistent storage.This method should be used if a persistent view is set in a cog and should be freed when the cog is unloaded to save memory or if you want to stop tracking a non-persistent view.
Added in version 2.3.
Changed in version 2.6: Non-persistent views can now be removed from storage.
- Parameters:
view (
nextcord.ui.View) – The view to remove from dispatching.message_id (Optional[
int]) – The message ID that the view is attached to. This is used to properly remove the view from the view store. This cannot be provided if the view is non-persistent.
- Raises:
TypeError – A view was not passed.
ValueError – The message_id parameter was passed in with a non-persistent view.
- add_modal(modal, *, user_id=None)¶
Registers a
Modalfor persistent listening.This method can be called for modals whose lifetime must be eventually superior to the one of the program or for modals whose call does not depend on particular criteria.
- Parameters:
modal (
nextcord.ui.Modal) – The view to register for dispatching.user_id (Optional[
int]) – The user ID that the view is attached to. This is used to filter the modal calls based on the users.
- Raises:
TypeError – A modal was not passed.
ValueError – The modal is not persistent. A persistent modal has a set custom_id and all their components with a set custom_id and a timeout set to None.
- remove_modal(modal)¶
Removes a
Modalfrom persistent listening.This method should be used if a persistent modal is set in a cog and should be freed when the cog is unloaded to save memory.
Added in version 2.3.
- Parameters:
modal (
nextcord.ui.Modal) – The modal to remove from dispatching.- Raises:
TypeError – A modal was not passed.
ValueError – The modal is not persistent. A persistent modal has a set custom_id and all their components with a set custom_id and a timeout set to None.
- views(*, persistent=True)¶
Returns all persistent or non-persistent views.
Added in version 2.6.
- property scheduled_events¶
A list of scheduled events
Added in version 2.0.
- Type:
List[ScheduledEvent]
- await process_application_commands(interaction)¶
This function is a coroutine. Processes the data in the given interaction and calls associated applications or autocomplete if possible. Lazy-loads commands if enabled.
- Parameters:
interaction (
Interaction) – Interaction from Discord to read data from.
- get_application_command(command_id)¶
Gets an application command from the cache that has the given command ID.
- Parameters:
command_id (
int) – Command ID corresponding to an application command.- Returns:
Returns the application command corresponding to the ID. If no command is found,
Noneis returned instead.- Return type:
Optional[
BaseApplicationCommand]
- get_application_command_from_signature(qualified_name, *, type=ApplicationCommandType.chat_input, guild=None, search_localizations=False)¶
Gets a locally stored application command object that matches the given signature.
Added in version 2.0.
Changed in version 3.0: - Subcommands/Subcommand groups can now be retrieved with this method. -
nameparameter was renamed toqualified_nameand now accepts subcommands/subcommand groups separated by a space. -cmd_typeparameter was renamed totype, defaults toApplicationCommandType.chat_inputand is now a keyword-only parameter. -guild_idparameter was renamed toguildwith type Union[int,Snowflake], defaults toNoneand is now a keyword-only parameter.- Parameters:
qualified_name (
str) – Full name of the application command. Case sensitive. Subcommands must be separated by a space, E.g,parent group subcommand.type (Union[
int,ApplicationCommandType]) – Type of application command. Defaults toApplicationCommandType.chat_input.guild (Optional[Union[
int,Snowflake]]) – Guild ID of the signature. If set toNone, it will attempt to get the global signature. Defaults toNone.search_localizations (
bool) –Whether to also search through the command’s
name_localizations. Defaults toFalse.Added in version 3.0.
- Returns:
command – Application Command with the given signature. If no command with that signature is found,
Noneis returned instead.- Return type:
Optional[
BaseApplicationCommand,SlashApplicationSubcommand]
- get_all_application_commands()¶
Returns a copied set of all added
BaseApplicationCommandobjects.
- get_application_commands(rollout=False)¶
Gets registered global commands.
- Parameters:
rollout (
bool) – Whether unregistered/unassociated commands should be returned as well. Defaults toFalse- Returns:
List of
BaseApplicationCommandobjects that are global.- Return type:
List[
BaseApplicationCommand]
- add_application_command(command, overwrite=False, use_rollout=False, pre_remove=True)¶
Adds a BaseApplicationCommand object to the client for use.
- Parameters:
command (
ApplicationCommand) – Command to add to the client for usage.overwrite (
bool) – If to overwrite any existing commands that would conflict with this one. Defaults toFalseuse_rollout (
bool) – If to apply the rollout signatures instead of existing ones. Defaults toFalsepre_remove (
bool) – If the command should be removed before adding it. This will clear all signatures from storage, including rollout ones.
- await sync_all_application_commands(data=None, *, use_rollout=True, associate_known=True, delete_unknown=True, update_known=True, register_new=True, ignore_forbidden=True)¶
This function is a coroutine.
Syncs all application commands with Discord. Will sync global commands if any commands added are global, and syncs with all guilds that have an application command targeting them.
This may call Discord many times depending on how different guilds you have local commands for, and how many commands Discord needs to be updated or added, which may cause your bot to be rate limited or even Cloudflare banned in VERY extreme cases.
This may incur high CPU usage depending on how many commands you have and how complex they are, which may cause your bot to halt while it checks local commands against the existing commands that Discord has.
For a more targeted version of this method, see
Client.sync_application_commands()- Parameters:
data (Optional[Dict[Optional[
int], List[dict]]]) – Data to use when comparing local application commands to what Discord has. The key should be theintguild ID (None for global) corresponding to the value list of application command payloads from Discord. Any guild ID’s not provided will be fetched if needed. Defaults toNoneuse_rollout (
bool) – If the rollout guild IDs of commands should be used. Defaults toTrueassociate_known (
bool) – If local commands that match a command already on Discord should be associated with each other. Defaults toTruedelete_unknown (
bool) – If commands on Discord that don’t match a local command should be deleted. Defaults toTrueupdate_known (
bool) – If commands on Discord have a basic match with a local command, but don’t fully match, should be updated. Defaults toTrueregister_new (
bool) – If a local command that doesn’t have a basic match on Discord should be added to Discord. Defaults toTrueignore_forbidden (
bool) – If this command should suppress aerrors.Forbiddenexception when the bot encounters a guild where it doesn’t have permissions to view application commands. Defaults toTrue
- await sync_application_commands(data=None, *, guild_id=None, associate_known=True, delete_unknown=True, update_known=True, register_new=True)¶
This function is a coroutine. Syncs the locally added application commands with the Guild corresponding to the given ID, or syncs global commands if the guild_id is
None.Changed in version 3.0: This replaces the now removed
delete_unknown_application_commands,associate_application_commands,update_application_commands, androllout_application_commandsmethods.- Parameters:
data (Optional[List[
dict]]) – Data to use when comparing local application commands to what Discord has. Should be a list of application command data from Discord. If left asNone, it will be fetched if needed. Defaults toNone.guild_id (Optional[
int]) – ID of the guild to sync application commands with. If set toNone, global commands will be synced instead. Defaults toNone.associate_known (
bool) – If local commands that match a command already on Discord should be associated with each other. Defaults toTrue.delete_unknown (
bool) – If commands on Discord that don’t match a local command should be deleted. Defaults toTrue.update_known (
bool) – If commands on Discord have a basic match with a local command, but don’t fully match, should be updated. Defaults toTrue.register_new (
bool) – If a local command that doesn’t have a basic match on Discord should be added to Discord. Defaults toTrue.
- await discover_application_commands(data=None, *, guild_id=None, associate_known=True, delete_unknown=True, update_known=True)¶
This function is a coroutine. Associates existing, deletes unknown, and updates modified commands for either global commands or a specific guild. This does a deep check on found commands, which may be expensive CPU-wise.
Running this for global or the same guild multiple times at once may cause unexpected or unstable behavior.
Changed in version 3.0: This replaces the now removed
deploy_application_commandsmethod.- Parameters:
data (Optional[List[
dict]]) – Payload fromHTTPClient.get_guild_commandsorHTTPClient.get_global_commandsto deploy with. If None, the payload will be retrieved from Discord.guild_id (Optional[
int]) – Guild ID to deploy application commands to. IfNone, global commands are deployed to.associate_known (
bool) – If True, commands on Discord that pass a signature check and a deep check will be associated with locally added ApplicationCommand objects.delete_unknown (
bool) – IfTrue, commands on Discord that fail a signature check will be removed. Ifupdate_knownisFalse, commands that pass the signature check but fail the deep check will also be removed.update_known (
bool) – IfTrue, commands on Discord that pass a signature check but fail the deep check will be updated.
- await register_new_application_commands(data=None, guild_id=None)¶
This function is a coroutine. Registers locally added application commands that don’t match a signature that Discord has registered for either global commands or a specific guild.
- Parameters:
data (Optional[List[
dict]]) – Data to use when comparing local application commands to what Discord has. Should be a list of application command data from Discord. If left asNone, it will be fetched if needed. Defaults toNoneguild_id (Optional[
int]) – ID of the guild to sync application commands with. If set toNone, global commands will be synced instead. Defaults toNone.
- await register_application_commands(*commands, guild_id=None)¶
This function is a coroutine. Registers the given application commands either for a specific guild or globally, and adds the commands to the bot.
- Parameters:
commands (
BaseApplicationCommand) – Application command to register. Multiple args are accepted.guild_id (Optional[
int]) – ID of the guild to register the application commands to. If set toNone, the commands will be registered as global commands instead. Defaults toNone.
- await delete_application_commands(*commands, guild_id=None)¶
This function is a coroutine. Deletes the given application commands either from a specific guild or globally, and removes the command IDs + signatures from the bot.
- Parameters:
commands (
BaseApplicationCommand) – Application command to delete. Multiple args are accepted.guild_id (Optional[
int]) – ID of the guild to delete the application commands from. If set toNone, the commands will be deleted from global commands instead. Defaults toNone.
- add_all_application_commands()¶
Adds application commands that are either decorated by the Client or added via a cog to the state. This does not register commands with Discord. If you want that, use
sync_all_application_commands()instead.Changed in version 3.0: This replaces the now removed
add_startup_application_commandsmethod.
- add_all_cog_commands()¶
Adds all
ApplicationCommandobjects inside added cogs to the application command list.
- parse_mentions(text)¶
Parses user mentions in a string and returns a list of
Userobjects.Note
This does not include role or channel mentions. See
Guild.parse_mentionsforMemberobjects,Guild.parse_role_mentionsforRoleobjects, andGuild.parse_channel_mentionsforGuildChannelobjects.Note
Only cached users will be returned. To get the IDs of all users mentioned, use
parse_raw_mentions()instead.Added in version 2.2.
- get_interaction(data, *, cls=<class 'nextcord.interactions.Interaction'>)¶
Returns an interaction for a gateway event.
- Parameters:
data – The data direct from the gateway.
cls – The factory class that will be used to create the interaction. By default, this is
Interaction. Should a custom class be provided, it should be a subclass ofInteraction.
- Returns:
Interaction – An instance
Interactionor the provided subclass... note:: – This is synchronous due to how slash commands are implemented.
- add_application_command_check(func)¶
Adds a global application command check to the client.
This is the non-decorator interface to
application_command_check().- Parameters:
func (Callable[[
Interaction],MaybeCoro[bool]]]) – The function that was used as a global application check.
- remove_application_command_check(func)¶
Removes a global application command check from the client.
This function is idempotent and will not raise an exception if the function is not in the global checks.
- Parameters:
func (Callable[[
Interaction],MaybeCoro[bool]]]) – The function to remove from the global application checks.
- application_command_check(func)¶
A decorator that adds a global applications command check to the client.
A global check is similar to a
check()that is applied on a per command basis except it is run before any command checks have been verified and applies to every application command the client has.Note
This function can either be a regular function or a coroutine.
Similar to a application command
check(), this takes a single parameter of typeInteractionand can only raise exceptions inherited fromApplicationError.Example
@client.application_command_check def check_commands(interaction: Interaction) -> bool: return interaction.application_command.qualified_name in allowed_commands
- application_command_before_invoke(coro)¶
A decorator that registers a coroutine as a pre-invoke hook.
A pre-invoke hook is called directly before the command is called. This makes it a useful function to set up database connections or any type of set up required.
This pre-invoke hook takes a sole parameter, a
Interaction.Note
The
application_command_before_invoke()andapplication_command_after_invoke()hooks are only called if all checks pass without error. If any check fails, then the hooks are not called.
- application_command_after_invoke(coro)¶
A decorator that registers a coroutine as a post-invoke hook.
A post-invoke hook is called directly after the command is called. This makes it a useful function to clean-up database connections or any type of clean up required. There may only be one global post-invoke hook.
This post-invoke hook takes a sole parameter, a
Interaction.Note
Similar to
application_command_before_invoke(), this is not called unless checks succeed. This hook is, however, always called regardless of the internal command callback raising an error (i.e.ApplicationInvokeError). This makes it ideal for clean-up scenarios.
- await create_application_emoji(*, name, image)¶
This function is a coroutine.
Creates an emoji for the current application.
- Parameters:
name (
str) – The name of the emoji.image (Union[
bytes,Asset,Attachment,File]) – The image data to create the emoji with.
- Returns:
The created emoji.
- Return type:
- Raises:
HTTPException – An error occurred creating the emoji.
TypeError – The client’s application ID was not set.
- await fetch_application_emojis()¶
This function is a coroutine.
Fetches the emojis that the current application has.
AutoShardedClient¶
- asyncchange_presence
- asyncclose
- asyncconnect
- defget_shard
- defis_ws_ratelimited
- class nextcord.AutoShardedClient(*, shard_ids=None, max_messages=1000, connector=None, proxy=None, proxy_auth=None, shard_id=None, shard_count=None, application_id=None, intents=<Intents value=3243773>, member_cache_flags=..., chunk_guilds_at_startup=..., status=None, activity=None, allowed_mentions=None, heartbeat_timeout=60.0, guild_ready_timeout=2.0, assume_unsync_clock=True, enable_debug_events=False, loop=None, lazy_load_commands=True, rollout_associate_known=True, rollout_delete_unknown=True, rollout_register_new=True, rollout_update_known=True, rollout_all_guilds=False, default_guild_ids=None)¶
A client similar to
Clientexcept 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
Clientwith 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_countis provided, then the library will use the Bot Gateway endpoint call to figure out how many shards to use.If a
shard_idsparameter is given, then those shard IDs will be used to launch the internal shards. Note thatshard_countmust be provided if this is used. By default, when omitted, the client will launch shards from 0 toshard_count - 1.- 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 thelatenciesproperty. Returnsnanif 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 orNoneif not found.
- property shards¶
Returns a mapping of shard IDs to their respective info object.
- Type:
Mapping[int,
ShardInfo]
- 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 change_presence(*, activity=None, status=None, shard_id=None)¶
This function is a coroutine.
Changes the client’s presence.
Example:
game = nextcord.Game("with the API") await client.change_presence(status=nextcord.Status.idle, activity=game)
Changed in version 2.0: Removed the
afkkeyword-only parameter.- Parameters:
activity (Optional[
BaseActivity]) – The activity being done.Noneif no currently active activity is done.status (Optional[
Status]) – Indicates what status to change to. IfNone, thenStatus.onlineis used.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
activityparameter 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().Added in version 1.6.
Application Info¶
InstallParams¶
ApplicationIntegrationTypeConfig¶
AppInfo¶
- class nextcord.AppInfo¶
Represents the application info for the bot provided by Discord.
- 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:
- verify_key¶
The hex encoded key for verification in interactions and the GameSDK’s GetTicket.
Added in version 1.3.
- Type:
- terms_of_service_url¶
The application’s terms of service URL, if set.
Added in version 2.0.
- Type:
Optional[
str]
- privacy_policy_url¶
The application’s privacy policy URL, if set.
Added in version 2.0.
- Type:
Optional[
str]
- integration_types_config¶
The default scopes and permissions for each supported installation context.
Added in version 3.0.
- Type:
Optional[Dict[
IntegrationType,ApplicationIntegrationTypeConfig]]
PartialAppInfo¶
- class nextcord.PartialAppInfo¶
Represents a partial AppInfo given by
create_invite()Added in version 2.0.
Team¶
- class nextcord.Team¶
Represents an application team for a bot provided by Discord.
- members¶
A list of the members in the team
Added in version 1.3.
- Type:
List[
TeamMember]
- property owner¶
The team’s owner.
- Type:
Optional[
TeamMember]
TeamMember¶
- class nextcord.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.
Added in version 1.3.
- discriminator¶
The team member’s discriminator. This is given when the username has conflicts.
- Type:
- membership_state¶
The membership state of the member (e.g. invited or accepted)
- Type:
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 nextcord
class MyClient(nextcord.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. To turn a function into a coroutine, they must be async def
functions.
- nextcord.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.
- nextcord.on_shard_connect(shard_id)¶
Similar to
on_connect()except used byAutoShardedClientto denote when a particular shard ID has connected to Discord.Added in version 1.4.
- Parameters:
shard_id (
int) – The shard ID that has connected.
- nextcord.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.
- nextcord.on_shard_disconnect(shard_id)¶
Similar to
on_disconnect()except used byAutoShardedClientto denote when a particular shard ID has disconnected from Discord.Added in version 1.4.
- Parameters:
shard_id (
int) – The shard ID that has disconnected.
- nextcord.on_http_ratelimit(limit, remaining, reset_after, bucket, scope)¶
Called when a HTTP request in progress either exhausts its bucket or gets a 429 response. For more information on how a ratelimit bucket is defined, check out the [Discord API Docs](https://discord.dev/topics/rate-limits).
If the 429 response is a global ratelimit, then use
on_global_http_ratelimit()instead.Added in version 2.4.
- Parameters:
limit (
int) – The amount of requests that have been made under the bucket that the request correlates to.remaining (
int) – The amount of remaining requests that can be made under the bucket that the request correlates to.reset_after (
float) – The amount of time we have to wait before making another request under the same bucket.bucket (
str) – The hash correlating to the bucket of the request from Discord. This hash denotes the rate limit being encountered.scope (Optional[
str]) – If we get a 429, the scope of the 429 response. This value can either be “user” (rate limit relating to the user) or “shared” (rate limit relating to a resource).
- nextcord.on_global_http_ratelimit(retry_after)¶
Called when a HTTP request in progress gets a 429 response and the scope is global.
If the 429 response is a non-global ratelimit or you want to track when the bucket expires, then use
on_http_ratelimit()instead.Added in version 2.4.
- Parameters:
retry_after (
float) – The amount of time we have to wait before making another request.
- nextcord.on_ready()¶
Called when the client is done preparing the data received from Discord. Usually after login is successful and the
Client.guildsand 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.
- nextcord.on_shard_ready(shard_id)¶
Similar to
on_ready()except used byAutoShardedClientto denote when a particular shard ID has become ready.- Parameters:
shard_id (
int) – The shard ID that is ready.
- nextcord.on_resumed()¶
Called when the client has resumed a session.
- nextcord.on_shard_resumed(shard_id)¶
Similar to
on_resumed()except used byAutoShardedClientto denote when a particular shard ID has resumed a session.Added in version 1.4.
- Parameters:
shard_id (
int) – The shard ID that has resumed.
- nextcord.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
Clientclass you can define anon_errorhandler consisting of a single empty raise statement. Exceptions raised byon_errorwill not be handled in any way byClient.Note
on_errorwill 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.
- nextcord.on_close()¶
Called when the client is exiting the event loop and shutting down.
- nextcord.on_socket_event_type(event_type)¶
Called whenever a websocket event is received from the WebSocket.
This is mainly useful for logging how many events you are receiving from the Discord gateway.
Added in version 2.0.
- Parameters:
event_type (
str) – The event type from Discord that is received, e.g.'READY'.
- nextcord.on_socket_raw_receive(msg)¶
Called whenever a message is completely received from the WebSocket, before it’s processed and parsed. This event is always dispatched when a complete message is received and the passed data is not parsed in any way.
This is only really useful for grabbing the WebSocket stream and debugging purposes.
This requires setting the
enable_debug_eventssetting in theClient.Note
This is only for the messages received from the client WebSocket. The voice WebSocket will not trigger this event.
- Parameters:
msg (
str) – The message passed in from the WebSocket library.
- nextcord.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.
This requires setting the
enable_debug_eventssetting in theClient.Note
This is only for the messages sent from the client WebSocket. The voice WebSocket will not trigger this event.
- nextcord.on_typing(channel, user, when)¶
Called when someone begins typing a message.
The
channelparameter can be aabc.Messageableinstance. Which could either beTextChannel,GroupChannel, orDMChannel.If the
channelis aTextChannelthen theuserparameter is aMember, otherwise it is aUser.This requires
Intents.typingto be enabled.- Parameters:
channel (
abc.Messageable) – The location where the typing originated from.when (
datetime.datetime) – When the typing started as an aware datetime in UTC.
- nextcord.on_raw_typing(payload)¶
Called when someone begins typing a message. Unlike
on_typing(), this is called regardless if the user can be found in the bot’s cache or not.If the typing event is occuring in a guild, the member that started typing can be accessed via
RawTypingEvent.memberThis requires
Intents.typingto be enabled.- Parameters:
payload (
RawTypingEvent) – The raw typing payload.
- nextcord.on_message(message)¶
Called when a
Messageis created and sent.This requires
Intents.messagesto 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
Botdoes not have this problem.- Parameters:
message (
Message) – The current message.
- nextcord.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
max_messagesparameter or use theon_raw_message_delete()event instead.This requires
Intents.messagesto be enabled.- Parameters:
message (
Message) – The deleted message.
- nextcord.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
max_messagesparameter or use theon_raw_bulk_message_delete()event instead.This requires
Intents.messagesto be enabled.- Parameters:
messages (List[
Message]) – The messages that have been deleted.
- nextcord.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_messageThis requires
Intents.messagesto be enabled.- Parameters:
payload (
RawMessageDeleteEvent) – The raw event payload data.
- nextcord.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_messagesThis requires
Intents.messagesto be enabled.- Parameters:
payload (
RawBulkMessageDeleteEvent) – The raw event payload data.
- nextcord.on_message_edit(before, after)¶
Called when a
Messagereceives 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
max_messagesparameter 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.messagesto be enabled.
- nextcord.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_messagewill return aMessageobject 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.messagesto be enabled.- Parameters:
payload (
RawMessageUpdateEvent) – The raw event payload data.
- nextcord.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
Messagebeing reacted, access it viaReaction.message.This requires
Intents.reactionsto be enabled.Note
This doesn’t require
Intents.memberswithin 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.
- nextcord.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.reactionsto be enabled.- Parameters:
payload (
RawReactionActionEvent) – The raw event payload data.
- nextcord.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.reactionsandIntents.membersto be enabled.Note
Consider using
on_raw_reaction_remove()if you need this and do not want to enable the members intent.
- nextcord.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.reactionsto be enabled.- Parameters:
payload (
RawReactionActionEvent) – The raw event payload data.
- nextcord.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.reactionsto be enabled.
- nextcord.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.reactionsto be enabled.- Parameters:
payload (
RawReactionClearEvent) – The raw event payload data.
- nextcord.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.reactionsto be enabled.Added in version 1.3.
- Parameters:
reaction (
Reaction) – The reaction that got cleared.
- nextcord.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.reactionsto be enabled.Added in version 1.3.
- Parameters:
payload (
RawReactionClearEmojiEvent) – The raw event payload data.
- nextcord.on_interaction(interaction)¶
Called when an interaction happened.
This currently happens due to slash command invocations or components being used.
Warning
This is a low level function that is not generally meant to be used. If you are working with components, consider using the callbacks associated with the
Viewinstead as it provides a nicer user experience.Added in version 2.0.
- Parameters:
interaction (
Interaction) – The interaction data.
- nextcord.on_private_channel_update(before, after)¶
Called whenever a private group DM is updated. e.g. changed name or topic.
This requires
Intents.messagesto be enabled.- Parameters:
before (
GroupChannel) – The updated group channel’s old info.after (
GroupChannel) – The updated group channel’s new info.
- nextcord.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 an aware datetime in UTC. Could beNone.
- nextcord.on_guild_channel_delete(channel)¶
- nextcord.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.guildsto be enabled.- Parameters:
channel (
abc.GuildChannel) – The guild channel that got created or deleted.
- nextcord.on_guild_channel_update(before, after)¶
Called whenever a guild channel is updated. e.g. changed name, topic, permissions.
This requires
Intents.guildsto be enabled.- Parameters:
before (
abc.GuildChannel) – The updated guild channel’s old info.after (
abc.GuildChannel) – The updated guild channel’s new info.
- nextcord.on_guild_channel_pins_update(channel, last_pin)¶
Called whenever a message is pinned or unpinned from a guild channel.
This requires
Intents.guildsto be enabled.- Parameters:
channel (Union[
TextChannel,Thread]) – The guild channel that had its pins updated.last_pin (Optional[
datetime.datetime]) – The latest message that was pinned as an aware datetime in UTC. Could beNone.
- nextcord.on_thread_create(thread)¶
Called when a thread is created.
Added in version 2.4.
- Parameters:
thread (
Thread) – The thread that got created.
- nextcord.on_thread_join(thread)¶
Called whenever a thread is joined or created.
Note that you can get the guild from
Thread.guild.This requires
Intents.guildsto be enabled.Note
This event is also called when a thread is created. To differentiate, use
on_thread_create()instead. This is done to avoid a breaking change in v2.Added in version 2.0.
- Parameters:
thread (
Thread) – The thread that got joined.
- nextcord.on_thread_remove(thread)¶
Called whenever a thread is removed. This is different from a thread being deleted.
Note that you can get the guild from
Thread.guild.This requires
Intents.guildsto be enabled.Warning
Due to technical limitations, this event might not be called as soon as one expects. Since the library tracks thread membership locally, the API only sends updated thread membership status upon being synced by joining a thread.
Added in version 2.0.
- Parameters:
thread (
Thread) – The thread that got removed.
- nextcord.on_thread_delete(thread)¶
Called whenever a thread is deleted.
Note that you can get the guild from
Thread.guild.This requires
Intents.guildsto be enabled.Added in version 2.0.
- Parameters:
thread (
Thread) – The thread that got deleted.
- nextcord.on_thread_member_join(member)¶
- nextcord.on_thread_member_remove(member)¶
Called when a
ThreadMemberleaves or joins aThread.You can get the thread a member belongs in by accessing
ThreadMember.thread.This requires
Intents.membersto be enabled.Added in version 2.0.
- Parameters:
member (
ThreadMember) – The member who joined or left.
- nextcord.on_thread_update(before, after)¶
Called whenever a thread is updated.
This requires
Intents.guildsto be enabled.Added in version 2.0.
- nextcord.on_guild_integrations_update(guild)¶
Called whenever an integration is created, modified, or removed from a guild.
This requires
Intents.integrationsto be enabled.Added in version 1.4.
- Parameters:
guild (
Guild) – The guild that had its integrations updated.
- nextcord.on_integration_create(integration)¶
Called when an integration is created.
This requires
Intents.integrationsto be enabled.Added in version 2.0.
- Parameters:
integration (
Integration) – The integration that was created.
- nextcord.on_integration_update(integration)¶
Called when an integration is updated.
This requires
Intents.integrationsto be enabled.Added in version 2.0.
- Parameters:
integration (
Integration) – The integration that was created.
- nextcord.on_raw_integration_delete(payload)¶
Called when an integration is deleted.
This requires
Intents.integrationsto be enabled.Added in version 2.0.
- Parameters:
payload (
RawIntegrationDeleteEvent) – The raw event payload data.
- nextcord.on_webhooks_update(channel)¶
Called whenever a webhook is created, modified, or removed from a guild channel.
This requires
Intents.webhooksto be enabled.- Parameters:
channel (
TextChannel) – The channel that had its webhooks updated.
- nextcord.on_member_join(member)¶
- nextcord.on_member_remove(member)¶
Called when a
Memberleaves or joins aGuild.This requires
Intents.membersto be enabled.- Parameters:
member (
Member) – The member who joined or left.
- nextcord.on_raw_member_remove(payload)¶
Called when a
Memberleaves aGuild. Unlikeon_member_remove()this is called regardless of the state of the internal message cache.This requires
Intents.membersto be enabled.Added in version 2.0.
- Parameters:
payload (
RawMemberRemoveEvent) – The raw event payload data.
- nextcord.on_member_update(before, after)¶
Called when a
Memberupdates their profile.This is called when one or more of the following things change:
nickname
roles
pending
flags
This requires
Intents.membersto be enabled.
- nextcord.on_presence_update(before, after)¶
Called when a
Memberupdates their presence.This is called when one or more of the following things change:
status
activity
This requires
Intents.presencesandIntents.membersto be enabled.Added in version 2.0.
- nextcord.on_user_update(before, after)¶
Called when a
Userupdates their profile.This is called when one or more of the following things change:
avatar
username
discriminator
This requires
Intents.membersto be enabled.
- nextcord.on_guild_join(guild)¶
Called when a
Guildis either created by theClientor when theClientjoins a guild.This requires
Intents.guildsto be enabled.- Parameters:
guild (
Guild) – The guild that was joined.
- nextcord.on_guild_remove(guild)¶
Called when a
Guildis 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.
For this event to be invoked, the
Clientmust have been part of the guild to begin with. (i.e. it is part ofClient.guilds)This requires
Intents.guildsto be enabled.- Parameters:
guild (
Guild) – The guild that got removed.
- nextcord.on_guild_update(before, after)¶
Called when a
Guildupdates, for example:Changed name
Changed AFK channel
Changed AFK timeout
etc
This requires
Intents.guildsto be enabled.
- nextcord.on_guild_role_create(role)¶
- nextcord.on_guild_role_delete(role)¶
Called when a
Guildcreates or deletes a newRole.To get the guild it belongs to, use
Role.guild.This requires
Intents.guildsto be enabled.- Parameters:
role (
Role) – The role that was created or deleted.
- nextcord.on_guild_role_update(before, after)¶
Called when a
Roleis changed guild-wide.This requires
Intents.guildsto be enabled.
- nextcord.on_guild_emojis_update(guild, before, after)¶
Called when a
Guildadds or removesEmoji.This requires
Intents.emojis_and_stickersto be enabled.
- nextcord.on_guild_stickers_update(guild, before, after)¶
Called when a
Guildupdates its stickers.This requires
Intents.emojis_and_stickersto be enabled.Added in version 2.0.
- Parameters:
guild (
Guild) – The guild who got their stickers updated.before (Sequence[
GuildSticker]) – A list of stickers before the update.after (Sequence[
GuildSticker]) – A list of stickers after the update.
- nextcord.on_guild_available(guild)¶
Called when a guild becomes available or unavailable. The guild must have existed in the
Client.guildscache.This requires
Intents.guildsto be enabled.- Parameters:
guild – The
Guildthat has changed availability.
- nextcord.on_voice_state_update(member, before, after)¶
Called when a
Memberchanges theirVoiceState.The following, but not limited to, examples illustrate when this event is called:
A member joins a voice or stage channel.
A member leaves a voice or stage 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_statesto 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.
- nextcord.on_stage_instance_create(stage_instance)¶
- nextcord.on_stage_instance_delete(stage_instance)¶
Called when a
StageInstanceis created or deleted for aStageChannel.Added in version 2.0.
- Parameters:
stage_instance (
StageInstance) – The stage instance that was created or deleted.
- nextcord.on_stage_instance_update(before, after)¶
Called when a
StageInstanceis updated.The following, but not limited to, examples illustrate when this event is called:
The topic is changed.
The privacy level is changed.
Added in version 2.0.
- Parameters:
before (
StageInstance) – The stage instance before the update.after (
StageInstance) – The stage instance after the update.
- nextcord.on_member_ban(guild, user)¶
Called when user gets banned from a
Guild.This requires
Intents.bansto be enabled.
- nextcord.on_member_unban(guild, user)¶
Called when a
Usergets unbanned from aGuild.This requires
Intents.bansto be enabled.
- nextcord.on_invite_create(invite)¶
Called when an
Inviteis created. You must have themanage_channelspermission to receive this.Added in version 1.3.
Note
There is a rare possibility that the
Invite.guildandInvite.channelattributes will be ofObjectrather than the respective models.This requires
Intents.invitesto be enabled.- Parameters:
invite (
Invite) – The invite that was created.
- nextcord.on_invite_delete(invite)¶
Called when an
Inviteis deleted. You must have themanage_channelspermission to receive this.Added in version 1.3.
Note
There is a rare possibility that the
Invite.guildandInvite.channelattributes will be ofObjectrather 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.invitesto be enabled.- Parameters:
invite (
Invite) – The invite that was deleted.
- nextcord.on_group_join(channel, user)¶
- nextcord.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.
- nextcord.on_guild_scheduled_event_create(event)¶
Called when a
ScheduledEventis created.- Parameters:
event (
ScheduledEvent) – The event that was created.
- nextcord.on_guild_scheduled_event_update(before, after)¶
Called when a
ScheduledEventis updated.- Parameters:
before (
ScheduledEvent) – The event before it was updated.after (
ScheduledEvent) – The event after it was updated.
- nextcord.on_guild_scheduled_event_delete(event)¶
Called when a
ScheduledEventis deleted.- Parameters:
event (
ScheduledEvent) – The event that was deleted.
- nextcord.on_guild_scheduled_event_user_add(event, user)¶
- nextcord.on_guild_scheduled_event_user_remove(event, user)¶
Called when a
ScheduledEventUseris interested in aScheduledEvent.- Parameters:
event (
ScheduledEvent) – The event that the user is interested in.user (
ScheduledEventUser) – The user that interested.
- nextcord.on_auto_moderation_rule_create(rule)¶
Called when an
AutoModerationRuleis created.Added in version 2.1.
- Parameters:
rule (
AutoModerationRule) – The rule that was created.
- nextcord.on_auto_moderation_rule_update(rule)¶
Called when an
AutoModerationRuleis edited.Added in version 2.1.
- Parameters:
rule (
AutoModerationRule) – The newly edited rule.
- nextcord.on_auto_moderation_rule_delete(rule)¶
Called when a
AutoModerationRuleis deleted.Added in version 2.1.
- Parameters:
rule (
AutoModerationRule) – The deleted rule.
- nextcord.on_auto_moderation_action_execution(execution)¶
Called when an
AutoModerationActionis executed.Added in version 2.1.
- Parameters:
execution (
AutoModerationActionExecution) – The object containing the execution information.
- nextcord.on_guild_audit_log_entry_create(entry)¶
Called when an
AuditLogEntryis created.Added in version 2.4.
- Parameters:
entry (
AuditLogEntry) – The entry that was created.
Utility Functions¶
- nextcord.utils.find(predicate, seq)¶
A helper to return the first element found in the sequence that meets the predicate. For example:
member = nextcord.utils.find(lambda m: m.name == 'Mighty', channel.guild.members)
would find the first
Memberwhose name is ‘Mighty’ and return it. If an entry is not found, thenNoneis 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 (
collections.abc.Iterable) – The iterable to search through.
- nextcord.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__yas the keyword argument.If nothing is found that matches the attributes passed, then
Noneis returned.Examples
Basic usage:
member = nextcord.utils.get(message.guild.members, name='Foo')
Multiple attribute matching:
channel = nextcord.utils.get(guild.voice_channels, name='Foo', bitrate=64000)
Nested attribute matching:
channel = nextcord.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.
- nextcord.utils.snowflake_time(id)¶
- Parameters:
id (
int) – The snowflake ID.- Returns:
An aware datetime in UTC representing the creation time of the snowflake.
- Return type:
- nextcord.utils.oauth_url(client_id, *, permissions=..., guild=..., redirect_uri=..., scopes=..., disable_guild_select=False, integration_type=...)¶
A helper function that returns the OAuth2 URL for inviting the bot into guilds.
- Parameters:
permissions (
Permissions) – The permissions you’re requesting. If not given then you won’t be requesting any permissions.guild (
Snowflake) – 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',).Added in version 1.7.
disable_guild_select (
bool) –Whether to disallow the user from changing the guild dropdown.
Added in version 2.0.
integration_type (
IntegrationType) –The integration type (otherwise known as installation context) that the invite is for.
Added in version 3.0.
- Returns:
The OAuth2 URL for inviting the bot into guilds.
- Return type:
- nextcord.utils.remove_markdown(text, *, ignore_links=True)¶
A helper function that removes markdown characters.
Added 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 * 5then it will be converted into10 5.- Parameters:
- Returns:
The text with the markdown special characters removed.
- Return type:
- nextcord.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:
- nextcord.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
AllowedMentionsclass.
- nextcord.utils.parse_raw_mentions(text)¶
A helper function that parses mentions from a string as an array of
UserIDs matched with the syntax of<@user_id>or<@!user_id>.Note
This does not include role or channel mentions. See
parse_raw_role_mentions()andparse_raw_channel_mentions()for those.Added in version 2.2.
- nextcord.utils.parse_raw_role_mentions(text)¶
A helper function that parses mentions from a string as an array of
RoleIDs matched with the syntax of<@&role_id>.Added in version 2.2.
- nextcord.utils.parse_raw_channel_mentions(text)¶
A helper function that parses mentions from a string as an array of
GuildChannelIDs matched with the syntax of<#channel_id>.Added in version 2.2.
- nextcord.utils.resolve_template(code)¶
Resolves a template code from a
Template, URL or code.Added in version 1.4.
- await nextcord.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.
Added 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 local time.result (Any) – If provided is returned to the caller when the coroutine completes.
- nextcord.utils.utcnow()¶
A helper function to return an aware UTC datetime representing the current time.
This should be preferred to
datetime.datetime.utcnow()since it is an aware datetime, compared to the naive datetime in the standard library.Added in version 2.0.
- Returns:
The current aware datetime in UTC.
- Return type:
- nextcord.utils.format_dt(dt, /, style=None)¶
A helper function to format a
datetime.datetimefor presentation within Discord.This allows for a locale-independent way of presenting data using Discord specific Markdown.
Style
Example Output
Description
t
22:57
Short Time
T
22:57:58
Long Time
d
17/05/2016
Short Date
D
17 May 2016
Long Date
f (default)
17 May 2016 22:57
Short Date Time
F
Tuesday, 17 May 2016 22:57
Long Date Time
R
5 years ago
Relative Time
Note that the exact output depends on the user’s locale setting in the client. The example output presented is using the
en-GBlocale.Added in version 2.0.
- Parameters:
dt (
datetime.datetime) – The datetime to format.style (
str) – The style to format the datetime with.
- Returns:
The formatted string.
- Return type:
- nextcord.utils.as_chunks(iterator, max_size)¶
A helper function that collects an iterator into chunks of a given size.
Added in version 2.0.
- Parameters:
iterator (Union[
collections.abc.Iterator,collections.abc.AsyncIterator]) – The iterator to chunk, can be sync or async.max_size (
int) – The maximum chunk size.
Warning
The last chunk collected may not be as large as
max_size.- Returns:
A new iterator which yields chunks of a given size.
- Return type:
Union[
Iterator,AsyncIterator]
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.
- class nextcord.ChannelType¶
Specifies the type of channel.
- text = 0¶
A text channel
- private = 1¶
A private text channel. Also called a direct message.
- voice = 2¶
A voice channel
- group = 3¶
A private group text channel.
- category = 4¶
A category channel.
- news = 5¶
A guild news channel.
- news_thread = 10¶
A news thread.
- public_thread = 11¶
A public thread.
- private_thread = 12¶
A private thread.
- stage_voice = 13¶
A guild stage voice channel.
- guild_directory = 14¶
A channel containing the guilds in a Student Hub
- forum = 15¶
A forum channel.
- class nextcord.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.
- default = 0¶
The default message type. This is the same as regular messages.
- recipient_add = 1¶
The system message when a user is added to a group private message or a thread.
- recipient_remove = 2¶
The system message when a user is removed from a group private message or a thread.
- call = 3¶
The system message denoting call state, e.g. missed call, started call, etc.
- channel_name_change = 4¶
The system message denoting that a channel’s name has been changed.
- channel_icon_change = 5¶
The system message denoting that a channel’s icon has been changed.
- pins_add = 6¶
The system message denoting that a pinned message has been added to a channel.
- new_member = 7¶
The system message denoting that a new member has joined a Guild.
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 = 12¶
The system message denoting that an announcement channel has been followed.
Added in version 1.3.
- guild_stream = 13¶
The system message denoting that a member is streaming in the guild.
Added in version 1.7.
- guild_discovery_disqualified = 14¶
The system message denoting that the guild is no longer eligible for Server Discovery.
Added in version 1.7.
- guild_discovery_requalified = 15¶
The system message denoting that the guild has become eligible again for Server Discovery.
Added in version 1.7.
- guild_discovery_grace_period_initial_warning = 16¶
- The system message denoting that the guild has failed to meet the Server
Discovery requirements for one week.
Added in version 1.7.
- guild_discovery_grace_period_final_warning = 17¶
- The system message denoting that the guild has failed to meet the Server
Discovery requirements for 3 weeks in a row.
Added in version 1.7.
- thread_created = 18¶
- The system message denoting that a thread has been created. This is only
sent if the thread has been created from an older message. The period of time required for a message to be considered old cannot be relied upon and is up to Discord.
Added in version 2.0.
- reply = 19¶
The system message denoting that the author is replying to a message.
Added in version 2.0.
- chat_input_command = 20¶
The system message denoting that a slash command was executed.
Added in version 2.0.
- thread_starter_message = 21¶
- The system message denoting the message in the thread that is the one that started the
thread’s conversation topic.
Added in version 2.0.
- guild_invite_reminder = 22¶
The system message sent as a reminder to invite people to the guild.
Added in version 2.0.
The system message denoting that a context menu command was executed.
Added in version 2.0.
- auto_moderation_action = 24¶
The system message denoting that an auto moderation action was executed.
Added in version 2.1.
- role_subscription_purchase = 25¶
The system message denoting that a role subscription was purchased.
Added in version 3.2.
- stage_start = 27¶
The system message denoting that a stage channel has started.
Added in version 2.6.
- stage_end = 28¶
The system message denoting that a stage channel has ended.
Added in version 2.6.
- stage_speaker = 29¶
The system message denoting that a stage channel has a new speaker.
Added in version 2.6.
- stage_topic = 31¶
The system message denoting that a stage channel has a new topic.
Added in version 2.6.
- class nextcord.VoiceRegion¶
Specifies the region a voice server belongs to.
- us_west = 'us-west'¶
The US West region.
- us_east = 'us-east'¶
The US East region.
- us_south = 'us-south'¶
The US South region.
- us_central = 'us-central'¶
The US Central region.
- eu_west = 'eu-west'¶
The Western Europe region.
- eu_central = 'eu-central'¶
The Central Europe region.
- singapore = 'singapore'¶
The Singapore region.
- london = 'london'¶
The London region.
- sydney = 'sydney'¶
The Sydney region.
- amsterdam = 'amsterdam'¶
The Amsterdam region.
- frankfurt = 'frankfurt'¶
The Frankfurt region.
- brazil = 'brazil'¶
The Brazil region.
- hongkong = 'hongkong'¶
The Hong Kong region.
- russia = 'russia'¶
The Russia region.
- japan = 'japan'¶
The Japan region.
- southafrica = 'southafrica'¶
The South Africa region.
- south_korea = 'south-korea'¶
The South Korea region.
- india = 'india'¶
The India region.
Added in version 1.2.
- europe = 'europe'¶
The Europe region.
Added in version 1.3.
- dubai = 'dubai'¶
The Dubai region.
Added in version 1.3.
- vip_us_east = 'vip-us-east'¶
The US East region for VIP guilds.
- vip_us_west = 'vip-us-west'¶
The US West region for VIP guilds.
- vip_amsterdam = 'vip-amsterdam'¶
The Amsterdam region for VIP guilds.
- class nextcord.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.Added in version 2.0.
- x == y
Checks if two verification levels are equal.
- x != y
Checks if two verification levels are not equal.
- x > y
Checks if a verification level is higher than another.
- x < y
Checks if a verification level is lower than another.
- x >= y
Checks if a verification level is higher or equal to another.
- x <= y
Checks if a verification level is lower or equal to another.
- none = 0¶
No citeria set.
- low = 1¶
Member must have a verified email on their Discord account.
- medium = 2¶
Member must have a verified email and be registered on Discord for longer than five minutes.
- high = 3¶
Member must have a verified email, be registered on Discord for longer than five minutes, and be a member of the guild for longer than ten minutes.
- highest = 4¶
Member must have a verified phone on their Discord account.
- class nextcord.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.Added in version 2.0.
- x == y
Checks if two content filter levels are equal.
- x != y
Checks if two content filter levels are not equal.
- x > y
Checks if a content filter level is higher than another.
- x < y
Checks if a content filter level is lower than another.
- x >= y
Checks if a content filter level is higher or equal to another.
- x <= y
Checks if a content filter level is lower or equal to another.
- disabled = 0¶
The guild does not have the content filter enabled.
- no_role = 1¶
The guild has the content filter enabled for members without a role.
- all_members = 2¶
The guild has the content filter enabled for every member.
- class nextcord.Status¶
Specifies a
Member‘s status.- online = 'online'¶
The member is online.
- offline = 'offline'¶
The member is offline.
- idle = 'idle'¶
The member is idle.
- dnd = 'dnd'¶
The member is “Do Not Disturb.
- do_not_disturb = 'dnd'¶
An alias for
Status.dnd.
- invisible = '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 beofflineinstead.
- class nextcord.DefaultAvatar¶
Represents the default avatar of a Discord
User.- blurple = 0¶
Represents the default avatar with the color blurple. See also
Colour.blurple
- grey = 1¶
Represents the default avatar with the color grey. See also
Colour.greyple
- gray = 1¶
An alias for
DefaultAvatar.grey.
- green = 2¶
Represents the default avatar with the color green. See also
Colour.green
- orange = 3¶
Represents the default avatar with the color orange. See also
Colour.orange
- red = 4¶
Represents the default avatar with the color red. See also
Colour.red
- fuchsia = 5¶
Represents the default avatar with the color fuchsia. See also
Colour.fuchsiaAdded in version 2.6.
- pink = 5¶
An alias for
DefaultAvatar.fuchsia.Added in version 2.6.
- class nextcord.NotificationLevel¶
- Specifies whether a
Guildhas notifications on for all messages or mentions only by default.
Added in version 2.0.
- x == y
Checks if two notification levels are equal.
- x != y
Checks if two notification levels are not equal.
- x > y
Checks if a notification level is higher than another.
- x < y
Checks if a notification level is lower than another.
- x >= y
Checks if a notification level is higher or equal to another.
- x <= y
Checks if a notification level is lower or equal to another.
- all_messages = 0¶
Members receive notifications for every message regardless of them being mentioned.
- only_mentions = 1¶
Members receive notifications for messages they are mentioned in.
- Specifies whether a
- class nextcord.AuditLogActionCategory¶
Represents the category that the
AuditLogActionbelongs to.This can be retrieved via
AuditLogEntry.category.- create = 1¶
The action is the creation of something.
- delete = 2¶
The action is the deletion of something.
- update = 3¶
The action is the update of something.
- class nextcord.UserFlags¶
Represents Discord User flags.
- staff = 1¶
The user is a Discord Employee.
- partner = 2¶
The user is a Discord Partner.
- hypesquad = 4¶
The user is a HypeSquad Events member.
- bug_hunter = 8¶
The user is a Bug Hunter.
- mfa_sms = 16¶
The user has SMS recovery for Multi Factor Authentication enabled.
The user has dismissed the Discord Nitro promotion.
- hypesquad_bravery = 64¶
The user is a HypeSquad Bravery member.
- hypesquad_brilliance = 128¶
The user is a HypeSquad Brilliance member.
- hypesquad_balance = 256¶
The user is a HypeSquad Balance member.
- early_supporter = 512¶
The user is an Early Supporter.
- team_user = 1024¶
The user is a Team User.
- system = 4096¶
The user is a system user (i.e. represents Discord officially).
- has_unread_urgent_messages = 8192¶
The user has an unread system message.
- bug_hunter_level_2 = 16384¶
The user is a Bug Hunter Level 2.
- verified_bot = 65536¶
The user is a Verified Bot.
- verified_bot_developer = 131072¶
The user is an Early Verified Bot Developer.
- discord_certified_moderator = 262144¶
The user is a Discord Certified Moderator.
- bot_http_interactions = 524288¶
- The user is a bot that uses only HTTP interactions and is shown in the
online member list.
Added in version 2.4.
- known_spammer = 1048576¶
The user is a Known Spammer.
- active_developer = 4194304¶
The user is an Active Developer.
Added in version 2.4.
- class nextcord.ActivityType¶
Specifies the type of
Activity. This is used to check how to interpret the activity itself.- unknown = -1¶
An unknown activity type. This should generally not happen.
- playing = 0¶
A “Playing” activity type.
- streaming = 1¶
A “Streaming” activity type.
- listening = 2¶
A “Listening” activity type.
- watching = 3¶
A “Watching” activity type.
- custom = 4¶
A “Custom” activity type.
- competing = 5¶
A “Competing” activity type.
Added in version 1.5.
- class nextcord.TeamMembershipState¶
- Represents the membership state of a team member retrieved
through
Client.application_info().
Added in version 1.3.
- invited = 1¶
Represents an invited member.
- accepted = 2¶
Represents a member currently in the team.
- class nextcord.WebhookType¶
Represents the type of webhook that can be received.
Added in version 1.3.
- incoming = 1¶
Represents a webhook that can post messages to channels with a token.
- channel_follower = 2¶
Represents a webhook that is internally managed by Discord, used for following channels.
- application = 3¶
Represents a webhook that is used for interactions or applications.
Added in version 2.0.
- class nextcord.ExpireBehaviour¶
Represents the behaviour the
Integrationshould perform when a user’s subscription has finished.There is an alias for this called
ExpireBehavior.Added in version 1.4.
- remove_role = 0¶
This will remove the
StreamIntegration.rolefrom the user when their subscription is finished.
- kick = 1¶
This will kick the user when their subscription is finished.
- class nextcord.StickerType¶
Represents the type of sticker.
Added in version 2.0.
- standard = 1¶
Represents a standard sticker.
- guild = 2¶
Represents a custom sticker created in a guild.
- class nextcord.StickerFormatType¶
Represents the type of sticker images.
Added in version 1.6.
- png = 1¶
Represents a sticker with a png image.
- apng = 2¶
Represents a sticker with an apng image.
- lottie = 3¶
Represents a sticker with a lottie image.
- gif = 4¶
Represents a sticker with a GIF image.
Added in version 2.4.
- class nextcord.InviteTarget¶
Represents the invite type for voice channel invites.
Added in version 2.0.
- unknown = 0¶
The invite doesn’t target anyone or anything.
- stream = 1¶
A stream invite that targets a user.
- embedded_application = 2¶
A stream invite that targets an embedded application.
- class nextcord.InteractionType¶
Specifies the type of
Interaction.Added in version 2.0.
- ping = 1¶
Represents Discord pinging to see if the interaction response server is alive.
- application_command = 2¶
Represents a slash command or context menu interaction.
- component = 3¶
Represents a component based interaction, i.e. using the Discord Bot UI Kit.
- application_command_autocomplete = 4¶
Represents a slash command autocomplete interaction.
- modal_submit = 5¶
Represents a modal submit interaction.
- class nextcord.InteractionResponseType¶
Specifies the response type for the interaction.
Added in version 2.0.
- pong = 1¶
Pongs the interaction when given a ping.
See also
InteractionResponse.pong()
- channel_message = 4¶
Respond to the interaction with a message.
See also
InteractionResponse.send_message()
- deferred_channel_message = 5¶
Responds to the interaction with a message at a later time.
See also
InteractionResponse.defer()
- deferred_message_update = 6¶
- Acknowledges the component interaction with a promise that
the message will update later (though there is no need to actually update the message).
See also
InteractionResponse.defer()
- message_update = 7¶
Responds to the interaction by editing the message.
See also
InteractionResponse.edit_message()
- class nextcord.Locale¶
- da = 'da'¶
Danish | Dansk
- de = 'de'¶
German | Deutsch
- en_GB = 'en-GB'¶
English, UK | English, UK
- en_US = 'en-US'¶
English, US | English, US
- es_ES = 'es-ES'¶
Spanish | Español
- fr = 'fr'¶
French | Français
- hr = 'hr'¶
Croatian | Hrvatski
- id = 'id'¶
Indonesian | Bahasa Indonesia
Added in version 2.4.
- it = 'it'¶
Italian | Italiano
- lt = 'lt'¶
Lithuanian | Lietuviškai
- hu = 'hu'¶
Hungarian | Magyar
- nl = 'nl'¶
Dutch | Nederlands
- no = 'no'¶
Norwegian | Norsk
- pl = 'pl'¶
Polish | Polski
- pt_BR = 'pt-BR'¶
Portuguese, Brazilian | Português do Brasil
- ro = 'ro'¶
Romanian, Romania | Română
- fi = 'fi'¶
Finnish | Suomi
- sv_SE = 'sv-SE'¶
Swedish | Svenska
- vi = 'vi'¶
Vietnamese | Tiếng Việt
- tr = 'tr'¶
Turkish | Türkçe
- cs = 'cs'¶
Czech | Čeština
- el = 'el'¶
Greek | Ελληνικά
- bg = 'bg'¶
Bulgarian | български
- ru = 'ru'¶
Russian | Pусский
- uk = 'uk'¶
Ukrainian | Українська
- hi = 'hi'¶
Hindi | हिन्दी
- th = 'th'¶
Thai | ไทย
- zh_CN = 'zh-CN'¶
Chinese, China | 中文
- ja = 'ja'¶
Japanese | 日本語
- zh_TW = 'zh-TW'¶
Chinese, Taiwan | 繁體中文
- ko = 'ko'¶
Korean | 한국어
- class nextcord.VideoQualityMode¶
Represents the camera video quality mode for voice channel participants.
Added in version 2.0.
- auto = 1¶
Represents auto camera video quality.
- full = 2¶
Represents full camera video quality.
- class nextcord.ComponentType¶
Represents the component type of a component.
Added in version 2.0.
- action_row = 1¶
Represents the group component which holds different components in a row.
- button = 2¶
Represents a button component.
- select = 3¶
Represents a select string component.
- string_select = 3¶
An alias for
ComponentType.select.Added in version 2.3.
- text_input = 4¶
Represents a text input component.
- user_select = 5¶
Represents a user select component.
Added in version 2.3.
- role_select = 6¶
Represents a role select component.
Added in version 2.3.
- mentionable_select = 7¶
Represents a mentionable select component.
Added in version 2.3.
- channel_select = 8¶
Represents a channel select component.
Added in version 2.3.
- class nextcord.ButtonStyle¶
Represents the style of the button component.
Added in version 2.0.
- primary = 1¶
Represents a blurple button for the primary action.
- secondary = 2¶
Represents a grey button for secondary actions.
- success = 3¶
Represents a green button for success actions.
- danger = 4¶
Represents a red button for dangerous actions.
- link = 5¶
Represents a link button.
- blurple = 1¶
An alias for
ButtonStyle.primary.
- grey = 2¶
An alias for
ButtonStyle.secondary.
- gray = 2¶
An alias for
ButtonStyle.secondary.
- green = 3¶
An alias for
ButtonStyle.success.
- red = 4¶
An alias for
ButtonStyle.danger.
- url = 5¶
An alias for
ButtonStyle.link.
- class nextcord.TextInputStyle¶
Represent the style of a text input component.
Added in version 2.0.
- short = 1¶
Represent a single line input.
- paragraph = 2¶
Represent a multi line input.
- class nextcord.StagePrivacyLevel¶
Represents a stage instance’s privacy level.
Added in version 2.0.
- public = 1¶
The stage instance can be joined by external users.
- closed = 2¶
The stage instance can only be joined by members of the guild.
- guild_only = 2¶
An alias for
StagePrivacyLevel.closed.
- class nextcord.NSFWLevel¶
Represents the NSFW level of a guild.
Added in version 2.0.
- x == y
Checks if two NSFW levels are equal.
- x != y
Checks if two NSFW levels are not equal.
- x > y
Checks if a NSFW level is higher than another.
- x < y
Checks if a NSFW level is lower than another.
- x >= y
Checks if a NSFW level is higher or equal to another.
- x <= y
Checks if a NSFW level is lower or equal to another.
- default = 0¶
The guild has not been categorised yet.
- explicit = 1¶
The guild contains NSFW content.
- safe = 2¶
The guild does not contain any NSFW content.
- age_restricted = 3¶
The guild may contain NSFW content.
- class nextcord.ScheduledEventEntityType¶
Represents the type of an entity on a scheduled event.
- stage_instance = 1¶
The event is for a stage
- voice = 2¶
The event is for a voice channel.
- external = 3¶
The event is happening elsewhere.
- class nextcord.ScheduledEventPrivacyLevel¶
Represents the privacy level of scheduled event.
- guild_only = 2¶
The scheduled event is only visible to members of the guild.
- class nextcord.ScheduledEventStatus¶
Represents the status of a scheduled event.
- scheduled = 1¶
The event is scheduled to happen.
- active = 2¶
The event is happening.
- completed = 3¶
The event has finished.
- canceled = 4¶
The event was cancelled.
- cancelled = 4¶
An alias for
ScheduledEventStatus.canceled.
- class nextcord.AutoModerationEventType¶
Represents what event context an auto moderation rule will be checked.
Added in version 2.1.
- message_send = 1¶
A member sends or edits a message in the guild.
- member_update = 2¶
A member edits their profile.
Added in version 3.2.
- class nextcord.AutoModerationTriggerType¶
Represents the type of content which can trigger an auto moderation rule.
Added in version 2.1.
Changed in version 2.2: Removed
harmful_linkas it is no longer used by Discord.- keyword = 1¶
This rule checks if content contains words from a user defined list of keywords.
- spam = 3¶
This rule checks if content represents generic spam.
- keyword_preset = 4¶
This rule checks if content contains words from Discord pre-defined wordsets.
- mention_spam = 5¶
This rule checks if the number of mentions in the message is more than the maximum allowed.
Added in version 2.3.
- member_profile = 6¶
This rule checks if member profile contains words from a user defined list of keywords.
Added in version 3.2.
- class nextcord.KeywordPresetType¶
Represents the type of a keyword preset auto moderation rule.
Added in version 2.1.
- profanity = 1¶
Words that may be considered forms of swearing or cursing.
- sexual_content = 2¶
Words that refer to sexually explicit behaviour or activity.
- slurs = 3¶
Personal insults or words that may be considered hate speech.
- class nextcord.AutoModerationActionType¶
Represents the action that will be taken if an auto moderation rule is triggered.
Added in version 2.1.
- block_message = 1¶
Blocks a message with content matching the rule.
- send_alert_message = 2¶
Logs message content to a specified channel.
- timeout = 3¶
Timeout user for a specified duration.
Note
This action type can only be used with the
Permissions.moderate_memberspermission.
- block_member_interaction = 4¶
Prevents a member from using text, voice, or other interactions.
Added in version 3.2.
- class nextcord.SortOrderType¶
The default sort order type used to sort posts in a
ForumChannel.Added in version 2.3.
- latest_activity = 0¶
Sort forum posts by their activity.
- creation_date = 1¶
Sort forum posts by their creation date.
- class nextcord.RoleConnectionMetadataType¶
Represents the type of comparison a role connection metadata record will use.
Added in version 2.4.
- integer_greater_than_or_equal = 2¶
The metadata value must be less than or equal to the guild’s configured value.
- integer_not_equal = 4¶
The metadata value must be greater than or equal to the guild’s configured value.
- datetime_greater_than_or_equal = 6¶
The metadata value must be equal to the guild’s configured value.
- boolean_not_equal = 8¶
The metadata value must be not equal to the guild’s configured value.
- class nextcord.ForumLayoutType¶
The default layout type used to display posts in a
ForumChannel.Added in version 2.4.
- not_set = 0¶
No default has been set by channel administrators.
- list = 1¶
Display posts as a list, more text focused.
- gallery = 2¶
Display posts as a collection of posts with images, this is more image focused.
- class nextcord.AuditLogAction¶
Represents the type of action being done for a
AuditLogEntry, which is retrievable vianextcord.Guild.audit_logs().- guild_update = 1¶
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, banner, or discovery splash
Changing the guild moderation settings
Changing things related to the guild widget
When this is the action, the type of
targetis theGuild.Possible attributes for
nextcord.AuditLogDiff:
- channel_create = 10¶
A new channel was created.
When this is the action, the type of
targetis either aabc.GuildChannelorObjectwith an ID.A more filled out object in the
Objectcase can be found by usingafter.Possible attributes for
nextcord.AuditLogDiff:
- channel_update = 11¶
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
targetis theabc.GuildChannelorObjectwith an ID.A more filled out object in the
Objectcase can be found by usingafterorbefore.Possible attributes for
nextcord.AuditLogDiff:
- channel_delete = 12¶
A channel was deleted.
When this is the action, the type of
targetis anObjectwith an ID.A more filled out object can be found by using the
beforeobject.Possible attributes for
nextcord.AuditLogDiff:
- overwrite_create = 13¶
A channel permission overwrite was created.
When this is the action, the type of
targetis theabc.GuildChannelorObjectwith an ID.When this is the action, the type of
extrais either aRoleorMember. If the object is not found then it is aObjectwith an ID being filled, a name, and atypeattribute set to either'role'or'member'to help dictate what type of ID it is.Possible attributes for
nextcord.AuditLogDiff:
- overwrite_update = 14¶
A channel permission overwrite was changed, this is typically when the permission values change.
See
overwrite_createfor more information on how thetargetandextrafields are set.Possible attributes for
nextcord.AuditLogDiff:
- overwrite_delete = 15¶
A channel permission overwrite was deleted.
See
overwrite_createfor more information on how thetargetandextrafields are set.Possible attributes for
nextcord.AuditLogDiff:
- kick = 20¶
A member was kicked.
When this is the action, the type of
targetis theUserwho got kicked.When this is the action,
changesis empty.
- member_prune = 21¶
A member prune was triggered.
When this is the action, the type of
targetis set toNone.When this is the action, the type of
extrais 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,
changesis empty.
- ban = 22¶
A member was banned.
When this is the action, the type of
targetis theUserwho got banned.When this is the action,
changesis empty.
- unban = 23¶
A member was unbanned.
When this is the action, the type of
targetis theUserwho got unbanned.When this is the action,
changesis empty.
- member_update = 24¶
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
targetis theMemberorUserwho got updated.Possible attributes for
nextcord.AuditLogDiff:
- member_role_update = 25¶
A member’s role has been updated. This triggers when a member either gains a role or loses a role.
When this is the action, the type of
targetis theMemberorUserwho got the role.Possible attributes for
nextcord.AuditLogDiff:
- member_move = 26¶
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
extrais set to an unspecified proxy object with two attributes:channel: ATextChannelorObjectwith the channel ID where the members were moved.count: An integer specifying how many members were moved.
Added in version 1.3.
- member_disconnect = 27¶
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
extrais set to an unspecified proxy object with one attribute:count: An integer specifying how many members were disconnected.
Added in version 1.3.
- bot_add = 28¶
A bot was added to the guild.
When this is the action, the type of
targetis theMemberorUserwhich was added to the guild.Added in version 1.3.
- role_create = 30¶
A new role was created.
When this is the action, the type of
targetis theRoleor aObjectwith the ID.Possible attributes for
nextcord.AuditLogDiff:
- role_update = 31¶
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
targetis theRoleor aObjectwith the ID.Possible attributes for
nextcord.AuditLogDiff:
- role_delete = 32¶
A role was deleted.
When this is the action, the type of
targetis theRoleor aObjectwith the ID.Possible attributes for
nextcord.AuditLogDiff:
- invite_create = 40¶
An invite was created.
When this is the action, the type of
targetis theInvitethat was created.Possible attributes for
nextcord.AuditLogDiff:
- invite_update = 41¶
An invite was updated.
When this is the action, the type of
targetis theInvitethat was updated.
- invite_delete = 42¶
An invite was deleted.
When this is the action, the type of
targetis theInvitethat was deleted.Possible attributes for
nextcord.AuditLogDiff:
- webhook_create = 50¶
A webhook was created.
When this is the action, the type of
targetis theObjectwith the webhook ID.Possible attributes for
nextcord.AuditLogDiff:
- webhook_update = 51¶
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
targetis theObjectwith the webhook ID.Possible attributes for
nextcord.AuditLogDiff:
- webhook_delete = 52¶
A webhook was deleted.
When this is the action, the type of
targetis theObjectwith the webhook ID.Possible attributes for
nextcord.AuditLogDiff:
- emoji_create = 60¶
An emoji was created.
When this is the action, the type of
targetis theEmojiorObjectwith the emoji ID.Possible attributes for
nextcord.AuditLogDiff:
- emoji_update = 61¶
An emoji was updated. This triggers when the name has changed.
When this is the action, the type of
targetis theEmojiorObjectwith the emoji ID.Possible attributes for
nextcord.AuditLogDiff:
- emoji_delete = 62¶
An emoji was deleted.
When this is the action, the type of
targetis theObjectwith the emoji ID.Possible attributes for
nextcord.AuditLogDiff:
- message_delete = 72¶
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
targetis theMemberorUserwho had their message deleted.When this is the action, the type of
extrais set to an unspecified proxy object with two attributes:count: An integer specifying how many messages were deleted.channel: ATextChannelorObjectwith the channel ID where the message got deleted.
- message_bulk_delete = 73¶
Messages were bulk deleted by a moderator.
When this is the action, the type of
targetis theTextChannelorObjectwith the ID of the channel that was purged.When this is the action, the type of
extrais set to an unspecified proxy object with one attribute:count: An integer specifying how many messages were deleted.
Added in version 1.3.
- message_pin = 74¶
A message was pinned in a channel.
When this is the action, the type of
targetis theMemberorUserwho had their message pinned.When this is the action, the type of
extrais set to an unspecified proxy object with two attributes:channel: ATextChannelorObjectwith the channel ID where the message was pinned.message_id: the ID of the message which was pinned.
Added in version 1.3.
- message_unpin = 75¶
A message was unpinned in a channel.
When this is the action, the type of
targetis theMemberorUserwho had their message unpinned.When this is the action, the type of
extrais set to an unspecified proxy object with two attributes:channel: ATextChannelorObjectwith the channel ID where the message was unpinned.message_id: the ID of the message which was unpinned.
Added in version 1.3.
- integration_create = 80¶
A guild integration was created.
When this is the action, the type of
targetis theObjectwith the integration ID of the integration which was created.Added in version 1.3.
- integration_update = 81¶
A guild integration was updated.
When this is the action, the type of
targetis theObjectwith the integration ID of the integration which was updated.Added in version 1.3.
- integration_delete = 82¶
A guild integration was deleted.
When this is the action, the type of
targetis theObjectwith the integration ID of the integration which was deleted.Added in version 1.3.
- stage_instance_create = 83¶
A stage instance was started.
When this is the action, the type of
targetis theStageInstanceorObjectwith the ID of the stage instance which was created.Possible attributes for
nextcord.AuditLogDiff:Added in version 2.0.
- stage_instance_update = 84¶
A stage instance was updated.
When this is the action, the type of
targetis theStageInstanceorObjectwith the ID of the stage instance which was updated.Possible attributes for
nextcord.AuditLogDiff:Added in version 2.0.
- stage_instance_delete = 85¶
A stage instance was ended.
Added in version 2.0.
- sticker_create = 90¶
A sticker was created.
When this is the action, the type of
targetis theGuildStickerorObjectwith the ID of the sticker which was updated.Possible attributes for
nextcord.AuditLogDiff:Added in version 2.0.
- sticker_update = 91¶
A sticker was updated.
When this is the action, the type of
targetis theGuildStickerorObjectwith the ID of the sticker which was updated.Possible attributes for
nextcord.AuditLogDiff:Added in version 2.0.
- sticker_delete = 92¶
A sticker was deleted.
When this is the action, the type of
targetis theGuildStickerorObjectwith the ID of the sticker which was updated.Possible attributes for
nextcord.AuditLogDiff:Added in version 2.0.
- scheduled_event_create = 100¶
A scheduled event was created.
When this is the action, the type of
targetis theScheduledEventorObjectwith the ID of the scheduled event which was created.
- scheduled_event_update = 101¶
A scheduled event was updated.
When this is the action, the type of
targetis theScheduledEventorObjectwith the ID of the scheduled event which was created.
- scheduled_event_delete = 102¶
A scheduled event was deleted.
When this is the action, the type of
targetis theScheduledEventorObjectwith the ID of the scheduled event which was created.
- thread_create = 110¶
A thread was created.
When this is the action, the type of
targetis theThreadorObjectwith the ID of the thread which was created.Possible attributes for
nextcord.AuditLogDiff:Added in version 2.0.
- thread_update = 111¶
A thread was updated.
When this is the action, the type of
targetis theThreadorObjectwith the ID of the thread which was updated.Possible attributes for
nextcord.AuditLogDiff:Added in version 2.0.
- thread_delete = 112¶
A thread was deleted.
When this is the action, the type of
targetis theThreadorObjectwith the ID of the thread which was deleted.Possible attributes for
nextcord.AuditLogDiff:Added in version 2.0.
- auto_moderation_rule_create = 140¶
An auto moderation rule was created.
When this is the action, the type of
targetis theAutoModerationRuleorObjectwith the ID of the rule which was created.Possible attributes for
nextcord.AuditLogDiff:Added in version 2.1.
- auto_moderation_rule_update = 141¶
An auto moderation rule was updated.
When this is the action, the type of
targetis theAutoModerationRuleorObjectwith the ID of the rule which was updated.Possible attributes for
nextcord.AuditLogDiff:Added in version 2.1.
- auto_moderation_rule_delete = 142¶
An auto moderation rule was deleted.
When this is the action, the type of
targetis theAutoModerationRuleorObjectwith the ID of the rule which was deleted.Possible attributes for
nextcord.AuditLogDiff:Added in version 2.1.
- auto_moderation_block_message = 143¶
A message was blocked by an auto moderation rule.
When this is the action, the type of
targetis theMemberorUserwhose message was blocked.When this is the action, the type of
extrais set to an unspecified proxy object with these three attributes:channel: AGuildChannel,ThreadorObjectwith the channel ID where the message was blocked.rule_name: Astrwith the name of the rule.rule_trigger_type: AAutoModerationTriggerTypevalue with the trigger type of the rule.
Added in version 2.1.
- auto_moderation_flag_to_channel = 144¶
A message was flagged by an auto moderation rule.
When this is the action, the type of
targetis theMemberorUserwhose message was flagged.When this is the action, the type of
extrais set to an unspecified proxy object with these three attributes:channel: AGuildChannel,ThreadorObjectwith the channel ID where the message was flagged.rule_name: Astrwith the name of the rule.rule_trigger_type: AAutoModerationTriggerTypevalue with the trigger type of the rule.
Added in version 2.3.
- auto_moderation_user_communication_disabled = 145¶
A member was timed out by an auto moderation rule.
When this is the action, the type of
targetis theMemberorUserwho was timed out.When this is the action, the type of
extrais set to an unspecified proxy object with these three attributes:channel: AGuildChannel,ThreadorObjectwith the channel ID where the member was timed out.rule_name: Astrwith the name of the rule.rule_trigger_type: AAutoModerationTriggerTypevalue with the trigger type of the rule.
Added in version 2.3.
- class nextcord.InviteType¶
Represents the type of an invite.
Added in version 3.0.
- guild = 0¶
The invite is for a guild.
- group_dm = 1¶
The invite is for a group DM.
- friend = 2¶
The invite is for a Discord user.
- class nextcord.IntegrationType¶
Where a
BaseApplicationCommandis available, only for globally-scoped commands.Added in version 3.0.
- guild_install = 0¶
App is installable to servers.
- user_install = 1¶
App is installable to users.
- class nextcord.InteractionContextType¶
Where a
BaseApplicationCommandcan be used, only for globally-scoped commands, or where aInteractionoriginates from.Added in version 3.0.
- guild = 0¶
The
BaseApplicationCommandcan be used within servers, or theInteractionoriginates from a server.
- bot_dm = 1¶
The
BaseApplicationCommandcan be used within DMs with the app’s bot user, or theInteractionoriginates from such DMs.
- private_channel = 2¶
The
BaseApplicationCommandcan be used within Group DMs and DMs other than the app’s bot user, or theInteractionoriginates from such 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
You can also chunk data using the utils.as_chunks() utility method.
It can be used as follows:
async for chunk in utils.as_chunks(channel.history(), 10):
# do stuff with chunks here
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. To accomplish
this goal, it must make use of a couple of data classes that aid in this goal.
AuditLogEntry¶
- class nextcord.AuditLogEntry(*, auto_moderation_rules, 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.
- action¶
The action that was done.
- Type:
- 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. SeeAuditLogActionfor which actions have this field filled out.- Type:
Any
- created_at¶
Returns the entry’s creation time in UTC.
- Type:
- target¶
The target that got changed. The exact type of this depends on the action being done.
- Type:
Any
- category¶
The category of the action, if applicable.
- Type:
Optional[
AuditLogActionCategory]
- changes¶
The list of changes this entry has.
- Type:
- before¶
The target’s prior state.
- Type:
- after¶
The target’s subsequent state.
- Type:
AuditLogChanges¶
- class nextcord.AuditLogChanges¶
An audit log change set.
- before¶
The old value. The attribute has the type of
AuditLogDiff.Depending on the
AuditLogActionCategoryretrieved bycategory, the data retrieved by this attribute differs:
- after¶
The new value. The attribute has the type of
AuditLogDiff.Depending on the
AuditLogActionCategoryretrieved bycategory, the data retrieved by this attribute differs:
AuditLogDiff¶
- actions
- afk_channel
- afk_timeout
- allow
- archived
- auto_archive_duration
- available
- avatar
- banner
- bitrate
- channel
- code
- color
- colour
- deaf
- default_auto_archive_duration
- default_message_notifications
- default_notifications
- deny
- description
- discovery_splash
- emoji
- enabled
- event_type
- exempt_channels
- exempt_roles
- explicit_content_filter
- format_type
- hoist
- icon
- id
- inviter
- locked
- max_age
- max_uses
- mentionable
- mfa_level
- mute
- name
- nick
- overwrites
- owner
- permissions
- position
- privacy_level
- public_updates_channel
- region
- roles
- rtc_region
- rules_channel
- slowmode_delay
- splash
- system_channel
- temporary
- topic
- trigger_metadata
- trigger_type
- type
- uses
- vanity_url_code
- verification_level
- video_quality_mode
- widget_channel
- widget_enabled
- class nextcord.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. See also
Guild.icon.- Type:
- splash¶
The guild’s invite splash. See also
Guild.splash.- Type:
- discovery_splash¶
The guild’s discovery splash. See also
Guild.discovery_splash.- Type:
- banner¶
The guild’s banner. See also
Guild.banner.- Type:
- owner¶
The guild’s owner. See also
Guild.owner
- region¶
The guild’s voice region. See also
Guild.region.- Type:
- afk_channel¶
The guild’s AFK channel.
If this could not be found, then it falls back to a
Objectwith 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
Objectwith the ID being set.See
Guild.system_channel.- Type:
Union[
TextChannel,Object]
- rules_channel¶
The guild’s rules channel.
If this could not be found then it falls back to a
Objectwith the ID being set.See
Guild.rules_channel.- Type:
Union[
TextChannel,Object]
- public_updates_channel¶
The guild’s public updates channel.
If this could not be found then it falls back to a
Objectwith the ID being set.See
Guild.public_updates_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
Objectwith 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
Roleorabc.GuildChannel.- Type:
- type¶
The type of channel or sticker.
- Type:
Union[
ChannelType,StickerType]
- topic¶
The topic of a
TextChannelorStageChannel.See also
TextChannel.topicorStageChannel.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
PermissionOverwritefor said target.The first element is the object being targeted, which can either be a
MemberorUserorRole. If this object is not found then it is aObjectwith an ID being filled and atypeattribute set to either'role'or'member'to help decide what type of ID it is.- Type:
List[Tuple[target,
PermissionOverwrite]]
- privacy_level¶
The privacy level of the stage instance.
- Type:
- roles¶
A list of roles being added or removed from a member.
If a role is not found then it is a
Objectwith 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
Objectwith 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:
Optional[
User]
- 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 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:
- rtc_region¶
The region for the voice channel’s voice communication. A value of
Noneindicates automatic voice region detection.See also
VoiceChannel.rtc_region.- Type:
- video_quality_mode¶
The camera video quality for the voice channel’s participants.
See also
VoiceChannel.video_quality_mode.- Type:
- format_type¶
The format type of a sticker being changed.
See also
GuildSticker.format- Type:
- emoji¶
The name of the emoji that represents a sticker being changed.
See also
GuildSticker.emoji- Type:
- description¶
The description of a sticker being changed.
See also
GuildSticker.description- Type:
- available¶
The availability of a sticker being changed.
See also
GuildSticker.available- Type:
- auto_archive_duration¶
The thread’s auto archive duration being changed.
See also
Thread.auto_archive_duration- Type:
- default_auto_archive_duration¶
The default auto archive duration for newly created threads being changed.
- Type:
- trigger_type¶
The trigger type of an auto moderation rule being changed.
- event_type¶
The event type of an auto moderation rule being changed.
- Type:
- actions¶
The list of actions being changed.
- Type:
List[
AutoModerationAction]
- trigger_metadata¶
The trigger metadata of an auto moderation rule being changed.
- Type:
AutoModTriggerMetadata
- exempt_roles¶
The list of roles that are exempt from an auto moderation rule being changed.
If a role is not found then it is an
Objectwith the ID set.
- exempt_channels¶
The list of channels that are exempt from an auto moderation rule being changed.
If a channel is not found then it is an
Objectwith the ID set.- Type:
List[Union[
abc.GuildChannel,Object]]
Webhook Support¶
nextcord offers support for creating, editing, and executing webhooks through the Webhook class.
Webhook¶
- clsWebhook.from_url
- clsWebhook.partial
- asyncdelete
- asyncdelete_message
- asyncedit
- asyncedit_message
- asyncfetch
- asyncfetch_message
- defis_authenticated
- defis_partial
- asyncsend
- class nextcord.Webhook¶
Represents an asynchronous 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 be bound using the library’s internal HTTP session.The second form involves creating a webhook object manually using the
from_url()orpartial()classmethods.For example, creating a webhook from a URL and using aiohttp:
from nextcord import Webhook import aiohttp async def foo(): async with aiohttp.ClientSession() as session: webhook = Webhook.from_url('url-here', session=session) await webhook.send('Hello World', username='Foo')
For a synchronous counterpart, see
SyncWebhook.- 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.
- type¶
The type of the webhook.
Added in version 1.3.
- Type:
- token¶
The authentication token of the webhook. If this is
Nonethen the webhook cannot be used to make requests.- Type:
Optional[
str]
- user¶
The user this webhook was created by. If the webhook was received without authentication then this will be
None.- Type:
Optional[
abc.User]
- source_guild¶
The guild of the channel that this webhook is following. Only given if
typeisWebhookType.channel_follower.Added in version 2.0.
- Type:
Optional[
PartialWebhookGuild]
- source_channel¶
The channel that this webhook is following. Only given if
typeisWebhookType.channel_follower.Added in version 2.0.
- Type:
Optional[
PartialWebhookChannel]
- classmethod partial(id, token, *, session, bot_token=None)¶
Creates a partial
Webhook.- Parameters:
id (
int) – The ID of the webhook.token (
str) – The authentication token of the webhook.session (
aiohttp.ClientSession) –The session to use to send requests with. Note that the library does not manage the session and will not close it.
Added in version 2.0.
bot_token (Optional[
str]) –The bot authentication token for authenticated requests involving the webhook.
Added in version 2.0.
- Returns:
A partial
Webhook. A partial webhook is just a webhook object with an ID and a token.- Return type:
- classmethod from_url(url, *, session, bot_token=None)¶
Creates a partial
Webhookfrom a webhook URL.- Parameters:
url (
str) – The URL of the webhook.session (
aiohttp.ClientSession) –The session to use to send requests with. Note that the library does not manage the session and will not close it.
Added in version 2.0.
bot_token (Optional[
str]) –The bot authentication token for authenticated requests involving the webhook.
Added in version 2.0.
- 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:
- await fetch(*, prefer_auth=True)¶
This function is a coroutine.
Fetches the current webhook.
This could be used to get a full webhook from a partial webhook.
Added in version 2.0.
Note
When fetching with an unauthenticated webhook, i.e.
is_authenticated()returnsFalse, then the returned webhook does not contain any user information.- Parameters:
prefer_auth (
bool) – Whether to use the bot token over the webhook token if available. Defaults toTrue.- Raises:
HTTPException – Could not fetch the webhook
NotFound – Could not find the webhook by this ID
InvalidArgument – This webhook does not have a token associated with it.
- Returns:
The fetched webhook.
- Return type:
- await delete(*, reason=None, prefer_auth=True)¶
This function is a coroutine.
Deletes this Webhook.
- Parameters:
- 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.
- await edit(*, reason=None, name=..., avatar=..., channel=None, prefer_auth=True)¶
This function is a coroutine.
Edits this Webhook.
Changed in version 2.1: The
avatarparameter now acceptsFile,Attachment, andAsset.- Parameters:
name (Optional[
str]) – The webhook’s new default name.avatar (Optional[Union[
bytes,Asset,Attachment,File]]) – A bytes-like object,File,Attachment, orAssetrepresenting the webhook’s new default avatar.channel (Optional[
abc.Snowflake]) –The webhook’s new channel. This requires an authenticated webhook.
Added in version 2.0.
reason (Optional[
str]) –The reason for editing this webhook. Shows up on the audit log.
Added in version 1.4.
prefer_auth (
bool) –Whether to use the bot token over the webhook token if available. Defaults to
True.Added in version 2.0.
- Raises:
HTTPException – Editing the webhook failed.
NotFound – This webhook does not exist.
InvalidArgument – This webhook does not have a token associated with it or it tried editing a channel without authentication.
- property avatar¶
Returns an
Assetfor the avatar the webhook has.If the webhook does not have a traditional avatar, an asset for the default avatar is returned instead.
- Type:
- property channel¶
The text channel this webhook belongs to.
If this is a partial webhook, then this will always return
None.- Type:
Optional[
TextChannel]
- property created_at¶
Returns the webhook’s creation time in UTC.
- Type:
- property guild¶
The guild this webhook belongs to.
If this is a partial webhook, then this will always return
None.- Type:
Optional[
Guild]
- is_authenticated()¶
bool: Whether the webhook is authenticated with a bot token.Added in version 2.0.
- await send(content=..., *, username=..., avatar_url=..., tts=False, file=..., files=..., embed=..., embeds=..., allowed_mentions=..., view=..., thread=..., wait=False, delete_after=None, ephemeral=None, flags=None, suppress_embeds=None, thread_name=None, components=None)¶
This function is a coroutine.
Sends a message using the webhook.
The content must be a type that can convert to a string through
str(content).To upload a single file, the
fileparameter should be used with a singleFileobject.If the
embedparameter is provided, it must be of typeEmbedand it must be a rich embed type. You cannot mix theembedparameter with theembedsparameter, which must be alistofEmbedobjects to send.Changed in version 2.4:
ephemeralcan now acceptNoneto indicate thatflagsshould be used.- 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 fromNoneto aWebhookMessageif set toTrue. If the type of webhook isWebhookType.applicationthen this is always set toTrue.username (
str) – The username to send with this message. If no username is provided then the default username for the webhook is used.avatar_url (
str) – The avatar URL to send with this message. If no avatar URL is provided then the default avatar for the webhook is used. If this is not a string then it is explicitly cast usingstr.tts (
bool) – Indicates if the message should be sent using text-to-speech.ephemeral (
bool) – Indicates if the message should only be visible to the user. This is only available toWebhookType.applicationwebhooks. If a view is sent with an ephemeral message and it has no timeout set then the timeout is set to 15 minutes.delete_after (Optional[
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.
Added in version 2.0.
file (
File) – The file to upload. This cannot be mixed withfilesparameter.files (List[
File]) – A list of files to send with the content. This cannot be mixed with thefileparameter.embed (
Embed) – The rich embed for the content to send. This cannot be mixed withembedsparameter.embeds (List[
Embed]) – A list of embeds to send with the content. Maximum of 10. This cannot be mixed with theembedparameter.allowed_mentions (
AllowedMentions) –Controls the mentions being processed in this message.
Added in version 1.4.
view (
nextcord.ui.View) –The view to send with the message. You can only send a view if this webhook is not partial and has state attached. A webhook has state attached if the webhook is managed by the library.
Added in version 2.0.
thread (
Snowflake) –Send a message to the specified thread. The thread will automatically be unarchived.
Added in version 2.0.
flags (Optional[
MessageFlags]) –The message flags being set for this message. Currently only
suppress_embedsis able to be set.Added in version 2.4.
suppress_embeds (Optional[
bool]) –Whether to suppress embeds on this message.
Added in version 2.4.
thread_name –
Name of thread to create (requires the webhook channel to be a forum or media channel).
Added in version 3.0.
- Raises:
HTTPException – Sending the message failed.
NotFound – This webhook was not found or has expired.
Forbidden – The authorization token for the webhook is incorrect.
InvalidArgument – You specified both
embedandembedsorfileandfiles.ValueError – The length of
embedswas invalid.InvalidArgument – There was no token associated with this webhook or
ephemeralwas passed with the improper webhook type or there was no state attached with this webhook when giving it a view.
- Returns:
If
waitisTruethen the message that was sent, otherwiseNone.- Return type:
Optional[
WebhookMessage]
- await fetch_message(id)¶
This function is a coroutine.
Retrieves a single
WebhookMessageowned by this webhook.Added in version 2.0.
- 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.
InvalidArgument – There was no token associated with this webhook.
- Returns:
The message asked for.
- Return type:
- await edit_message(message_id, *, content=..., embeds=..., embed=..., file=..., files=..., attachments=..., view=..., thread=..., allowed_mentions=None)¶
This function is 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.Added in version 1.6.
Changed in version 2.0: The edit is no longer in-place, instead the newly edited message is returned.
- Parameters:
message_id (
int) – The message ID to edit.content (Optional[
str]) – The content to edit the message with orNoneto clear it.embeds (List[
Embed]) – A list of embeds to edit the message with.embed (Optional[
Embed]) – The embed to edit the message with.Nonesuppresses the embeds. This should not be mixed with theembedsparameter.file (
File) –The file to upload. This cannot be mixed with
filesparameter.Added in version 2.0.
files (List[
File]) –A list of files to send with the content. This cannot be mixed with the
fileparameter.Added in version 2.0.
attachments (List[
Attachment]) –A list of attachments to keep in the message.
Added in version 2.0.
allowed_mentions (
AllowedMentions) – Controls the mentions being processed in this message. Seeabc.Messageable.send()for more information.view (Optional[
View]) –The updated view to update this message with. If
Noneis passed then the view is removed. The webhook must have state attached, similar tosend().Added in version 2.0.
thread (
Snowflake) –The thread that the message to be edited is in.
Added in version 3.0.
- Raises:
HTTPException – Editing the message failed.
Forbidden – Edited a message that is not yours.
InvalidArgument – You specified both
embedandembedsorfileandfiles.ValueError – The length of
embedswas invalid.InvalidArgument – There was no token associated with this webhook or the webhook had no state.
- Returns:
The newly edited webhook message.
- Return type:
- await delete_message(message_id, /)¶
This function is 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.Added 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 nextcord.WebhookMessage¶
Represents a message sent from your webhook.
This allows you to edit or delete a message sent by your webhook.
This inherits from
nextcord.Messagewith changes toedit()anddelete()to work.Added in version 1.6.
- await edit(content=..., embeds=..., embed=..., file=..., files=..., attachments=..., view=..., allowed_mentions=None, delete_after=None)¶
This function is a coroutine.
Edits the message.
Added in version 1.6.
Changed in version 2.0: The edit is no longer in-place, instead the newly edited message is returned.
- Parameters:
content (Optional[
str]) – The content to edit the message with orNoneto clear it.embeds (List[
Embed]) – A list of embeds to edit the message with.embed (Optional[
Embed]) – The embed to edit the message with.Nonesuppresses the embeds. This should not be mixed with theembedsparameter.file (
File) –The file to upload. This cannot be mixed with
filesparameter.Added in version 2.0.
files (List[
File]) –A list of files to send with the content. This cannot be mixed with the
fileparameter.Added in version 2.0.
attachments (List[
Attachment]) –A list of attachments to keep in the message. To keep all existing attachments, pass
message.attachments.Added in version 2.0.
allowed_mentions (
AllowedMentions) – Controls the mentions being processed in this message. Seeabc.Messageable.send()for more information.view (Optional[
View]) –The updated view to update this message with. If
Noneis passed then the view is removed.Added in version 2.0.
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.
Added in version 2.0.
- Raises:
HTTPException – Editing the message failed.
Forbidden – Edited a message that is not yours.
InvalidArgument – You specified both
embedandembedsorfileandfiles.ValueError – The length of
embedswas invalid.InvalidArgument – There was no token associated with this webhook.
- Returns:
The newly edited message.
- Return type:
- await 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. The waiting is done in the background and deletion failures are ignored.- Raises:
Forbidden – You do not have proper permissions to delete the message.
NotFound – The message was deleted already.
HTTPException – Deleting the message failed.
SyncWebhook¶
- clsSyncWebhook.from_url
- clsSyncWebhook.partial
- defdelete
- defdelete_message
- defedit
- defedit_message
- deffetch
- deffetch_message
- defis_authenticated
- defis_partial
- defsend
- class nextcord.SyncWebhook¶
Represents a synchronous Discord webhook.
For an asynchronous counterpart, see
Webhook.- 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.
- type¶
The type of the webhook.
Added in version 1.3.
- Type:
- token¶
The authentication token of the webhook. If this is
Nonethen the webhook cannot be used to make requests.- Type:
Optional[
str]
- user¶
The user this webhook was created by. If the webhook was received without authentication then this will be
None.- Type:
Optional[
abc.User]
- source_guild¶
The guild of the channel that this webhook is following. Only given if
typeisWebhookType.channel_follower.Added in version 2.0.
- Type:
Optional[
PartialWebhookGuild]
- source_channel¶
The channel that this webhook is following. Only given if
typeisWebhookType.channel_follower.Added in version 2.0.
- Type:
Optional[
PartialWebhookChannel]
- classmethod partial(id, token, *, session=..., bot_token=None)¶
Creates a partial
Webhook.- Parameters:
id (
int) – The ID of the webhook.token (
str) – The authentication token of the webhook.session (
requests.Session) – The session to use to send requests with. Note that the library does not manage the session and will not close it. If not given, therequestsauto session creation functions are used instead.bot_token (Optional[
str]) – The bot authentication token for authenticated requests involving the webhook.
- Returns:
A partial
Webhook. A partial webhook is just a webhook object with an ID and a token.- Return type:
- classmethod from_url(url, *, session=..., bot_token=None)¶
Creates a partial
Webhookfrom a webhook URL.- Parameters:
url (
str) – The URL of the webhook.session (
requests.Session) – The session to use to send requests with. Note that the library does not manage the session and will not close it. If not given, therequestsauto session creation functions are used instead.bot_token (Optional[
str]) – The bot authentication token for authenticated requests involving the webhook.
- 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:
- fetch(*, prefer_auth=True)¶
Fetches the current webhook.
This could be used to get a full webhook from a partial webhook.
Note
When fetching with an unauthenticated webhook, i.e.
is_authenticated()returnsFalse, then the returned webhook does not contain any user information.- Parameters:
prefer_auth (
bool) – Whether to use the bot token over the webhook token if available. Defaults toTrue.- Raises:
HTTPException – Could not fetch the webhook
NotFound – Could not find the webhook by this ID
InvalidArgument – This webhook does not have a token associated with it.
- Returns:
The fetched webhook.
- Return type:
- delete(*, reason=None, prefer_auth=True)¶
Deletes this Webhook.
- Parameters:
- 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, name=..., avatar=..., channel=None, prefer_auth=True)¶
Edits this Webhook.
Changed in version 2.1: The
avatarparameter now acceptsFile.- Parameters:
name (Optional[
str]) – The webhook’s new default name.avatar (Optional[Union[
bytes,File]]) – A bytes-like object,Filerepresenting the webhook’s new default avatar.channel (Optional[
abc.Snowflake]) – The webhook’s new channel. This requires an authenticated webhook.reason (Optional[
str]) –The reason for editing this webhook. Shows up on the audit log.
Added in version 1.4.
prefer_auth (
bool) – Whether to use the bot token over the webhook token if available. Defaults toTrue.
- Raises:
HTTPException – Editing the webhook failed.
NotFound – This webhook does not exist.
InvalidArgument – This webhook does not have a token associated with it or it tried editing a channel without authentication.
- Returns:
The newly edited webhook.
- Return type:
- send(content=..., *, username=..., avatar_url=..., tts=False, file=..., files=..., embed=..., embeds=..., allowed_mentions=..., thread=..., wait=False, thread_name=None)¶
Sends a message using the webhook.
The content must be a type that can convert to a string through
str(content).To upload a single file, the
fileparameter should be used with a singleFileobject.If the
embedparameter is provided, it must be of typeEmbedand it must be a rich embed type. You cannot mix theembedparameter with theembedsparameter, which must be alistofEmbedobjects to send.- Parameters:
content (
str) – The content of the message to send.wait (
bool) – Whether the server should wait before sending a response. This essentially means that the return type of this function changes fromNoneto aWebhookMessageif set toTrue.username (
str) – The username to send with this message. If no username is provided then the default username for the webhook is used.avatar_url (
str) – The avatar URL to send with this message. If no avatar URL is provided then the default avatar for the webhook is used. If this is not a string then it is explicitly cast usingstr.tts (
bool) – Indicates if the message should be sent using text-to-speech.file (
File) – The file to upload. This cannot be mixed withfilesparameter.files (List[
File]) – A list of files to send with the content. This cannot be mixed with thefileparameter.embed (
Embed) – The rich embed for the content to send. This cannot be mixed withembedsparameter.embeds (List[
Embed]) – A list of embeds to send with the content. Maximum of 10. This cannot be mixed with theembedparameter.allowed_mentions (
AllowedMentions) –Controls the mentions being processed in this message.
Added in version 1.4.
thread (
Snowflake) –The thread to send this message to.
Added in version 2.0.
thread_name –
Name of thread to create (requires the webhook channel to be a forum or media channel).
Added in version 3.0.
- Raises:
HTTPException – Sending the message failed.
NotFound – This webhook was not found.
Forbidden – The authorization token for the webhook is incorrect.
InvalidArgument – You specified both
embedandembedsorfileandfiles.ValueError – The length of
embedswas invalid.InvalidArgument – There was no token associated with this webhook.
- Returns:
If
waitisTruethen the message that was sent, otherwiseNone.- Return type:
Optional[
SyncWebhookMessage]
- fetch_message(id, /)¶
Retrieves a single
SyncWebhookMessageowned by this webhook.Added in version 2.0.
- 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.
InvalidArgument – There was no token associated with this webhook.
- Returns:
The message asked for.
- Return type:
- property avatar¶
Returns an
Assetfor the avatar the webhook has.If the webhook does not have a traditional avatar, an asset for the default avatar is returned instead.
- Type:
- property channel¶
The text channel this webhook belongs to.
If this is a partial webhook, then this will always return
None.- Type:
Optional[
TextChannel]
- property created_at¶
Returns the webhook’s creation time in UTC.
- Type:
- edit_message(message_id, *, content=..., embeds=..., embed=..., file=..., files=..., attachments=..., allowed_mentions=None, thread=...)¶
Edits a message owned by this webhook.
This is a lower level interface to
WebhookMessage.edit()in case you only have an ID.Added in version 1.6.
- Parameters:
message_id (
int) – The message ID to edit.content (Optional[
str]) – The content to edit the message with orNoneto clear it.embeds (List[
Embed]) – A list of embeds to edit the message with.embed (Optional[
Embed]) – The embed to edit the message with.Nonesuppresses the embeds. This should not be mixed with theembedsparameter.file (
File) – The file to upload. This cannot be mixed withfilesparameter.files (List[
File]) – A list of files to send with the content. This cannot be mixed with thefileparameter.attachments (List[
Attachment]) – A list of attachments to keep in the message.allowed_mentions (
AllowedMentions) – Controls the mentions being processed in this message. Seeabc.Messageable.send()for more information.thread (
Snowflake) –The thread that the message to be edited is in.
Added in version 3.0.
- Raises:
HTTPException – Editing the message failed.
Forbidden – Edited a message that is not yours.
InvalidArgument – You specified both
embedandembedsorfileandfiles.ValueError – The length of
embedswas invalid.InvalidArgument – There was no token associated with this webhook.
- property guild¶
The guild this webhook belongs to.
If this is a partial webhook, then this will always return
None.- Type:
Optional[
Guild]
- is_authenticated()¶
bool: Whether the webhook is authenticated with a bot token.Added in version 2.0.
- delete_message(message_id, /)¶
Deletes a message owned by this webhook.
This is a lower level interface to
WebhookMessage.delete()in case you only have an ID.Added 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.
SyncWebhookMessage¶
- class nextcord.SyncWebhookMessage¶
Represents a message sent from your webhook.
This allows you to edit or delete a message sent by your webhook.
This inherits from
nextcord.Messagewith changes toedit()anddelete()to work.Added in version 2.0.
- edit(content=..., embeds=..., embed=..., attachments=..., file=..., files=..., allowed_mentions=None)¶
Edits the message.
- Parameters:
content (Optional[
str]) – The content to edit the message with orNoneto clear it.embeds (List[
Embed]) – A list of embeds to edit the message with.embed (Optional[
Embed]) – The embed to edit the message with.Nonesuppresses the embeds. This should not be mixed with theembedsparameter.file (
File) – The file to upload. This cannot be mixed withfilesparameter.files (List[
File]) – A list of files to send with the content. This cannot be mixed with thefileparameter.attachments (List[
Attachment]) – A list of attachments to keep in the message. To keep all existing attachments, passmessage.attachments.allowed_mentions (
AllowedMentions) – Controls the mentions being processed in this message. Seeabc.Messageable.send()for more information.
- Raises:
HTTPException – Editing the message failed.
Forbidden – Edited a message that is not yours.
InvalidArgument – You specified both
embedandembedsorfileandfiles.ValueError – The length of
embedswas invalid.InvalidArgument – There was no token associated with this webhook.
- Returns:
The newly edited message.
- Return type:
- delete(*, delay=None)¶
Deletes the message.
- Parameters:
delay (Optional[
float]) – If provided, the number of seconds to wait before deleting the message. This 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.
Abstract Base Classes¶
An abstract base class (also known as an abc) is a class that models can inherit
to get their behaviour. Abstract base classes should not be instantiated.
They are mainly there for usage with isinstance() and issubclass().
This library has a module related to abstract base classes, in which all the ABCs are subclasses of
typing.Protocol.
Snowflake¶
- class nextcord.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 nextcord.abc.User¶
An ABC that details the common operations on a Discord user.
The following implement this ABC:
This ABC must also implement
Snowflake.- global_name¶
The user’s global name. This is represented in the UI as “Display Name”
Added in version 2.6.
- Type:
PrivateChannel¶
GuildChannel¶
- asyncclone
- asynccreate_invite
- asyncdelete
- asyncinvites
- asyncmove
- defoverwrites_for
- defpermissions_for
- asyncset_permissions
- class nextcord.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.
Note
Due to API inconsistencies, the position may not mirror the correct UI ordering
- Type:
- property changed_roles¶
Returns a list of roles that have been overridden from their default values in the
rolesattribute.- Type:
List[
Role]
- property created_at¶
Returns the channel’s creation time in UTC.
- Type:
- 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
Roleor aMemberand the value is the overwrite as aPermissionOverwrite.- Returns:
The channel’s permission overwrites.
- Return type:
Dict[Union[
Role,Member],PermissionOverwrite]
- property category¶
The category this channel belongs to.
If there is no category then this is
None.- Type:
Optional[
CategoryChannel]
- property permissions_synced¶
Whether or not the permissions for this channel are synced with the category it belongs to.
If there is no category then this is
False.Added in version 1.3.
- Type:
- property jump_url¶
Returns a URL that allows the client to jump to this channel.
Added in version 2.0.
- Type:
- permissions_for(obj, /)¶
Handles permission resolution for the
MemberorRole.This function takes into consideration the following cases:
Guild owner
Guild roles
Channel overrides
Member overrides
Timed-out members
If a
Roleis passed, then it checks the permissions someone with that role would have, which is essentially:The default role permissions
The permissions of the role used as a parameter
The default role permission overwrites
The permission overwrites of the role used as a parameter
Changed in version 2.3: Only
view_channelandread_message_historycan be returned for timed-out membersChanged in version 2.0: The object passed in can now be a role object.
- await delete(*, reason=None)¶
This function is a coroutine.
Deletes the channel.
You must have
manage_channelspermission 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, *, reason=None, **kwargs)¶
This function is a coroutine.
Sets the channel specific permission overwrites for a target in the channel.
The
targetparameter should either be aMemberor aRolethat belongs to guild.The
overwriteparameter, if given, must either beNoneorPermissionOverwrite. For convenience, you can pass in keyword arguments denotingPermissionsattributes. If this is done, then you cannot mix the keyword arguments with theoverwriteparameter.If the
overwriteparameter isNone, then the permission overwrites are deleted.You must have the
manage_rolespermission to use this.Note
This method replaces the old overwrites with the ones given.
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
PermissionOverwriteoverwrite = nextcord.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, orNoneto 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
RoleorMember.
- 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_channelspermission to do this.Added 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(*, beginning=None, end=None, before=None, after=None, offset=0, category=..., sync_permissions=False, reason=None)¶
This function is a coroutine.
A rich interface to help move a channel relative to other channels.
If exact position movement is required,
editshould be used instead.You must have the
manage_channelspermission to do this.Note
Voice channels will always be sorted below text channels. This is a Discord limitation.
Added in version 1.7.
Changed in version 2.4:
beginning,end,before,afterandreasonnow acceptNone.- Parameters:
beginning (Optional[
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 (Optional[
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 (Optional[
Snowflake]) – The channel that should be before our current channel. This is mutually exclusive withbeginning,end, andafter.after (Optional[
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 of2withbeginning=Truewould 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, andafterparameters.category (Optional[
Snowflake]) – The category to move this channel under. IfNoneis 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 (Optional[
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, max_age=0, max_uses=0, temporary=False, unique=True, target_type=None, target_user=None, target_application_id=None)¶
This function is a coroutine.
Creates an instant invite from a text or voice channel.
You must have the
create_instant_invitepermission 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 toFalsethen it will return a previously created invite.reason (Optional[
str]) – The reason for creating this invite. Shows up on the audit log.target_type (Optional[
InviteTarget]) –The type of target for the voice channel invite, if any.
Added in version 2.0.
target_user (Optional[
User]) –The user whose stream to display for this invite, required if
target_typeisInviteTarget.stream. The user must be streaming in the channel.Added in version 2.0.
target_application_id: –
Optional[
int]: The id of the embedded application for the invite, required iftarget_typeisInviteTarget.embedded_application.Added in version 2.0.
- 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_channelsto 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
- asyncforward
- defhistory
- asyncsend
- asynctrigger_typing
- deftyping
- class nextcord.abc.Messageable¶
An ABC that details the common operations on a model that can send messages.
The following implement this ABC:
- async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)¶
This function returns an async iterator.
Returns an async iterator that enables receiving the destination’s message history.
You must have
read_message_historypermissions to use this.Examples
Usage
counter = 0 async for message in channel.history(limit=200): if message.author == client.user: counter += 1
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 datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.after (Optional[Union[
Snowflake,datetime.datetime]]) – Retrieve messages after this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.around (Optional[Union[
Snowflake,datetime.datetime]]) – Retrieve messages around this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time. When using this argument, the maximum limit is 101. Note that if the limit is an even number then this will return at most limit + 1 messages.oldest_first (Optional[
bool]) – If set toTrue, return messages in oldest->newest order. Defaults toTrueifafteris 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
withandasync withwork with this.Example Usage:
async with channel.typing(): # simulate something heavy await asyncio.sleep(10) await channel.send('done!')
- await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, mention_author=None, view=None, flags=None, suppress_embeds=None)¶
This function is a coroutine.
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through
str(content). If the content is set toNone(the default), then theembedorembedsparameter must be provided.To upload a single file, the
fileparameter should be used with a singleFileobject. To upload multiple files, thefilesparameter should be used with alistofFileobjects. Specifying both parameters will lead to an exception.To upload a single embed, the
embedparameter should be used with a singleEmbedobject. To upload multiple embeds, theembedsparameter should be used with alistofEmbedobjects. Specifying both parameters will lead to an exception.- Parameters:
content (Optional[
str]) – The content of the message to send.tts (
bool) – Indicates if the message should be sent using text-to-speech.embed (
Embed) – The rich embed for the content.file (
File) – The file to upload.files (List[
File]) – A list of files to upload. Must be a maximum of 10.nonce (Union[
int,str]) – 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_mentionsare used instead.Added in version 1.4.
reference (Union[
Message,MessageReference,PartialMessage]) –A reference to the
Messageto 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_userattribute ofallowed_mentionsor by settingmention_author.Added in version 1.6.
mention_author (Optional[
bool]) –If set, overrides the
replied_userattribute ofallowed_mentions.Added in version 1.6.
view (
nextcord.ui.View) – A Discord UI View to add to the message.embeds (List[
Embed]) –A list of embeds to upload. Must be a maximum of 10.
Added in version 2.0.
stickers (Sequence[Union[
GuildSticker,StickerItem]]) –A list of stickers to upload. Must be a maximum of 3.
Added in version 2.0.
flags (Optional[
MessageFlags]) –The message flags being set for this message. Currently only
suppress_embedsis able to be set.Added in version 2.4.
suppress_embeds (Optional[
bool]) –Whether to suppress embeds on this message.
Added in version 2.4.
- Raises:
HTTPException – Sending the message failed.
Forbidden – You do not have the proper permissions to send the message.
InvalidArgument – The
fileslist is not of the appropriate size, you specified bothfileandfiles, or you specified bothembedandembeds, or thereferenceobject is not aMessage,MessageReferenceorPartialMessage
- Returns:
The message that was sent.
- Return type:
- await forward(message)¶
Forward a message to this channel.
- Parameters:
message (
Message) – The message to forward.note:: (..) – It is not possible to forward messages through interactions. It is only possible to forward a message to a channel as a message.
- Raises:
HTTPException – Forwarding/sending the message failed.
Forbidden – You do not have the proper permissions to send the message.
.. versionadded: – 3.0:
- await trigger_typing()¶
This function is a coroutine.
Triggers a typing indicator to the destination.
Typing indicator will go away after 10 seconds, or after a message is sent.
- await fetch_message(id, /)¶
This function is a coroutine.
Retrieves a single
Messagefrom the destination.- 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:
Connectable¶
- class nextcord.abc.Connectable¶
An ABC that details the common operations on a channel that can connect to a voice server.
The following implement this ABC:
Note
This ABC is not decorated with
typing.runtime_checkable(), so will failisinstance()/issubclass()checks.
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¶
- asyncedit
- defmentioned_in
- class nextcord.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.
- discriminator¶
The user’s discriminator.
Warning
This field is deprecated, and will only return if the user has not yet migrated to the new username update.
Deprecated since version 2.6.
- Type:
- system¶
Specifies if the user is a system user (i.e. represents Discord officially).
Added in version 1.3.
- Type:
- await edit(*, username=..., avatar=..., banner=...)¶
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.
Changed in version 2.0: The edit is no longer in-place, instead the newly edited client user is returned.
Changed in version 2.1: The
avatarparameter now acceptsFile,Attachment, andAsset.Added in version 3.0: The
bannerfield has been added.- Parameters:
username (
str) – The new username you wish to change to.avatar (Optional[Union[
bytes,Asset,Attachment,File]]) – A bytes-like object,File,Attachment, orAssetrepresenting the image to upload. Could beNoneto denote no avatar.banner (Optional[Union[
bytes,Asset,Attachment,File]]) – A bytes-like object,File,Attachment, orAssetrepresenting the image to upload. Could beNoneto denote no banner.
- Raises:
HTTPException – Editing your profile failed.
InvalidArgument – Wrong image format passed for
avatarand/orbanner.
- Returns:
The newly edited client user.
- Return type:
- property accent_color¶
Returns the user’s accent color, if applicable.
There is an alias for this named
accent_colour.Added in version 2.0.
Note
This information is only available via
Client.fetch_user().- Type:
Optional[
Colour]
- property accent_colour¶
Returns the user’s accent colour, if applicable.
There is an alias for this named
accent_color.Added in version 2.0.
Note
This information is only available via
Client.fetch_user().- Type:
Optional[
Colour]
- property avatar¶
Returns an
Assetfor the avatar the user has.If the user does not have a traditional avatar,
Noneis returned. If you want the avatar that a user has displayed, considerdisplay_avatar.- Type:
Optional[
Asset]
- property avatar_decoration¶
Returns the user’s avatar decoration, if applicable.
You can get the asset of the avatar decoration via
AvatarDecoration.asset.Added in version 3.2.
- Type:
Optional[
AvatarDecoration]
- property banner¶
Returns the user’s banner asset, if available.
Added in version 2.0.
Note
This information is only available via
Client.fetch_user().- 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.
- ..versionchanged:: 2.6
Added handling for the new username system for users without a discriminator.
- Type:
- property display_avatar¶
Returns the user’s display avatar.
For regular users this is just their default avatar or uploaded avatar.
Added in version 2.0.
- Type:
- property display_name¶
Returns the user’s display name.
This will return the name using the following hierachy:
Global Name (also known as ‘Display Name’ in the Discord UI)
Unique username
- Type:
- mentioned_in(message)¶
Checks if the user is mentioned in the specified message.
- property public_flags¶
The publicly available flags the user has.
- Type:
User¶
- asynccreate_dm
- asyncfetch_message
- asyncforward
- defhistory
- defmentioned_in
- asyncsend
- asynctrigger_typing
- deftyping
- class nextcord.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.
- discriminator¶
The user’s discriminator.
Warning
This field is deprecated, and will only return if the user has not yet migrated to the new username update.
Deprecated since version 2.6.
- Type:
- async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)¶
This function returns an async iterator.
Returns an async iterator that enables receiving the destination’s message history.
You must have
read_message_historypermissions to use this.Examples
Usage
counter = 0 async for message in channel.history(limit=200): if message.author == client.user: counter += 1
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 datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.after (Optional[Union[
Snowflake,datetime.datetime]]) – Retrieve messages after this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.around (Optional[Union[
Snowflake,datetime.datetime]]) – Retrieve messages around this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time. When using this argument, the maximum limit is 101. Note that if the limit is an even number then this will return at most limit + 1 messages.oldest_first (Optional[
bool]) – If set toTrue, return messages in oldest->newest order. Defaults toTrueifafteris 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
withandasync withwork with this.Example Usage:
async with channel.typing(): # simulate something heavy await asyncio.sleep(10) 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.
Added in version 1.7.
- Type:
List[
Guild]
- property accent_color¶
Returns the user’s accent color, if applicable.
There is an alias for this named
accent_colour.Added in version 2.0.
Note
This information is only available via
Client.fetch_user().- Type:
Optional[
Colour]
- property accent_colour¶
Returns the user’s accent colour, if applicable.
There is an alias for this named
accent_color.Added in version 2.0.
Note
This information is only available via
Client.fetch_user().- Type:
Optional[
Colour]
- property avatar¶
Returns an
Assetfor the avatar the user has.If the user does not have a traditional avatar,
Noneis returned. If you want the avatar that a user has displayed, considerdisplay_avatar.- Type:
Optional[
Asset]
- property avatar_decoration¶
Returns the user’s avatar decoration, if applicable.
You can get the asset of the avatar decoration via
AvatarDecoration.asset.Added in version 3.2.
- Type:
Optional[
AvatarDecoration]
- property banner¶
Returns the user’s banner asset, if available.
Added in version 2.0.
Note
This information is only available via
Client.fetch_user().- 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:
- await create_dm()¶
This function is a coroutine.
Creates a
DMChannelwith 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¶
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.
- ..versionchanged:: 2.6
Added handling for the new username system for users without a discriminator.
- Type:
- property display_avatar¶
Returns the user’s display avatar.
For regular users this is just their default avatar or uploaded avatar.
Added in version 2.0.
- Type:
- property display_name¶
Returns the user’s display name.
This will return the name using the following hierachy:
Global Name (also known as ‘Display Name’ in the Discord UI)
Unique username
- Type:
- await fetch_message(id, /)¶
This function is a coroutine.
Retrieves a single
Messagefrom the destination.- 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 forward(message)¶
Forward a message to this channel.
- Parameters:
message (
Message) – The message to forward.note:: (..) – It is not possible to forward messages through interactions. It is only possible to forward a message to a channel as a message.
- Raises:
HTTPException – Forwarding/sending the message failed.
Forbidden – You do not have the proper permissions to send the message.
.. versionadded: – 3.0:
- mentioned_in(message)¶
Checks if the user is mentioned in the specified message.
- property public_flags¶
The publicly available flags the user has.
- Type:
- await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, mention_author=None, view=None, flags=None, suppress_embeds=None)¶
This function is a coroutine.
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through
str(content). If the content is set toNone(the default), then theembedorembedsparameter must be provided.To upload a single file, the
fileparameter should be used with a singleFileobject. To upload multiple files, thefilesparameter should be used with alistofFileobjects. Specifying both parameters will lead to an exception.To upload a single embed, the
embedparameter should be used with a singleEmbedobject. To upload multiple embeds, theembedsparameter should be used with alistofEmbedobjects. Specifying both parameters will lead to an exception.- Parameters:
content (Optional[
str]) – The content of the message to send.tts (
bool) – Indicates if the message should be sent using text-to-speech.embed (
Embed) – The rich embed for the content.file (
File) – The file to upload.files (List[
File]) – A list of files to upload. Must be a maximum of 10.nonce (Union[
int,str]) – 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_mentionsare used instead.Added in version 1.4.
reference (Union[
Message,MessageReference,PartialMessage]) –A reference to the
Messageto 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_userattribute ofallowed_mentionsor by settingmention_author.Added in version 1.6.
mention_author (Optional[
bool]) –If set, overrides the
replied_userattribute ofallowed_mentions.Added in version 1.6.
view (
nextcord.ui.View) – A Discord UI View to add to the message.embeds (List[
Embed]) –A list of embeds to upload. Must be a maximum of 10.
Added in version 2.0.
stickers (Sequence[Union[
GuildSticker,StickerItem]]) –A list of stickers to upload. Must be a maximum of 3.
Added in version 2.0.
flags (Optional[
MessageFlags]) –The message flags being set for this message. Currently only
suppress_embedsis able to be set.Added in version 2.4.
suppress_embeds (Optional[
bool]) –Whether to suppress embeds on this message.
Added in version 2.4.
- Raises:
HTTPException – Sending the message failed.
Forbidden – You do not have the proper permissions to send the message.
InvalidArgument – The
fileslist is not of the appropriate size, you specified bothfileandfiles, or you specified bothembedandembeds, or thereferenceobject is not aMessage,MessageReferenceorPartialMessage
- Returns:
The message that was sent.
- Return type:
AvatarDecoration¶
- class nextcord.AvatarDecoration¶
Represents an avatar decoration. This is a cosmetic item that can be applied to a user’s avatar.
You can get this object via
User.avatar_decoration().Added in version 3.2.
- user¶
The user this avatar decoration belongs to.
- Type:
BaseUser
Attachment¶
- class nextcord.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
strand is hashable.- height¶
The attachment’s height, 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
urlin 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
Added in version 1.7.
- Type:
Optional[
str]
- description¶
The attachment’s description. This is used for alternative text in the Discord client.
Added in version 2.0.
- Type:
Optional[
str]
- duration_secs¶
The duration of the audio file (currently for voice messages).
Added in version 3.0.
- Type:
Optional[
float]
- 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,str]) – The file-like object to save this attachment to or the filename to use. If a filename is passed then a file is created with that filename and used instead.seek_begin (
bool) – Whether to seek to the beginning of the file after saving is successfully done.use_cached (
bool) – Whether to useproxy_urlrather thanurlwhen 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
bytesobject.Added in version 1.1.
- Parameters:
use_cached (
bool) – Whether to useproxy_urlrather thanurlwhen 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(*, filename=..., description=..., use_cached=False, spoiler=False, force_close=True)¶
This function is a coroutine.
Converts the attachment into a
Filesuitable for sending viaabc.Messageable.send().Added in version 1.3.
- Parameters:
filename (Optional[
str]) –The filename to use for the file. If not specified then the filename of the attachment is used instead.
Added in version 2.0.
description (Optional[
str]) –The description to use for the file. If not specified then the description of the attachment is used instead.
Added in version 2.0.
use_cached (
bool) –Whether to use
proxy_urlrather thanurlwhen 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.Added in version 1.4.
spoiler (
bool) –Whether the file is a spoiler.
Added in version 1.4.
force_close (
bool) –- Whether to forcibly close the bytes used to create the file
when
.close()is called. This will also make the file bytes unusable by flushing it from memory after it is sent or used once. Keep this enabled if you don’t wish to reuse the same bytes.
Added in version 2.2.
- 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:
- waveform¶
The base64 decoded data representing a sampled waveform (currently for voice messages).
Added in version 3.0.
- Type:
Optional[array[
int]]
- flags()¶
Optional[
AttachmentFlags]: The avaliable flags that the attachment has.Added in version 2.6.
Asset¶
- defis_animated
- asyncread
- defreplace
- asyncsave
- asyncto_file
- defwith_format
- defwith_size
- defwith_static_format
- class nextcord.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.
- 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.
- replace(*, size=..., format=..., static_format=...)¶
Returns a new asset with the passed components replaced.
- Parameters:
- Raises:
InvalidArgument – An invalid size or format was passed.
- Returns:
The newly updated asset.
- Return type:
- with_size(size, /)¶
Returns a new asset with the specified size.
- Parameters:
size (
int) – The new size of the asset.- Raises:
InvalidArgument – The asset had an invalid size.
- Returns:
The new updated asset.
- Return type:
- with_format(format, /)¶
Returns a new asset with the specified format.
- Parameters:
format (
str) – The new format of the asset.- Raises:
InvalidArgument – The asset had an invalid format.
- Returns:
The new updated asset.
- Return type:
- with_static_format(format, /)¶
Returns a new asset with the specified static format.
This only changes the format if the underlying asset is not animated. Otherwise, the asset is not changed.
- Parameters:
format (
str) – The new static format of the asset.- Raises:
InvalidArgument – The asset had an invalid format.
- Returns:
The new updated asset.
- Return type:
- await read()¶
This function is a coroutine.
Retrieves the content of this asset as a
bytesobject.- Raises:
DiscordException – There was no 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[
io.BufferedIOBase,os.PathLike]) – The file-like object to save this asset to or the filename to use. If a filename is passed then a file is created with that filename and used instead.seek_begin (
bool) – Whether to seek to the beginning of the file after saving is successfully done.
- Raises:
DiscordException – There was no internal connection state.
HTTPException – Downloading the asset failed.
NotFound – The asset was deleted.
- Returns:
The number of bytes written.
- Return type:
- await to_file(*, filename=..., description=None, spoiler=False, force_close=True)¶
This function is a coroutine.
Converts the asset into a
Filesuitable for sending viaabc.Messageable.send().Added in version 2.0.
- Parameters:
filename (Optional[
str]) – The filename of the file. If not provided, then the filename from the asset’s URL is used.description (Optional[
str]) – The description for the file.spoiler (
bool) – Whether the file is a spoiler.force_close (
bool) –Whether to forcibly close the bytes used to create the file when
.close()is called. This will also make the file bytes unusable by flushing it from memory after it is sent or used once. Keep this enabled if you don’t wish to reuse the same bytes.Added in version 2.2.
- Raises:
DiscordException – The asset does not have an associated state.
InvalidArgument – The asset is a unicode emoji.
TypeError – The asset is a sticker with lottie type.
HTTPException – Downloading the asset failed.
NotFound – The asset was deleted.
- Returns:
The asset as a file suitable for sending.
- Return type:
Message¶
- activity
- application
- attachments
- author
- channel
- channel_mentions
- clean_content
- components
- content
- created_at
- edited_at
- embeds
- flags
- guild
- id
- interaction
- interaction_metadata
- jump_url
- mention_everyone
- mentions
- nonce
- pinned
- raw_channel_mentions
- raw_mentions
- raw_role_mentions
- reactions
- reference
- role_mentions
- role_subscription
- snapshots
- stickers
- system_content
- thread
- tts
- type
- webhook_id
- asyncadd_reaction
- asyncclear_reaction
- asyncclear_reactions
- asynccreate_thread
- asyncdelete
- asyncedit
- asyncforward
- defis_system
- asyncpin
- asyncpublish
- asyncremove_reaction
- asyncreply
- defto_reference
- asyncunpin
- class nextcord.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
Memberthat sent the message. Ifchannelis a private channel or the user has the left the guild, then it is aUserinstead.
- 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.
- channel¶
The
TextChannelorThreadthat the message was sent from. Could be aDMChannelorGroupChannelif it’s a private message.- Type:
Union[
TextChannel,Thread,DMChannel,GroupChannel,PartialMessageable]
- reference¶
The message that this message references. This is only applicable to messages of type
MessageType.pins_add, crossposted messages created by a followed channel integration, or message replies.Added in version 1.5.
- Type:
Optional[
MessageReference]
- mention_everyone¶
Specifies if the message mentions everyone.
Note
This does not check if the
@everyoneor the@heretext is in the message itself. Rather this boolean indicates if either the@everyoneor the@heretext is in the message and it did end up mentioning.- Type:
- mentions¶
A list of
Memberthat were mentioned. If the message is in a private message then the list will be ofUserinstead. 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.GuildChannelthat 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
Rolethat 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]
- flags¶
Extra features of the message.
Added in version 1.3.
- Type:
- reactions¶
Reactions to a message. Reactions can be either custom emoji or standard unicode emoji.
- Type:
List[
Reaction]
- activity¶
The activity associated with this message. Sent with Rich-Presence related messages that for example, request joining, spectating, or listening to or with another member.
It is a dictionary with the following optional keys:
type: An integer denoting the type of message activity being requested.party_id: The party ID associated with the party.
- Type:
Optional[
dict]
- application¶
The rich presence enabled application associated with this message.
It is a dictionary with the following keys:
id: A string representing the application’s ID.name: A string representing the application’s name.description: A string representing the application’s description.icon: A string representing the icon ID of the application.cover_image: A string representing the embed’s image asset ID.
- Type:
Optional[
dict]
- stickers¶
A list of sticker items given to the message.
Added in version 1.6.
- Type:
List[
StickerItem]
- interaction¶
The interaction data of a message, if applicable.
Warning
This field is deprecated, use
interaction_metadatainstead.Deprecated since version 3.0.
- Type:
Optional[
MessageInteraction]
- interaction_metadata¶
The interaction metadata of a message. Present if the message is sent as a result of an interaction.
Added in version 3.0.
- Type:
Optional[
MessageInteractionMetadata]
- snapshots¶
A list of message snapshots that the message contains.
Added in version 3.0.
- Type:
List[
MessageSnapshot]
- role_subscription¶
The role subscription data of a message, if applicable.
Added in version 3.2.
- Type:
Optional[
MessageRoleSubscription]
- 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 created_at¶
The message’s creation time in UTC.
- Type:
- property edited_at¶
An aware UTC datetime object containing the edited time of the message.
- Type:
Optional[
datetime.datetime]
- property thread¶
The thread started from this message. None if no thread was started.
- Type:
Optional[
Thread]
- is_system()¶
bool: Whether the message is a system message.A system message is a message that is constructed entirely by the Discord API in response to something.
Added 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.defaultandMessageType.reply, this just returns the regularMessage.content. Otherwise this returns an English message denoting the contents of the system message.- 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_messagespermission.Changed in version 1.1: Added the new
delaykeyword-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=..., embed=..., embeds=..., attachments=..., suppress=..., delete_after=None, allowed_mentions=..., view=..., file=..., files=...)¶
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
suppresskeyword-only parameter was added.- Parameters:
content (Optional[
str]) – The new content to replace the message with. Could beNoneto remove the content.embed (Optional[
Embed]) – The new embed to replace the original with. Could beNoneto remove the embed.embeds (List[
Embed]) –The new embeds to replace the original with. Must be a maximum of 10. To remove all embeds
[]should be passed.Added in version 2.0.
attachments (List[
Attachment]) – A list of attachments to keep in the message. To keep all existing attachments, passmessage.attachments.suppress (
bool) – Whether to suppress embeds for the message. This removes all the embeds if set toTrue. If set toFalsethis brings the embeds back if they were suppressed. Using this parameter requiresmanage_messages.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_mentionsare used instead.Added in version 1.4.
view (Optional[
View]) – The updated view to update this message with. IfNoneis passed then the view is removed.file (Optional[
File]) –If provided, a new file to add to the message.
Added in version 2.0.
files (Optional[List[
File]]) –If provided, a list of new files to add to the message.
Added in version 2.0.
- Raises:
NotFound – The message was not found.
HTTPException – Editing the message failed.
Forbidden – Tried to suppress a message without permissions or edited a message’s content or embed that isn’t yours.
InvalidArgument – You specified both
embedandembedsorfileandfiles.
- Returns:
The edited message.
- Return type:
- await publish()¶
This function is a coroutine.
Publishes this message to your announcement channel.
You must have the
send_messagespermission to do this.If the message is not your own then the
manage_messagespermission is also 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_messagespermission 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.
Added 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_messagespermission 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.
Added 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_historypermission to use this. If nobody else has reacted to the message using this emoji, theadd_reactionspermission 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.
memberparameter is not you) then themanage_messagespermission is needed.The
memberparameter must represent a member and meet theabc.Snowflakeabc.- 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_messagespermission to use this.Added 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_messagespermission 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=...)¶
This function is a coroutine.
Creates a public thread from this message.
You must have
create_public_threadsin order to create a public thread from a message.The channel this message belongs in must be a
TextChannel.Added in version 2.0.
- Parameters:
- Raises:
Forbidden – You do not have permissions to create a thread.
HTTPException – Creating the thread failed.
InvalidArgument – This message does not have guild info attached.
- Returns:
The created thread.
- Return type:
- await reply(content=None, **kwargs)¶
This function is a coroutine.
A shortcut method to
abc.Messageable.send()to reply to theMessage.Added in version 1.6.
- Raises:
HTTPException – Sending the message failed.
Forbidden – You do not have the proper permissions to send the message.
InvalidArgument – The
fileslist is not of the appropriate size or you specified bothfileandfiles.
- Returns:
The message that was sent.
- Return type:
- await forward(channel)¶
Forward this message to a channel.
Note
It is not possible to forward messages through interactions. It is only possible to forward a message to a channel as a message.
- Parameters:
channel (
Messageable) – The channel to forward this message.- Raises:
HTTPException – Forwarding/sending the message failed.
Forbidden – You do not have the proper permissions to send the message.
.. versionadded: – 3.0:
- to_reference(*, fail_if_not_exists=True)¶
Creates a
MessageReferencefrom the current message.Added in version 1.6.
- Parameters:
fail_if_not_exists (
bool) –Whether replying using the message reference should raise
HTTPExceptionif the message no longer exists or Discord could not fetch the message.Added in version 1.7.
- Returns:
The reference to this message.
- Return type:
DeletedReferencedMessage¶
- class nextcord.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.
Added in version 1.6.
Reaction¶
- class nextcord.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)¶
This function returns an async iterator.
Returns an async iterator representing the users that have reacted to the message.
The
afterparameter must represent a member and meet theabc.Snowflakeabc.Examples
Usage
# I do not actually recommend doing this. async for user in reaction.users(): await channel.send(f'{user} has reacted with {reaction.emoji}!')
- Parameters:
limit (Optional[
int]) – The maximum number of results to return. If not provided, returns all the users who reacted to the message.after (Optional[
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 aMemberis in a guild message context. Sometimes it can be aUserif the member has left the guild.
- await remove(user)¶
This function is a coroutine.
Remove the reaction by the provided
Userfrom the message.If the reaction is not your own (i.e.
userparameter is not you) then themanage_messagespermission is needed.The
userparameter must represent a user or member and meet theabc.Snowflakeabc.- 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_messagespermission to use this.Added 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
- approximate_member_count
- approximate_presence_count
- banner
- bitrate_limit
- bots
- categories
- channels
- chunked
- created_at
- default_notifications
- default_role
- description
- discovery_splash
- emoji_limit
- emojis
- explicit_content_filter
- features
- filesize_limit
- forum_channels
- humans
- icon
- id
- invites_disabled
- large
- max_members
- max_presences
- max_stage_video_channel_users
- max_video_channel_users
- me
- member_count
- members
- mfa_level
- name
- nsfw_level
- owner
- owner_id
- preferred_locale
- premium_progress_bar_enabled
- premium_subscriber_role
- premium_subscribers
- premium_subscription_count
- premium_tier
- public_updates_channel
- region
- roles
- rules_channel
- safety_alerts_channel
- scheduled_events
- self_role
- shard_id
- splash
- stage_channels
- stage_instances
- sticker_limit
- stickers
- system_channel
- system_channel_flags
- text_channels
- threads
- unavailable
- verification_level
- voice_channels
- voice_client
- asyncactive_threads
- defaudit_logs
- asyncauto_moderation_rules
- asyncban
- defbans
- asyncbulk_ban
- defby_category
- asyncchange_voice_state
- asyncchunk
- asynccreate_auto_moderation_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
- asyncdelete_emoji
- asyncdelete_sticker
- asyncedit
- asyncedit_role_positions
- asyncedit_widget
- asyncestimate_pruned_members
- asyncfetch_auto_moderation_rule
- asyncfetch_ban
- asyncfetch_channel
- asyncfetch_channels
- asyncfetch_emoji
- asyncfetch_emojis
- asyncfetch_member
- deffetch_members
- asyncfetch_role
- asyncfetch_roles
- asyncfetch_scheduled_event
- deffetch_scheduled_events
- asyncfetch_sticker
- asyncfetch_stickers
- defget_application_commands
- defget_channel
- defget_channel_or_thread
- defget_member
- defget_member_named
- defget_role
- defget_scheduled_event
- defget_stage_instance
- defget_thread
- asyncintegrations
- asyncinvites
- asynckick
- asyncleave
- defparse_channel_mentions
- defparse_mentions
- defparse_role_mentions
- asyncprune_members
- asyncquery_members
- asyncrollout_application_commands
- asyncsync_application_commands
- asynctemplates
- asyncunban
- asyncvanity_invite
- asyncwebhooks
- asyncwidget
- class nextcord.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.
- stickers¶
All stickers that the guild owns.
Added in version 2.0.
- Type:
Tuple[
GuildSticker, …]
- region¶
The region the guild belongs on. There is a chance that the region will be a
strif the value is not recognised by the enumerator.- Type:
- afk_channel¶
The channel that denotes the AFK channel.
Noneif it doesn’t exist.- Type:
Optional[
VoiceChannel]
- owner_id¶
The guild owner’s ID. Use
Guild.ownerinstead.- Type:
Indicates if the guild is unavailable. If this is
Truethen the reliability of other attributes outside ofGuild.idis 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_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.
Added in version 1.4.
- Type:
Optional[
int]
- 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:
- verification_level¶
The guild’s verification level.
- Type:
- explicit_content_filter¶
The guild’s explicit content filter.
- Type:
- default_notifications¶
The guild’s notification settings.
- Type:
- features¶
A list of features that the guild has. The features that a guild can have are subject to arbitrary change by Discord.
They are currently as follows:
ANIMATED_BANNER: Guild can upload an animated banner.ANIMATED_ICON: Guild can upload an animated icon.AUTO_MODERATION: Guild has set up auto moderation rules.APPLICATION_COMMAND_PERMISSIONS_V2: Guild is using the old permissions configuration behavior.BANNER: Guild can upload and use a banner. (i.e.banner)COMMUNITY: Guild is a community server.DEVELOPER_SUPPORT_SERVER: Guild has been set as a support server on the App Directory.DISCOVERABLE: Guild shows up in Server Discovery.ENHANCED_ROLE_COLORS: Guild has enhanced role colors enabled (gradients, holographic).FEATURABLE: Guild is able to be featured in Server Discovery.INVITES_DISABLED: Guild has paused invites, preventing new users from joining.INVITE_SPLASH: Guild’s invite page can have a special splash.MEMBER_VERIFICATION_GATE_ENABLED: Guild has Membership Screening enabled.MONETIZATION_ENABLED: Guild has enabled monetization.MORE_STICKERS: Guild has increased custom sticker slots.NEWS: Guild can create news channels.PARTNERED: Guild is a partnered server.PREVIEW_ENABLED: Guild can be viewed before being accepted via Membership Screening.RAID_ALERTS_DISABLED: Guild disabled alerts for join raids in the configured safety alerts channel.ROLE_ICONS: Guild is able to set role icons.TICKETED_EVENTS_ENABLED: Guild has enabled ticketed events.VANITY_URL: Guild can have a vanity invite URL (e.g. discord.gg/discord-api).VERIFIED: Guild is a verified server.VIP_REGIONS: Guild has VIP voice regions.WELCOME_SCREEN_ENABLED: Guild has enabled the welcome screen.ROLE_SUBSCRIPTIONS_ENABLED: Guild has enabled role subscriptions.ROLE_SUBSCRIPTIONS_AVAILABLE_FOR_PURCHASE: Guild has role subscriptions that can be purchased.
- Type:
List[
str]
The premium tier for this guild. Corresponds to “Boost Level” 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]
- approximate_member_count¶
The approximate number of members in the guild. This is
Noneunless the guild is obtained usingClient.fetch_guild()withwith_counts=True.Added in version 2.0.
- Type:
Optional[
int]
- approximate_presence_count¶
The approximate number of members currently active in the guild. This includes idle, dnd, online, and invisible members. Offline members are excluded. This is
Noneunless the guild is obtained usingClient.fetch_guild()withwith_counts=True.Added in version 2.0.
- Type:
Optional[
int]
- max_stage_video_channel_users¶
The maximum amount of users in a stage channel when video is being broadcasted.
Added in version 2.6.
- Type:
Optional[
int]
- async for ... in fetch_members(*, limit=1000, after=None)¶
This function returns an async iterator.
Returns an async iterator 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
membersinstead.Added in version 1.3.
All parameters are optional.
- Parameters:
limit (Optional[
int]) – The number of members to retrieve. Defaults to 1000. PassNoneto 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 datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local 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)
- async for ... in audit_logs(*, limit=100, before=None, after=None, oldest_first=None, user=None, action=None)¶
This function returns an async iterator.
Returns an async iterator that enables receiving the guild’s audit logs.
You must have the
view_audit_logpermission to use this.Examples
Getting the first 100 entries:
async for entry in guild.audit_logs(limit=100): print(f'{entry.user} did {entry.action} to {entry.target}')
Getting entries for a specific action:
async for entry in guild.audit_logs(action=nextcord.AuditLogAction.ban): print(f'{entry.user} banned {entry.target}')
Getting entries made by a specific user:
entries = [entry async for entry in guild.audit_logs(limit=None, user=guild.me)] await channel.send(f'I made {len(entries)} moderation actions.')
- Parameters:
limit (Optional[
int]) – The number of entries to retrieve. IfNoneretrieve all entries.before (Optional[Union[
abc.Snowflake,datetime.datetime]]) – Retrieve entries before this date or entry. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.after (Optional[Union[
abc.Snowflake,datetime.datetime]]) – Retrieve entries after this date or entry. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.oldest_first (Optional[
bool]) – If set toTrue, return entries in oldest->newest order. Defaults toTrueifafteris specified, otherwiseFalse.user (Optional[
abc.Snowflake]) – The moderator to filter entries from.action (Optional[
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 channels¶
A list of channels that belong to this guild.
- Type:
List[
abc.GuildChannel]
- property threads¶
A list of threads that you have permission to view.
Added in version 2.0.
- Type:
List[
Thread]
- property large¶
Indicates if the guild is a ‘large’ guild.
A large guild is defined as having more than
large_thresholdcount members, which for this library is set to the maximum of 250.- Type:
- property invites_disabled¶
Indicates if the guild’s invites are paused.
Added in version 2.4.
- Type:
- property voice_channels¶
A list of voice channels that belong to this guild.
This is sorted by the position and are in UI order from top to bottom.
- Type:
List[
VoiceChannel]
- property stage_channels¶
A list of stage channels that belong to this guild.
Added 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.userexcept an instance ofMember. This is essentially used to get the member version of yourself.- Type:
- property voice_client¶
Returns the
VoiceProtocolassociated with this guild, if any.- Type:
Optional[
VoiceProtocol]
- property text_channels¶
A list of text channels that belong to this guild.
This is sorted by the position and are in UI order from top to bottom.
- Type:
List[
TextChannel]
- property categories¶
A list of categories that belong to this guild.
This is sorted by the position and are in UI order from top to bottom.
- Type:
List[
CategoryChannel]
- property forum_channels¶
A list of forum channels that belong to this guild.
This is sorted by the position and are in UI order from top to bottom.
- Type:
List[
ForumChannel]
- property scheduled_events¶
A list of scheduled events in this guild.
Added in version 2.0.
- Type:
List[
ScheduledEvent]
] Whether the premium boost progress bar is enabled.
Added in version 2.6.
- Type:
Optional[
bool
- by_category()¶
Returns every
CategoryChanneland 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_or_thread(channel_id, /)¶
Returns a channel or thread with the given ID.
Added in version 2.0.
- Parameters:
channel_id (
int) – The ID to search for.- Returns:
The returned channel or thread or
Noneif not found.- Return type:
Optional[Union[
Thread,abc.GuildChannel]]
- get_channel(channel_id, /)¶
Returns a channel with the given ID.
Note
This does not search for threads.
- Parameters:
channel_id (
int) – The ID to search for.- Returns:
The returned channel or
Noneif not found.- Return type:
Optional[
abc.GuildChannel]
- get_thread(thread_id, /)¶
Returns a thread with the given ID.
Added in version 2.0.
- property system_channel¶
Returns the guild’s channel used for system messages.
If no channel is set, then this returns
None.- Type:
Optional[
TextChannel]
- property system_channel_flags¶
Returns the guild’s system channel settings.
- Type:
- 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.Added 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.Added in version 1.4.
- Type:
Optional[
TextChannel]
- property safety_alerts_channel¶
Returns the guild’s channel where admins and moderators of the guild receive safety alerts from Discord. The guild must be a Community guild.
If no channel is set then this returns
None.Added in version 2.6.
- Type:
Optional[
TextChannel]
- property sticker_limit¶
The maximum number of sticker slots this guild has.
Added in version 2.0.
- Type:
- property filesize_limit¶
The maximum number of bytes files can have when uploaded to this guild.
- Type:
- property bots¶
A list of bots that belong to this guild.
Warning
Due to a Discord limitation, in order for this attribute to remain up-to-date and accurate, it requires
Intents.membersto be specified.Added in version 2.0.
- Type:
List[
Member]
- property humans¶
A list of user accounts that belong to this guild.
Warning
Due to a Discord limitation, in order for this attribute to remain up-to-date and accurate, it requires
Intents.membersto be specified.Added in version 2.0.
- Type:
List[
Member]
- get_member(user_id, /)¶
Returns a member with the given ID.
A list of members who have “boosted” this guild.
- Type:
List[
Member]
- property roles¶
Returns a
listof the guild’s roles in hierarchy order.The first element of this list will be the lowest role in the hierarchy.
- Type:
List[
Role]
- get_role(role_id, /)¶
Returns a role with the given ID.
Gets the premium subscriber role, AKA “boost” role, in this guild.
Added in version 1.6.
- Type:
Optional[
Role]
- property self_role¶
Gets the role associated with this client’s user, if any.
Added in version 1.6.
- Type:
Optional[
Role]
- property stage_instances¶
Returns a
listof the guild’s stage instances that are currently running.Added in version 2.0.
- Type:
List[
StageInstance]
- get_stage_instance(stage_instance_id, /)¶
Returns a stage instance with the given ID.
Added in version 2.0.
- Parameters:
stage_instance_id (
int) – The ID to search for.- Returns:
The stage instance or
Noneif not found.- Return type:
Optional[
StageInstance]
- property discovery_splash¶
Returns the guild’s discovery splash asset, if available.
- Type:
Optional[
Asset]
- property member_count¶
Returns the true member count, if available.
Warning
Due to a Discord limitation, in order for this attribute to remain up-to-date and accurate, it requires
Intents.membersto be specified.- Type:
Optional[
int]
- property chunked¶
Returns a boolean indicating if the guild is “chunked”.
A chunked guild means that
member_countis equal to the number of members stored in the internalmemberscache.If this value returns
False, then you should request for offline members.- Type:
- property created_at¶
Returns the guild’s creation time in UTC.
- Type:
- 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,
Noneis returned.
- await create_text_channel(name, *, reason=None, category=None, position=..., topic=..., slowmode_delay=..., nsfw=..., overwrites=..., default_thread_slowmode_delay=...)¶
This function is a coroutine.
Creates a
TextChannelfor the guild.Note that you need the
manage_channelspermission to create the channel.The
overwritesparameter can be used to create a ‘secret’ channel upon creation. This parameter expects adictof overwrites with the target (either aMemberor aRole) as the key and aPermissionOverwriteas 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: nextcord.PermissionOverwrite(read_messages=False), guild.me: nextcord.PermissionOverwrite(read_messages=True) } channel = await guild.create_text_channel('secret', overwrites=overwrites)
- Parameters:
name (
str) – The channel’s name.overwrites (Dict[Union[
Role,Member],PermissionOverwrite]) – Adictof target (either a role or a member) toPermissionOverwriteto 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 (
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 is21600.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, *, reason=None, category=None, position=..., bitrate=..., user_limit=..., rtc_region=..., video_quality_mode=..., overwrites=...)¶
This function is a coroutine.
This is similar to
create_text_channel()except makes aVoiceChannelinstead.- Parameters:
name (
str) – The channel’s name.overwrites (Dict[Union[
Role,Member],PermissionOverwrite]) – Adictof target (either a role or a member) toPermissionOverwriteto 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.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
Noneindicates automatic voice region detection.Added in version 1.7.
video_quality_mode (
VideoQualityMode) –The camera video quality for the voice channel’s participants.
Added in version 2.0.
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_stage_channel(name, *, topic, position=..., overwrites=..., category=None, bitrate=None, user_limit=None, nsfw=None, rtc_region=..., video_quality_mode=None, reason=None)¶
This function is a coroutine.
This is similar to
create_text_channel()except makes aStageChannelinstead.Added in version 1.7.
- Parameters:
name (
str) – The channel’s name.topic (
str) – The new channel’s topic.overwrites (Dict[Union[
Role,Member],PermissionOverwrite]) – Adictof target (either a role or a member) toPermissionOverwriteto 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.bitrate (Optional[
int]) –The channel’s preferred audio bitrate in bits per second.
Added in version 2.6.
user_limit (
int) –The channel’s limit for number of members that can be in a voice channel.
Added in version 2.6.
rtc_region (Optional[
VoiceRegion]) –The region for the voice channel’s voice communication. A value of
Noneindicates automatic voice region detection.Added in version 2.6.
nsfw (
bool) –To mark the channel as NSFW or not.
Added in version 2.6.
video_quality_mode (
VideoQualityMode) –The camera video quality for the voice channel’s participants.
Added in version 2.6.
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_category(name, *, overwrites=..., reason=None, position=...)¶
This function is a coroutine.
Same as
create_text_channel()except makes aCategoryChannelinstead.Note
The
categoryparameter 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_forum_channel(name, *, topic, position=..., overwrites=..., category=None, default_thread_slowmode_delay=..., default_reaction=..., available_tags=..., reason=None, default_sort_order=..., default_forum_layout=None)¶
This function is a coroutine.
This is similar to
create_text_channel()except makes aForumChannelinstead.Added in version 2.1.
Changed in version 2.5: Added the
default_forum_layoutparameter.- Parameters:
name (
str) – The channel’s name.topic (
str) – The new channel’s topic.overwrites (Dict[Union[
Role,Member],PermissionOverwrite]) – Adictof target (either a role or a member) toPermissionOverwriteto 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.reason (Optional[
str]) – The reason for creating this channel. Shows up on the audit log.default_sort_order (Optional[
SortOrderType]) –The default sort order used to sort posts in this channel.
Added in version 2.3.
default_thread_slowmode_delay (
int) –The default slowmode delay for threads created in this channel. Must be between
0and21600.Added in version 2.4.
default_reaction (Optional[Union[
Emoji,PartialEmoji,str]]) –The default reaction for threads created in this channel.
Added in version 2.4.
available_tags (List[
ForumTag]) –The available tags for threads created in this channel.
Added in version 2.4.
default_forum_layout (Optional[
ForumLayoutType]) – The default layout type used to display posts in this forum.
- 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=..., reason=None, position=...)¶
This function is a coroutine.
Same as
create_text_channel()except makes aCategoryChannelinstead.Note
The
categoryparameter 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(*, reason=..., name=..., description=..., icon=..., banner=..., splash=..., discovery_splash=..., community=..., region=..., afk_channel=..., owner=..., afk_timeout=..., default_notifications=..., verification_level=..., explicit_content_filter=..., vanity_code=..., system_channel=..., system_channel_flags=..., preferred_locale=..., rules_channel=..., public_updates_channel=..., invites_disabled=..., premium_progress_bar_enabled=...)¶
This function is a coroutine.
Edits the guild.
You must have the
manage_guildpermission to edit the guild.Changed in version 1.4: The
rules_channelandpublic_updates_channelkeyword-only parameters were added.Changed in version 2.0: The
discovery_splashandcommunitykeyword-only parameters were added.Changed in version 2.0: The newly updated guild is returned.
Changed in version 2.1: The
icon,banner,splash,discovery_splashparameters now acceptFile,Attachment, andAsset.Changed in version 2.4: The
invites_disabledparameter has been added.Changed in version 2.6: The
premium_progress_bar_enabledparameter has been added.- Parameters:
name (
str) – The new name of the guild.description (Optional[
str]) – The new description of the guild. Could beNonefor no description. This is only available to guilds that containPUBLICinGuild.features.icon (Optional[Union[
bytes,Asset,Attachment,File]]) – A bytes-like object,File,Attachment, orAssetrepresenting the icon. Only PNG/JPEG is supported. GIF is only available to guilds that containANIMATED_ICONinGuild.features. Could beNoneto denote removal of the icon.banner (Optional[Union[
bytes,Asset,Attachment,File]]) – A bytes-like object,File,Attachment, orAssetrepresenting the banner. Could beNoneto denote removal of the banner. This is only available to guilds that containBANNERinGuild.features.splash (Optional[Union[
bytes,Asset,Attachment,File]]) – A bytes-like object,File,Attachment, orAssetrepresenting the invite splash. Only PNG/JPEG supported. Could beNoneto denote removing the splash. This is only available to guilds that containINVITE_SPLASHinGuild.features.discovery_splash (Optional[Union[
bytes,Asset,Attachment,File]]) – A bytes-like object,File,Attachment, orAssetrepresenting the discovery splash. Only PNG/JPEG supported. Could beNoneto denote removing the splash. This is only available to guilds that containDISCOVERABLEinGuild.features.community (
bool) – Whether the guild should be a Community guild. If set toTrue, bothrules_channelandpublic_updates_channelparameters are required.region (Union[
str,VoiceRegion]) – The new region for the guild’s voice communication.afk_channel (Optional[
VoiceChannel]) – The new channel that is the AFK channel. Could beNonefor 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 beNonefor 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-USorjaorzh-CN.rules_channel (Optional[
TextChannel]) – The new channel that is used for rules. This is only available to guilds that containPUBLICinGuild.features. Could beNonefor 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 containPUBLICinGuild.features. Could beNonefor no public updates channel.invites_disabled (
bool) – Whether the invites should be paused for the guild. This will prevent new users from joining said guild.premium_progress_bar_enabled (
bool) – Whether the premium guild boost progress bar is enabled.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
iconis 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.
- Returns:
The newly updated guild. Note that this has the same limitations as mentioned in
Client.fetch_guild()and may not have full data.- Return type:
- await fetch_channels()¶
This function is a coroutine.
Retrieves all
abc.GuildChannelthat the guild has.Note
This method is an API call. For general usage, consider
channelsinstead.Added 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:
Sequence[
abc.GuildChannel]
- await active_threads()¶
This function is a coroutine.
Returns a list of active
Threadthat the client can access.This includes both private and public threads.
Added in version 2.0.
- Raises:
HTTPException – The request to get the active threads failed.
- Returns:
The active threads
- Return type:
List[
Thread]
- await fetch_member(member_id, /)¶
This function is a coroutine.
Retrieves a
Memberfrom a guild ID, and a member ID.Note
This method is an API call. If you have
Intents.membersand 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
BanEntryfor a user.You must have the
ban_memberspermission 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
BanEntryobject for the specified user.- Return type:
- await fetch_channel(channel_id, /)¶
This function is a coroutine.
Retrieves a
abc.GuildChannelorThreadwith the specified ID.Note
This method is an API call. For general usage, consider
get_channel_or_thread()instead.Added in version 2.0.
- Raises:
.InvalidData – An unknown channel type was received from Discord or the guild the channel belongs to is not the same as the one in this object points to.
.HTTPException – Retrieving the channel failed.
.NotFound – Invalid Channel ID.
.Forbidden – You do not have permission to fetch this channel.
- Returns:
The channel from the ID.
- Return type:
Union[
abc.GuildChannel,Thread]
- bans(*, limit=1000, before=None, after=None)¶
This function returns an async iterator.
Returns an async iterator that enables receiving the destination’s bans.
You must have the
ban_memberspermission to get this information.Changed in version 2.0: Due to a breaking change in Discord’s API, this now returns an
AsyncIteratorinstead of alist.Examples
Usage
counter = 0 async for ban in guild.bans(limit=200): if not ban.user.bot: counter += 1
All parameters are optional.
- Parameters:
- Raises:
Forbidden – You do not have permissions to get the bans.
HTTPException – An error occurred while fetching the bans.
- Yields:
BanEntry– The ban with the ban data parsed.
- await prune_members(*, days, compute_prune_count=True, roles=..., reason=None)¶
This function is a coroutine.
Prunes the guild from its inactive members.
The inactive members are denoted if they have not logged on in
daysnumber of days and they have no roles.You must have the
manage_guildandkick_memberspermissions 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
rolesparameter.Changed in version 1.4: The
roleskeyword-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 toTruewhich 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 (List[
abc.Snowflake]) – A list ofabc.Snowflakethat 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_countisFalsethen this returnsNone.- Return type:
Optional[
int]
- await templates()¶
This function is a coroutine.
Gets the list of templates from this guild.
Requires
manage_guildpermissions.Added in version 1.7.
- await webhooks()¶
This function is a coroutine.
Gets the list of webhooks from this guild.
Requires
manage_webhookspermissions.
- await estimate_pruned_members(*, days, roles=...)¶
This function is a coroutine.
Similar to
prune_members()except instead of actually pruning members, it returns how many members it would prune from the guild had it been called.- Parameters:
days (
int) – The number of days before counting as inactive.roles (List[
abc.Snowflake]) –A list of
abc.Snowflakethat represent roles to include in the estimate. If a member has a role that is not specified, they’ll be excluded.Added 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_guildpermission 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]
Note
This method does not include the Guild’s vanity URL. To get the vanity URL
Invite, refer toGuild.vanity_invite().
- await create_template(*, name, description=...)¶
This function is a coroutine.
Creates a template for the guild.
You must have the
manage_guildpermission to do this.Added 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_guildpermission to do this.Added 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_guildpermission to do this.Added in version 1.4.
- Raises:
Forbidden – You do not have permission to create the integration.
HTTPException – Fetching the integrations failed.
- Returns:
The list of integrations that are attached to the guild.
- Return type:
List[
Integration]
- await fetch_stickers()¶
This function is a coroutine.
Retrieves a list of all
Stickers for the guild.Added in version 2.0.
Note
This method is an API call. For general usage, consider
stickersinstead.- Raises:
HTTPException – An error occurred fetching the stickers.
- Returns:
The retrieved stickers.
- Return type:
List[
GuildSticker]
- await fetch_sticker(sticker_id, /)¶
This function is a coroutine.
Retrieves a custom
Stickerfrom the guild.Added in version 2.0.
Note
This method is an API call. For general usage, consider iterating over
stickersinstead.- Parameters:
sticker_id (
int) – The sticker’s ID.- Raises:
NotFound – The sticker requested could not be found.
HTTPException – An error occurred fetching the sticker.
- Returns:
The retrieved sticker.
- Return type:
- await create_sticker(*, name, description=None, emoji, file, reason=None)¶
This function is a coroutine.
Creates a
Stickerfor the guild.You must have
manage_emojis_and_stickerspermission to do this.Added in version 2.0.
- Parameters:
name (
str) – The sticker name. Must be at least 2 characters.description (Optional[
str]) – The sticker’s description. Can beNone.emoji (
str) – The name of a unicode emoji that represents the sticker’s expression.file (
File) – The file of the sticker to upload.reason (
str) – The reason for creating this sticker. Shows up on the audit log.
- Raises:
Forbidden – You are not allowed to create stickers.
HTTPException – An error occurred creating a sticker.
- Returns:
The created sticker.
- Return type:
- await delete_sticker(sticker, *, reason=None)¶
This function is a coroutine.
Deletes the custom
Stickerfrom the guild.You must have
manage_emojis_and_stickerspermission to do this.Added in version 2.0.
- Parameters:
sticker (
abc.Snowflake) – The sticker you are deleting.reason (Optional[
str]) – The reason for deleting this sticker. Shows up on the audit log.
- Raises:
Forbidden – You are not allowed to delete stickers.
HTTPException – An error occurred deleting the sticker.
- await fetch_emojis()¶
This function is a coroutine.
Retrieves all custom
Emojis from the guild.Note
This method is an API call. For general usage, consider
emojisinstead.- 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
Emojifrom the guild.Note
This method is an API call. For general usage, consider iterating over
emojisinstead.- 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=..., reason=None)¶
This function is a coroutine.
Creates a custom
Emojifor the guild.There is currently a limit of 50 static and animated emojis respectively per guild, unless the guild has the
MORE_EMOJIfeature which extends the limit to 200.You must have the
manage_emojispermission to do this.Changed in version 2.1: The
imageparameter now acceptsFile,Attachment, andAsset.- Parameters:
name (
str) – The emoji name. Must be at least 2 characters.image (Union[
bytes,Asset,Attachment,File]) – The bytes-like object,File,Attachment, orAssetrepresenting the image data to use. Only JPG, PNG and GIF images are supported.roles (List[
Role]) – AlistofRoles 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 delete_emoji(emoji, *, reason=None)¶
This function is a coroutine.
Deletes the custom
Emojifrom the guild.You must have
manage_emojispermission to do this.- Parameters:
emoji (
abc.Snowflake) – The emoji you are deleting.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 fetch_roles(*, cache=False)¶
This function is a coroutine.
Retrieves all
Rolethat the guild has.Note
This method is an API call. For general usage, consider
rolesinstead.- Parameters:
cache (bool) – Whether or not to also update this guilds role cache. Defaults to
False.- Raises:
HTTPException – Retrieving the roles failed.
- Returns:
All roles in the guild.
- Return type:
List[
Role]
- await fetch_role(role_id, /)¶
This function is a coroutine.
Retrieve a
Rolefrom this guild by its ID.Added in version 3.0.
- Parameters:
role_id (int) – The ID of the role to fetch.
- Raises:
HTTPException – Retrieving the role failed.
NotFound – The role was not found.
- Returns:
The role in the guild.
- Return type:
- await create_role(*, name=..., permissions=..., color=..., colour=..., colors=..., colours=..., hoist=..., mentionable=..., icon=..., reason=None)¶
This function is a coroutine.
Creates a
Rolefor the guild.All fields are optional.
You must have the
manage_rolespermission to do this.Changed in version 1.6: Can now pass
inttocolourkeyword-only parameter.Changed in version 2.1: The
iconparameter now acceptsFile,Attachment, andAsset.- Parameters:
name (
str) – The role name. Defaults to ‘new role’.permissions (
Permissions) – The permissions to have. Defaults to no permissions.colour (Union[
Colour,int]) – The colour for the role. Defaults toColour.default(). This is aliased tocoloras 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[Union[
str,bytes,Asset,Attachment,File]]) – The icon of the role. Supports unicode emojis and imagesreason (Optional[
str]) – The reason for creating this role. Shows up on the audit log.
- Raises:
Forbidden – You do not have permissions to create the role.
HTTPException – Creating the role failed.
InvalidArgument – An invalid keyword argument was given.
- Returns:
The newly created role.
- Return type:
- await edit_role_positions(positions, *, reason=None)¶
This function is a coroutine.
Bulk edits a list of
Rolein the guild.You must have the
manage_rolespermission to do this.Added 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.Snowflakeabc.You must have the
kick_memberspermission 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_seconds=None)¶
This function is a coroutine.
Bans a user from the guild.
The user must meet the
abc.Snowflakeabc.You must have the
ban_memberspermission to do this.For backwards compatibility reasons, by default one day worth of messages will be deleted.
Changed in version 3.0:
delete_message_dayshas been removed in favor ofdelete_message_seconds.- Parameters:
user (
abc.Snowflake) – The user to ban from their guild.delete_message_seconds (Optional[
int]) –The number of seconds worth of messages to delete from the user in the guild. The minimum is 0 and the maximum is 604800 (7 days).
Added in version 2.3.
reason (Optional[
str]) – The reason the user got banned.
- Raises:
Forbidden – You do not have the proper permissions to ban.
HTTPException – Banning failed.
- await bulk_ban(users, *, delete_message_seconds=None, reason=None)¶
This function is a coroutine.
Bans a list of users. This is similar to
Guild.ban()except it bulk bans multiple users.You must have the
ban_membersandmanage_guildpermissions to do this.Added in version 3.0.
- Parameters:
users (List[
abc.Snowflake]) – The users to ban from a guild.delete_message_seconds (Optional[
int]) –The number of seconds worth of messages to delete from these users. Can range from 0 to 604800 seconds (7 days).
Defaults to 0.
reason (Optional[
str]) – The reason these users got banned.
- Raises:
Forbidden – You do not have the proper permissions to bulk ban.
HTTPException – Bulk banning failed. This may occur if all provided users failed to be banned due to the following reasons: - The users are already banned - You do not have the proper permissions to ban a user
- Returns:
The failed and banned users in the form of
Object.- Return type:
- await unban(user, *, reason=None)¶
This function is a coroutine.
Unbans a user from the guild.
The user must meet the
abc.Snowflakeabc.You must have the
ban_memberspermission 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_URLinfeatures.You must have the
manage_guildpermission 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. If
Nonethen the guild does not have a vanity invite set.- Return type:
Optional[
Invite]
- 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 edit_widget(*, enabled=..., channel=...)¶
This function is a coroutine.
Edits the widget of the guild.
You must have the
manage_guildpermission to use thisAdded in version 2.0.
- Parameters:
- Raises:
Forbidden – You do not have permission to edit the widget.
HTTPException – Editing the widget failed.
- 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.
Added in version 1.5.
- Parameters:
cache (
bool) – Whether to cache the members as well.- Raises:
ClientException – The members intent is not enabled.
- Returns:
Returns a list of all the members in the guild.
- Return type:
Optional[List[
Member]]
- 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.
Added 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.Added 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.
Added 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.
Added in version 1.4.
- Parameters:
channel (Optional[
VoiceChannel]) – Channel the client wants to join. UseNoneto disconnect.self_mute (
bool) – Indicates if the client should be self-muted.self_deaf (
bool) – Indicates if the client should be self-deafened.
- fetch_scheduled_events(*, with_users=False)¶
This function returns an async iterator.
Returns an async iterator that enables receiving scheduled events on this guild.
Note
This method is an API call. For general usage, consider
scheduled_eventsinstead.Added in version 2.0.
- Parameters:
with_users (Optional[
bool]) – If the event should be received withScheduledEvent.usersThis defaults toFalse- the events’userswill be empty.- Raises:
HTTPException – Getting the events failed.
- Yields:
ScheduledEvent– The event with users if applicable
Examples
Usage
async for event in guild.fetch_scheduled_events(): print(event.name)
- get_scheduled_event(event_id)¶
Get a scheduled event from cache by id.
Note
This may not return the updated users, use
fetch_scheduled_event()if that is desired.- Parameters:
event_id (int) – The scheduled event id to fetch.
- Returns:
The event object, if found.
- Return type:
Optional[ScheduledEvent]
- await fetch_scheduled_event(event_id, *, with_users=False)¶
This function is a coroutine.
Fetch a scheduled event object.
Note
This is an api call, if updated users is not needed, consisder
get_scheduled_event()- Parameters:
- Returns:
The received event object
- Return type:
- await create_scheduled_event(*, name, entity_type, start_time, channel=..., metadata=..., privacy_level=ScheduledEventPrivacyLevel.guild_only, end_time=..., description=..., image=None, reason=None)¶
This function is a coroutine.
Create a new scheduled event object.
Changed in version 2.1: The
imageparameter now acceptsFile,Attachment, andAsset.- Parameters:
channel (
abc.GuildChannel) – The channel the event will happen in, if anymetadata (
EntityMetadata) – The metadata for the eventname (
str) – The name of the eventprivacy_level (
ScheduledEventPrivacyLevel) – The privacy level for the eventstart_time (
datetime.datetime) – The scheduled start timeend_time (
datetime.datetime) – The scheduled end timedescription (
str) – The description for the evententity_type (
ScheduledEventEntityType) – The type of eventimage (Optional[Union[
bytes,Asset,Attachment,File]]) – A bytes-like object,File,Attachment, orAssetrepresenting the cover image.reason (Optional[
str]) – The reason for creating this scheduled event. Shows up in the audit logs.
- Returns:
The created event object.
- Return type:
- get_application_commands(rollout=False)¶
Gets all application commands registered for this guild.
- Parameters:
rollout (
bool)
- await sync_application_commands(data=None, *, associate_known=True, delete_unknown=True, update_known=True, register_new=True)¶
This function is a coroutine. Syncs the locally added application commands with this Guild.
- Parameters:
data (Optional[List[
dict]]) – Data to use when comparing local application commands to what Discord has. Should be a list of application command data from Discord. If left asNone, it will be fetched if needed. Defaults toNone.associate_known (
bool) – If local commands that match a command already on Discord should be associated with each other. Defaults toTrue.delete_unknown (
bool) – If commands on Discord that don’t match a local command should be deleted. Defaults toTrue.update_known (
bool) – If commands on Discord have a basic match with a local command, but don’t fully match, should be updated. Defaults toTrue.register_new (
bool) – If a local command that doesn’t have a basic match on Discord should be added to Discord. Defaults toTrue.
- await rollout_application_commands(associate_known=True, delete_unknown=True, update_known=True, register_new=True)¶
This function is a coroutine. Rolls out application commands to the guild, associating, deleting, updating, and/or newly registering as needed.
- Parameters:
associate_known (
bool) – Whether commands on Discord that match a locally added command should be associated with each other. Defaults toTruedelete_unknown
update_known
register_new
- await auto_moderation_rules()¶
This function is a coroutine.
Get the list of auto moderation rules from this guild.
Requires the
manage_guildpermission.Added in version 2.1.
- Raises:
Forbidden – You do not have permission to fetch the auto moderation rules.
- Returns:
The auto moderation rules of this guild.
- Return type:
List[
AutoModerationRule]
- await fetch_auto_moderation_rule(rule_id, /)¶
This function is a coroutine.
Retrieves a
AutoModerationRulefrom this guild by its IDRequires the
manage_guildpermission.Added in version 2.1.
- Parameters:
rule_id (
int) – The ID of the auto moderation rule to fetch.- Raises:
NotFound – The requested rule could not be found.
Forbidden – You do not have permission to fetch auto moderation rules.
HTTPException – Fetching the rule failed.
- Returns:
The found auto moderation rule.
- Return type:
- await create_auto_moderation_rule(*, name, event_type, trigger_type, actions, trigger_metadata=None, enabled=None, exempt_roles=None, exempt_channels=None, reason=None)¶
This function is a coroutine.
Create a new auto moderation rule.
Requires the
manage_guildpermission.Added in version 2.1.
- Parameters:
name (
str) – The name to use for this rule.event_type (
AutoModerationEventType) – The type of event conteto listen to for this rule.actions (List[
AutoModerationAction]) – The actions to execute when this rule is triggered.trigger_type (
AutoModerationTriggerType) – The type of content that triggers this rule.trigger_metadata (Optional[
AutoModerationTriggerMetadata]) – The additional data to use to determine if this rule has been triggered.enabled (Optional[
bool]) – If this rule should be enabled.exempt_roles (Optional[List[
abc.Snowflake]]) – Roles that should be exempt from this rule.exempt_channels (Optional[List[
abc.Snowflake]]) – Channels that should be exempt from this rule.reason (Optional[
str]) – The reason for creating this rule. Shows in the audit log.
- Raises:
Forbidden – You do not have permission to create auto moderation rules.
HTTPException – Creating the rule failed.
InvalidArgument – An invalid type was passed for an argument.
- Returns:
The newly created auto moderation rule.
- Return type:
- parse_mentions(text)¶
Parses user mentions in a string and returns a list of
Memberobjects. If the member is not in the guild, aUserobject is returned for that member instead.Note
This does not include role or channel mentions. See
parse_role_mentions()forRoleobjects andparse_channel_mentions()forGuildChannelobjects.Note
Only members or users found in the cache will be returned. To get the IDs of all users mentioned, use
parse_raw_mentions()instead.Added in version 2.2.
- parse_role_mentions(text)¶
Parses role mentions in a string and returns a list of
Roleobjects.Note
Only cached roles found in the
Guildwill be returned. To get the IDs of all roles mentioned, useparse_raw_role_mentions()instead.Added in version 2.2.
- parse_channel_mentions(text)¶
Parses channel mentions in a string and returns a list of
GuildChannelobjects.Note
Only cached channels found in the
Guildwill be returned. To get the IDs of all channels mentioned, useparse_raw_channel_mentions()instead.Added in version 2.2.
- Parameters:
text (
str) – String to parse mentions in.- Returns:
List of
GuildChannelobjects that were mentioned in the string.- Return type:
List[
GuildChannel]
GuildPreview¶
- class nextcord.GuildPreview¶
Represents a Discord guild preview.
- stickers¶
All the stickers that the guild owns, if any.
- Type:
List[
GuildSticker]
- .. versionadded :: 2.6
Integration¶
- class nextcord.Integration¶
Represents a guild integration.
Added in version 1.4.
- account¶
The account linked to this integration.
- Type:
- await delete(*, reason=None)¶
This function is a coroutine.
Deletes the integration.
You must have the
manage_guildpermission to do this.- Parameters:
reason (
str) –The reason the integration was deleted. Shows up on the audit log.
Added in version 2.0.
- Raises:
Forbidden – You do not have permission to delete the integration.
HTTPException – Deleting the integration failed.
- class nextcord.IntegrationAccount¶
Represents an integration account.
Added in version 1.4.
- class nextcord.BotIntegration¶
Represents a bot integration on discord.
Added in version 2.0.
- account¶
The integration account information.
- Type:
- application¶
The application tied to this integration.
- Type:
- class nextcord.IntegrationApplication¶
Represents an application for a bot integration.
Added in version 2.0.
- class nextcord.StreamIntegration¶
Represents a stream integration for Twitch or YouTube.
Added in version 2.0.
- enable_emoticons¶
Whether emoticons should be synced for this integration (currently twitch only).
- Type:
Optional[
bool]
- expire_behaviour¶
The behaviour of expiring subscribers. Aliased to
expire_behavioras well.- Type:
- account¶
The integration account information.
- Type:
- synced_at¶
An aware UTC datetime representing when the integration was last synced.
- Type:
- property expire_behavior¶
An alias for
expire_behaviour.- Type:
- await edit(*, expire_behaviour=..., expire_grace_period=..., enable_emoticons=...)¶
This function is a coroutine.
Edits the integration.
You must have the
manage_guildpermission to do this.- Parameters:
expire_behaviour (
ExpireBehaviour) – The behaviour when an integration subscription lapses. Aliased toexpire_behavioras well.expire_grace_period (
int) – The period (in days) where the integration will ignore lapsed subscriptions.enable_emoticons (
bool) – Where emoticons should be synced for this integration (currently twitch only).
- Raises:
Forbidden – You do not have permission to edit the integration.
HTTPException – Editing the guild failed.
InvalidArgument –
expire_behaviourdid not receive aExpireBehaviour.
- await sync()¶
This function is a coroutine.
Syncs the integration.
You must have the
manage_guildpermission to do this.- Raises:
Forbidden – You do not have permission to sync the integration.
HTTPException – Syncing the integration failed.
Interaction¶
- asyncdelete_original_message
- asyncedit
- asyncedit_original_message
- defis_expired
- asyncoriginal_message
- asyncsend
- class nextcord.Interaction¶
Represents a Discord interaction.
An interaction happens when a user does an action that needs to be notified. Current examples are slash commands and components.
- x == y
Checks if two interactions are equal.
- x != y
Checks if two interactions are not equal.
- hash(x)
Returns the interaction’s hash.
Added in version 2.0.
Changed in version 2.1:
Interactionis now hashable.- type¶
The interaction type.
- Type:
- attached¶
The attached data of the interaction. This is used to store any data you may need inside the interaction for convenience. This data will stay on the interaction, even after a
Interaction.application_command_before_invoke().- Type:
InteractionAttached
- application_command¶
The application command that handled the interaction.
- Type:
Optional[
ApplicationCommand]
- authorizing_integration_owners¶
Mapping of installation contexts that the interaction was authorized for to related user or guild IDs. You can find out about this field in the official Discord documentation.
Added in version 3.0.
- Type:
Optional[Dict[
IntegrationType,int]]
- context¶
Context where the interaction was triggered from.
Added in version 3.0.
- Type:
Optional[
InteractionContextType]
- property created_at¶
An aware datetime in UTC representing the creation time of the interaction.
- Type:
- property expires_at¶
An aware datetime in UTC representing the time when the interaction will expire.
- Type:
- channel¶
The channel the interaction was sent from.
Note that due to a Discord limitation, DM channels are not resolved since there is no data to complete them. These are
PartialMessageableinstead.- Type:
Optional[Union[
abc.GuildChannel,PartialMessageable,Thread]]
- property permissions¶
The resolved permissions of the member in the channel, including overwrites.
In a non-guild context where this doesn’t apply, an empty permissions object is returned.
- Type:
- property app_permissions¶
The resolved permissions of the bot in the channel, including overwrites.
In a non-guild context where this doesn’t apply, an empty permissions object is returned.
- Type:
- response¶
Returns an object responsible for handling responding to the interaction.
A response can only be done once. If secondary messages need to be sent, consider using
followupinstead.- Type:
- await original_message()¶
This function is a coroutine.
Fetches the original interaction response message associated with the interaction.
If the interaction response was
InteractionResponse.send_message()then this would return the message that was sent using that response. Otherwise, this would return the message that triggered the interaction.Repeated calls to this will return a cached value.
- Raises:
HTTPException – Fetching the original response message failed.
ClientException – The channel for the message could not be resolved.
- Returns:
The original interaction response message.
- Return type:
- await edit_original_message(*, content=..., embeds=..., embed=..., file=..., files=..., attachments=..., view=..., allowed_mentions=None, components=None)¶
This function is a coroutine.
Edits the original interaction response message.
This is a lower level interface to
InteractionMessage.edit()in case you do not want to fetch the message and save an HTTP request.This method is also the only way to edit the original message if the message sent was ephemeral.
- Parameters:
content (Optional[
str]) – The content to edit the message with orNoneto clear it.embeds (List[
Embed]) – A list of embeds to edit the message with.embed (Optional[
Embed]) – The embed to edit the message with.Nonesuppresses the embeds. This should not be mixed with theembedsparameter.file (
File) – The file to upload. This cannot be mixed withfilesparameter.files (List[
File]) – A list of files to send with the content. This cannot be mixed with thefileparameter.attachments (List[
Attachment]) – A list of attachments to keep in the message. To keep existing attachments, you must fetch the message withoriginal_message()and passmessage.attachmentsto this parameter.allowed_mentions (
AllowedMentions) – Controls the mentions being processed in this message. Seeabc.Messageable.send()for more information.view (Optional[
View]) – The updated view to update this message with. IfNoneis passed then the view is removed.
- Raises:
HTTPException – Editing the message failed.
Forbidden – Edited a message that is not yours.
InvalidArgument – You specified both
embedandembedsorfileandfiles.ValueError – The length of
embedswas invalid.
- Returns:
The newly edited message.
- Return type:
- await delete_original_message(*, delay=None)¶
This function is a coroutine.
Deletes the original interaction response message.
This is a lower level interface to
InteractionMessage.delete()in case you do not want to fetch the message and save an HTTP request.- Parameters:
delay (Optional[
float]) – If provided, the number of seconds to wait before deleting the message. The waiting is done in the background and deletion failures are ignored.- Raises:
HTTPException – Deleting the message failed.
Forbidden – Deleted a message that is not yours.
- await send(content=None, *, embed=..., embeds=..., file=..., files=..., view=..., tts=False, delete_after=None, allowed_mentions=..., flags=None, ephemeral=None, suppress_embeds=None, components=None)¶
This function is a coroutine.
This is a shorthand function for helping in sending messages in response to an interaction. If the interaction has not been responded to,
InteractionResponse.send_message()is used. If the responseis_done()then the message is sent viaInteraction.followupusingWebhook.sendinstead.- Raises:
HTTPException – Sending the message failed.
NotFound – The interaction has expired or the interaction has been responded to but the followup webhook is expired.
Forbidden – The authorization token for the webhook is incorrect.
InvalidArgument – You specified both
embedandembedsorfileandfiles.ValueError – The length of
embedswas invalid.
- Returns:
If the interaction has not been responded to, returns a
PartialInteractionMessagesupporting only theedit()anddelete()operations. To fetch theInteractionMessageyou may usefetch()orInteraction.original_message(). If the interaction has been responded to, returns theWebhookMessage.- Return type:
- await edit(*args, **kwargs)¶
This function is a coroutine.
This is a shorthand function for helping in editing messages in response to a component or modal submit interaction. If the interaction has not been responded to,
InteractionResponse.edit_message()is used. If the responseis_done()then the message is edited via theInteraction.messageusingMessage.edit()instead.- Raises:
HTTPException – Editing the message failed.
InvalidArgument – You specified both
embedandembedsorfileandfiles.TypeError – An object not of type
Filewas passed tofileorfiles.HTTPException – Editing the message failed.
InvalidArgument –
Interaction.messagewasNone, this may occur in aThreador when the interaction is not a component or modal submit interaction.
- Returns:
The edited message. If the interaction has not yet been responded to,
InteractionResponse.edit_message()is used which returns aMessageorNonecorresponding toInteraction.message. Otherwise, theMessageis returned viaMessage.edit().- Return type:
Optional[
Message]
InteractionResponse¶
- asyncdefer
- asyncedit_message
- defis_done
- asyncpong
- asyncsend_autocomplete
- asyncsend_message
- asyncsend_modal
- class nextcord.InteractionResponse¶
Represents a Discord interaction response.
This type can be accessed through
Interaction.response.Added in version 2.0.
- is_done()¶
bool: Indicates whether an interaction response has been done before.An interaction can only be responded to once.
- await defer(*, ephemeral=False, with_message=False)¶
This function is a coroutine.
Defers the interaction response.
This is typically used when the interaction is acknowledged and a secondary action will be done later.
- Parameters:
ephemeral (
bool) – Indicates whether the deferred message will eventually be ephemeral. This only applies for interactions of typeInteractionType.application_commandor whenwith_messageis Truewith_message (
bool) –Indicates whether the response will be a message with thinking state (bot is thinking…). This is always True for interactions of type
InteractionType.application_command. For interactions of typeInteractionType.componentthis defaults to False.Added in version 2.0.
- Raises:
HTTPException – Deferring the interaction failed.
InteractionResponded – This interaction has already been responded to before.
- await pong()¶
This function is a coroutine.
Pongs the ping interaction.
This should rarely be used.
- Raises:
HTTPException – Ponging the interaction failed.
InteractionResponded – This interaction has already been responded to before.
- await send_autocomplete(choices)¶
This function is a coroutine.
Responds to this interaction by sending an autocomplete payload.
- Parameters:
choices (Union[
dict,list]) – The choices to send the user. If adictis given, each key-value pair is turned into a name-value pair. Name is what Discord shows the user, value is what Discord sends to the bot. If something not adict, such as alist, is given, each value is turned into a duplicate name-value pair, where the display name and the value Discord sends back are the same.- Raises:
HTTPException – Sending the message failed.
InteractionResponded – This interaction has already been responded to before.
- await send_message(content=None, *, embed=..., embeds=..., file=..., files=..., view=..., tts=False, delete_after=None, allowed_mentions=..., flags=None, ephemeral=None, suppress_embeds=None, components=None)¶
This function is a coroutine.
Responds to this interaction by sending a message.
Changed in version 2.4:
ephemeralcan now acceptNoneto indicate thatflagsshould be used.- Parameters:
content (Optional[
str]) – The content of the message to send.embeds (List[
Embed]) – A list of embeds to send with the content. Maximum of 10. This cannot be mixed with theembedparameter.embed (
Embed) – The rich embed for the content to send. This cannot be mixed withembedsparameter.file (
File) – The file to upload.files (List[
File]) – A list of files to upload. Maximum of 10. This cannot be mixed with thefileparameter.tts (
bool) – Indicates if the message should be sent using text-to-speech.view (
nextcord.ui.View) – The view to send with the message.ephemeral (
bool) – Indicates if the message should only be visible to the user who started the interaction. If a view is sent with an ephemeral message and it has no timeout set then the timeout is set to 15 minutes.delete_after (Optional[
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. Seeabc.Messageable.send()for more information.flags (Optional[
MessageFlags]) –The message flags being set for this message. Currently only
suppress_embedsis able to be set.Added in version 2.4.
suppress_embeds (Optional[
bool]) –Whether to suppress embeds on this message.
Added in version 2.4.
- Raises:
HTTPException – Sending the message failed.
NotFound – The interaction has expired.
InteractionResponse.defer()andInteraction.followupshould be used if the interaction will take a while to respond.InvalidArgument – You specified both
embedandembedsorfileandfiles.TypeError – An object not of type
Filewas passed tofileorfiles.ValueError – The length of
embedswas invalid.InteractionResponded – This interaction has already been responded to before.
- Returns:
An object supporting only the
edit()anddelete()operations. To fetch theInteractionMessageyou may usePartialInteractionMessage.fetch()orInteraction.original_message().- Return type:
- await send_modal(modal)¶
This function is a coroutine.
Respond to this interaction by sending a modal.
- Parameters:
modal (
nextcord.ui.Modal) – The modal to be sent in response to the interaction and which will be displayed on the user’s screen.- Raises:
HTTPException – Sending the modal failed.
InteractionResponded – This interaction has already been responded to before.
- await edit_message(*, content=..., embed=..., embeds=..., file=..., files=..., attachments=..., view=..., delete_after=None, components=None)¶
This function is a coroutine.
Responds to this interaction by editing the message that the component or modal submit interaction originated from.
- Parameters:
content (Optional[
str]) – The new content to replace the message with.Noneremoves the content.embeds (List[
Embed]) – A list of embeds to edit the message with.embed (Optional[
Embed]) – The embed to edit the message with.Nonesuppresses the embeds. This should not be mixed with theembedsparameter.file (
File) – The file to upload.files (List[
File]) – A list of files to upload. Maximum of 10. This cannot be mixed with thefileparameter.attachments (List[
Attachment]) – A list of attachments to keep in the message. To keep all existing attachments, passinteraction.message.attachments.view (Optional[
View]) – The updated view to update this message with. IfNoneis passed then the view is removed.delete_after (Optional[
float]) – If provided, the number of seconds to wait in the background before deleting the message we just sent. If the deletion fails, then it is silently ignored.
- Raises:
HTTPException – Editing the message failed.
InvalidArgument – You specified both
embedandembedsorfileandfiles.TypeError – An object not of type
Filewas passed tofileorfiles.InteractionResponded – This interaction has already been responded to before.
- Returns:
The message that was edited, or None if the
Interaction.messageis not found (this may happen if the interaction occurred in aThread).- Return type:
Optional[
Message]
InteractionMessage¶
- asyncadd_reaction
- asyncclear_reaction
- asyncclear_reactions
- asynccreate_thread
- asyncdelete
- asyncedit
- asyncforward
- defis_system
- asyncpin
- asyncpublish
- asyncremove_reaction
- asyncreply
- defto_reference
- asyncunpin
- class nextcord.InteractionMessage¶
Represents the original interaction response message.
To retrieve this object see
PartialInteractionMessage.fetch()orInteraction.original_message().This inherits from
nextcord.Messagewith changes toedit()anddelete()to work with the interaction response.Added in version 2.0.
- 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_historypermission to use this. If nobody else has reacted to the message using this emoji, theadd_reactionspermission 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.
- 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:
- 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_messagespermission to use this.Added 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_messagespermission 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=...)¶
This function is a coroutine.
Creates a public thread from this message.
You must have
create_public_threadsin order to create a public thread from a message.The channel this message belongs in must be a
TextChannel.Added in version 2.0.
- Parameters:
- Raises:
Forbidden – You do not have permissions to create a thread.
HTTPException – Creating the thread failed.
InvalidArgument – This message does not have guild info attached.
- Returns:
The created thread.
- Return type:
- property created_at¶
The message’s creation time in UTC.
- Type:
- await 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. The waiting is done in the background and deletion failures are 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=..., embeds=..., embed=..., file=..., files=..., attachments=..., view=..., allowed_mentions=None, delete_after=None, components=None)¶
This function is a coroutine.
Edits the message.
- Parameters:
content (Optional[
str]) – The content to edit the message with orNoneto clear it.embeds (List[
Embed]) – A list of embeds to edit the message with.embed (Optional[
Embed]) – The embed to edit the message with.Nonesuppresses the embeds. This should not be mixed with theembedsparameter.file (
File) – The file to upload. This cannot be mixed withfilesparameter.files (List[
File]) – A list of files to send with the content. This cannot be mixed with thefileparameter.attachments (List[
Attachment]) – A list of attachments to keep in the message. To keep existing attachments, you must fetch the message withoriginal_message()and passmessage.attachmentsto this parameter.allowed_mentions (
AllowedMentions) – Controls the mentions being processed in this message. Seeabc.Messageable.send()for more information.view (Optional[
View]) – The updated view to update this message with. IfNoneis passed then the view is removed.delete_after (Optional[
float]) – If provided, the number of seconds to wait in the background before deleting the message we just edited. If the deletion fails, then it is silently ignored.
- Raises:
HTTPException – Editing the message failed.
Forbidden – Edited a message that is not yours.
InvalidArgument – You specified both
embedandembedsorfileandfiles.ValueError – The length of
embedswas invalid.
- Returns:
The newly edited message.
- Return type:
- property edited_at¶
An aware UTC datetime object containing the edited time of the message.
- Type:
Optional[
datetime.datetime]
- await forward(channel)¶
Forward this message to a channel.
Note
It is not possible to forward messages through interactions. It is only possible to forward a message to a channel as a message.
- Parameters:
channel (
Messageable) – The channel to forward this message.- Raises:
HTTPException – Forwarding/sending the message failed.
Forbidden – You do not have the proper permissions to send the message.
.. versionadded: – 3.0:
- is_system()¶
bool: Whether the message is a system message.A system message is a message that is constructed entirely by the Discord API in response to something.
Added in version 1.3.
- await pin(*, reason=None)¶
This function is a coroutine.
Pins the message.
You must have the
manage_messagespermission 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.
Added 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.
You must have the
send_messagespermission to do this.If the message is not your own then the
manage_messagespermission is also needed.- Raises:
Forbidden – You do not have the proper permissions to publish this message.
HTTPException – Publishing the message failed.
- 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_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_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]
- 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.
memberparameter is not you) then themanage_messagespermission is needed.The
memberparameter must represent a member and meet theabc.Snowflakeabc.- 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, **kwargs)¶
This function is a coroutine.
A shortcut method to
abc.Messageable.send()to reply to theMessage.Added in version 1.6.
- Raises:
HTTPException – Sending the message failed.
Forbidden – You do not have the proper permissions to send the message.
InvalidArgument – The
fileslist is not of the appropriate size or you specified bothfileandfiles.
- Returns:
The message that was sent.
- Return type:
- system_content¶
A property that returns the content that is rendered regardless of the
Message.type.In the case of
MessageType.defaultandMessageType.reply, this just returns the regularMessage.content. Otherwise this returns an English message denoting the contents of the system message.- Type:
- property thread¶
The thread started from this message. None if no thread was started.
- Type:
Optional[
Thread]
- to_reference(*, fail_if_not_exists=True)¶
Creates a
MessageReferencefrom the current message.Added in version 1.6.
- Parameters:
fail_if_not_exists (
bool) –Whether replying using the message reference should raise
HTTPExceptionif the message no longer exists or Discord could not fetch the message.Added 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_messagespermission 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.
Added 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.
PartialInteractionMessage¶
- class nextcord.PartialInteractionMessage¶
Represents the original interaction response message when only the application state and interaction token are available.
This allows you to edit or delete the message associated with the interaction response. This object is returned when responding to an interaction with
InteractionResponse.send_message().This does not support most attributes and methods of
nextcord.Message. Thefetch()method can be used to retrieve the fullInteractionMessageobject.- x == y
Checks if two partial interaction messages are equal.
- x != y
Checks if two partial interaction messages are not equal.
- hash(x)
Returns the partial interaction message’s hash.
Added in version 2.0.
Changed in version 2.1:
PartialInteractionMessageis now hashable byInteraction.id.Note
The hash of a
PartialInteractionMessageis the same as the hash of theInteractionthat it is associated with but not that of the fullInteractionMessage.- await fetch()¶
This function is a coroutine.
Fetches the original interaction response message associated with the interaction.
Repeated calls to this will return a cached value.
- Raises:
HTTPException – Fetching the original response message failed.
ClientException – The channel for the message could not be resolved.
- Returns:
The original interaction response message.
- Return type:
- property author¶
The client that responded to the interaction.
If the interaction was in a guild, this is a
Memberrepresenting the client. Otherwise, this is aClientUser.- Type:
Optional[Union[
Member,ClientUser]]
- property channel¶
The channel the interaction was sent from.
Note that due to a Discord limitation, DM channels are not resolved since there is no data to complete them. These are
PartialMessageableinstead.- Type:
Optional[Union[
abc.GuildChannel,PartialMessageable,Thread]]
- await 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. The waiting is done in the background and deletion failures are 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=..., embeds=..., embed=..., file=..., files=..., attachments=..., view=..., allowed_mentions=None, delete_after=None, components=None)¶
This function is a coroutine.
Edits the message.
- Parameters:
content (Optional[
str]) – The content to edit the message with orNoneto clear it.embeds (List[
Embed]) – A list of embeds to edit the message with.embed (Optional[
Embed]) – The embed to edit the message with.Nonesuppresses the embeds. This should not be mixed with theembedsparameter.file (
File) – The file to upload. This cannot be mixed withfilesparameter.files (List[
File]) – A list of files to send with the content. This cannot be mixed with thefileparameter.attachments (List[
Attachment]) – A list of attachments to keep in the message. To keep existing attachments, you must fetch the message withoriginal_message()and passmessage.attachmentsto this parameter.allowed_mentions (
AllowedMentions) – Controls the mentions being processed in this message. Seeabc.Messageable.send()for more information.view (Optional[
View]) – The updated view to update this message with. IfNoneis passed then the view is removed.delete_after (Optional[
float]) – If provided, the number of seconds to wait in the background before deleting the message we just edited. If the deletion fails, then it is silently ignored.
- Raises:
HTTPException – Editing the message failed.
Forbidden – Edited a message that is not yours.
InvalidArgument – You specified both
embedandembedsorfileandfiles.ValueError – The length of
embedswas invalid.
- Returns:
The newly edited message.
- Return type:
MessageInteraction¶
- class nextcord.MessageInteraction¶
Represents a message’s interaction data.
A message’s interaction data is a property of a message when the message is a response to an interaction from any bot.
Added in version 2.1.
- x == y
Checks if two message interactions are equal.
- x != y
Checks if two interaction messages are not equal.
- hash(x)
Returns the message interaction’s hash.
- type¶
The interaction type.
- Type:
- .. warning::
This class is deprecated, use
Message.interaction_metadatainstead.
- .. deprecated:: 3.0
- property created_at¶
The interaction’s creation time in UTC.
- Type:
MessageInteractionMetadata¶
- class nextcord.MessageInteractionMetadata¶
Represents a message’s interaction metadata.
A message’s interaction metadata is a property of a message when the message is a response to an interaction from any bot.
Added in version 3.0.
- x == y
Checks if two message interactions are equal.
- x != y
Checks if two interaction messages are not equal.
- hash(x)
Returns the message interaction’s hash.
- type¶
The interaction type.
- Type:
- user¶
The
Userwho invoked the interaction orMemberif the interaction occurred in a guild and that member is cached.
- authorizing_integration_owners¶
Mapping of installation contexts that the interaction was authorized for to related user or guild IDs. You can find out about this field in the official Discord documentation.
Added in version 3.0.
- Type:
Dict[
IntegrationType,str]
- original_response_message_id¶
The ID of the original response message, present only on follow-up messages.
- Type:
Optional[
int]
- interacted_message_id¶
The ID of the message that contained the interactive component, present only on messages created from component interactions.
- Type:
Optional[
int]
- triggering_interaction_metadata¶
Metadata for the interaction that was used to open the modal, present only on modal submit interactions.
- Type:
Optional[
MessageInteractionMetadata]
- property created_at¶
The interaction’s creation time in UTC.
- Type:
Member¶
- accent_color
- accent_colour
- activities
- activity
- avatar
- avatar_decoration
- banner
- bot
- color
- colour
- communication_disabled_until
- created_at
- default_avatar
- desktop_status
- discriminator
- display_avatar
- display_banner
- display_name
- dm_channel
- flags
- global_name
- guild
- guild_avatar
- guild_banner
- guild_permissions
- id
- joined_at
- mention
- mobile_status
- mutual_guilds
- name
- nick
- pending
- premium_since
- public_flags
- raw_status
- roles
- status
- system
- top_role
- voice
- web_status
- asyncadd_roles
- asyncban
- asynccreate_dm
- asyncdisconnect
- asyncedit
- asyncfetch_message
- asyncforward
- defget_role
- defhistory
- defis_on_mobile
- asynckick
- defmentioned_in
- asyncmove_to
- asyncremove_roles
- asyncrequest_to_speak
- asyncsend
- asynctimeout
- asynctrigger_typing
- deftyping
- asyncunban
- class nextcord.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
Userinstances too.
- x != y
Checks if two members are not equal. Note that this works with
Userinstances too.
- hash(x)
Returns the member’s hash.
- str(x)
Returns the member’s name with the discriminator.
- joined_at¶
An aware datetime object that specifies the date and time in UTC that the member joined the guild. If the member left and rejoined the guild, this will be the latest date. In certain cases, this can be
None.- Type:
Optional[
datetime.datetime]
- activities¶
The activities that the user is currently doing.
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]]
An aware datetime object that specifies the date and time in UTC when the member used their “Nitro boost” on the guild, if available. This could be
None.- Type:
Optional[
datetime.datetime]
- async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)¶
This function returns an async iterator.
Returns an async iterator that enables receiving the destination’s message history.
You must have
read_message_historypermissions to use this.Examples
Usage
counter = 0 async for message in channel.history(limit=200): if message.author == client.user: counter += 1
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 datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.after (Optional[Union[
Snowflake,datetime.datetime]]) – Retrieve messages after this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.around (Optional[Union[
Snowflake,datetime.datetime]]) – Retrieve messages around this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time. When using this argument, the maximum limit is 101. Note that if the limit is an even number then this will return at most limit + 1 messages.oldest_first (Optional[
bool]) – If set toTrue, return messages in oldest->newest order. Defaults toTrueifafteris 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
withandasync withwork with this.Example Usage:
async with channel.typing(): # simulate something heavy await asyncio.sleep(10) await channel.send('done!')
- property global_name¶
Equivalent to
User.global_name
- property discriminator¶
Equivalent to
User.discriminator
- property system¶
Equivalent to
User.system
- property created_at¶
Equivalent to
User.created_at
- property default_avatar¶
Equivalent to
User.default_avatar
- property avatar¶
Equivalent to
User.avatar
- property dm_channel¶
Equivalent to
User.dm_channel
- await create_dm()¶
This function is a coroutine.
Creates a
DMChannelwith this user.This should be rarely called, as this is done transparently for most people.
- Returns:
The channel that was created.
- Return type:
- property mutual_guilds¶
Equivalent to
User.mutual_guilds
- property public_flags¶
Equivalent to
User.public_flags
- property banner¶
Equivalent to
User.banner
- property accent_color¶
Equivalent to
User.accent_color
- property accent_colour¶
Equivalent to
User.accent_colour
- property avatar_decoration¶
Equivalent to
User.avatar_decoration
- property status¶
The member’s overall status. If the value is unknown, then it will be a
strinstead.
- 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 roles¶
A
listofRolethat 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 mention¶
Returns a string that allows you to mention the member.
Changed in version 2.2: The nickname mention syntax is no longer returned as it is deprecated by Discord.
- Type:
- property display_name¶
Returns the user’s display name.
This will return the name using the following hierachy:
Guild specific nickname
Global Name (also known as ‘Display Name’ in the Discord UI)
Unique username
- Type:
- property display_avatar¶
Returns the member’s display avatar.
For regular members this is just their avatar, but if they have a guild specific avatar then that is returned instead.
Added in version 2.0.
- Type:
- property guild_avatar¶
Returns an
Assetfor the guild avatar the member has. If unavailable,Noneis returned.Added in version 2.0.
- Type:
Optional[
Asset]
- property guild_banner¶
Returns an
Assetfor the guild member’s banner. If unavailable,Noneis returned.Added in version 3.0.
- Type:
Optional[
Asset]
- property display_banner¶
Returns the member’s display banner. If unavailable,
Noneis returnedFor regular members this is just their banner, if any, but if they have a guild specific banner then that is returned instead.
Added in version 3.0.
- Type:
Optional[
Asset]
- property activity¶
Returns the primary activity the user is currently doing. Could be
Noneif no activity is being done.Note
Due to a Discord API limitation, this may be
Noneif 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:
Optional[Union[
BaseActivity,Spotify]]
- property flags¶
Returns the member’s flags.
Added in version 2.6.
- Type:
- mentioned_in(message)¶
Checks if the member is mentioned in the specified message.
- 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
abc.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¶
A datetime object that represents the time in which the member will be able to interact again.
Note
This is
Noneif the user has no timeout.Added in version 2.0.
- Type:
Optional[
datetime.datetime]
- await ban(*, delete_message_seconds=None, reason=None)¶
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 timeout(timeout, *, reason=None)¶
This function is a coroutine.
Times out this member.
Note
This is a more direct method of timing out a member. You can also time out members using
Member.edit().Added in version 2.0.
- await edit(*, nick=..., mute=..., deafen=..., suppress=..., roles=..., voice_channel=..., reason=None, timeout=..., flags=..., bypass_verification=...)¶
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
timeout
bypass_verification
All parameters are optional.
Changed in version 1.1: Can now pass
Nonetovoice_channelto kick a member from voice.Changed in version 2.0: The newly member is now optionally returned, if applicable.
- Parameters:
nick (Optional[
str]) – The member’s new nickname. UseNoneto 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.
Added in version 1.7.
roles (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. PassNoneto kick them from voice.reason (Optional[
str]) – The reason for editing this member. Shows up on the audit log.timeout (Optional[Union[
datetime,timedelta]) –The time until the member should not be timed out. Set this to None to disable their timeout.
Added in version 2.0.
flags (
MemberFlags) –The flags to set for this member. Currently only
bypasses_verificationis able to be set.Added in version 2.6.
bypass_verification (
bool) –Indicates if the member should be allowed to bypass the guild verification requirements.
Added in version 2.6.
- Raises:
Forbidden – You do not have the proper permissions to the action requested.
HTTPException – The operation failed.
- Returns:
The newly updated member, if applicable. This is only returned when certain fields are updated.
- Return type:
Optional[
Member]
- 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
editprovidingsuppressasFalse.Added 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_memberspermission to use this.This raises the same exceptions as
edit().Changed in version 1.1: Can now pass
Noneto kick a member from voice.- Parameters:
channel (Optional[
VoiceChannel]) – The new voice channel to move the member to. PassNoneto kick them from voice.reason (Optional[
str]) – The reason for doing this action. Shows up on the audit log.
- await disconnect(*, reason=None)¶
This function is a coroutine.
Disconnects a member from the voice channel they are connected to.
You must have the
move_memberspermission to use this.This raises the same exceptions as
edit().- Parameters:
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
Roles.You must have the
manage_rolespermission to use this, and the addedRoles must appear lower in the list of roles than the highest role of the member.- Parameters:
*roles (
abc.Snowflake) – An argument list ofabc.Snowflakerepresenting aRoleto 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.
- await remove_roles(*roles, reason=None, atomic=True)¶
This function is a coroutine.
Removes
Roles from this member.You must have the
manage_rolespermission to use this, and the removedRoles must appear lower in the list of roles than the highest role of the member.- Parameters:
*roles (
abc.Snowflake) – An argument list ofabc.Snowflakerepresenting aRoleto 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 fetch_message(id, /)¶
This function is a coroutine.
Retrieves a single
Messagefrom the destination.- 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 forward(message)¶
Forward a message to this channel.
- Parameters:
message (
Message) – The message to forward.note:: (..) – It is not possible to forward messages through interactions. It is only possible to forward a message to a channel as a message.
- Raises:
HTTPException – Forwarding/sending the message failed.
Forbidden – You do not have the proper permissions to send the message.
.. versionadded: – 3.0:
- get_role(role_id, /)¶
Returns a role with the given ID from roles which the member has.
Added in version 2.0.
- await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, mention_author=None, view=None, flags=None, suppress_embeds=None)¶
This function is a coroutine.
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through
str(content). If the content is set toNone(the default), then theembedorembedsparameter must be provided.To upload a single file, the
fileparameter should be used with a singleFileobject. To upload multiple files, thefilesparameter should be used with alistofFileobjects. Specifying both parameters will lead to an exception.To upload a single embed, the
embedparameter should be used with a singleEmbedobject. To upload multiple embeds, theembedsparameter should be used with alistofEmbedobjects. Specifying both parameters will lead to an exception.- Parameters:
content (Optional[
str]) – The content of the message to send.tts (
bool) – Indicates if the message should be sent using text-to-speech.embed (
Embed) – The rich embed for the content.file (
File) – The file to upload.files (List[
File]) – A list of files to upload. Must be a maximum of 10.nonce (Union[
int,str]) – 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_mentionsare used instead.Added in version 1.4.
reference (Union[
Message,MessageReference,PartialMessage]) –A reference to the
Messageto 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_userattribute ofallowed_mentionsor by settingmention_author.Added in version 1.6.
mention_author (Optional[
bool]) –If set, overrides the
replied_userattribute ofallowed_mentions.Added in version 1.6.
view (
nextcord.ui.View) – A Discord UI View to add to the message.embeds (List[
Embed]) –A list of embeds to upload. Must be a maximum of 10.
Added in version 2.0.
stickers (Sequence[Union[
GuildSticker,StickerItem]]) –A list of stickers to upload. Must be a maximum of 3.
Added in version 2.0.
flags (Optional[
MessageFlags]) –The message flags being set for this message. Currently only
suppress_embedsis able to be set.Added in version 2.4.
suppress_embeds (Optional[
bool]) –Whether to suppress embeds on this message.
Added in version 2.4.
- Raises:
HTTPException – Sending the message failed.
Forbidden – You do not have the proper permissions to send the message.
InvalidArgument – The
fileslist is not of the appropriate size, you specified bothfileandfiles, or you specified bothembedandembeds, or thereferenceobject is not aMessage,MessageReferenceorPartialMessage
- Returns:
The message that was sent.
- Return type:
Spotify¶
- class nextcord.Spotify¶
Represents a Spotify listening activity from Discord. This is a special case of
Activitythat 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.
Added 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 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:
- property start¶
When the user started playing this song in UTC.
- Type:
- property end¶
When the user will stop playing this song in UTC.
- Type:
- property duration¶
The duration of the song being played.
- Type:
VoiceState¶
- class nextcord.VoiceState¶
Represents a Discord user’s voice state.
- self_stream¶
Indicates if the user is currently streaming via ‘Go Live’ feature.
Added in version 1.3.
- Type:
- suppress¶
Indicates if the user is suppressed from speaking.
Only applies to stage channels.
Added in version 1.7.
- Type:
- requested_to_speak_at¶
An aware datetime object that specifies the date and time in UTC that the member requested to speak. It will be
Noneif they are not requesting to speak anymore or have been accepted to speak.Only applicable to stage channels.
Added in version 1.7.
- Type:
Optional[
datetime.datetime]
- channel¶
The voice channel that the user is currently connected to.
Noneif the user is not currently in a voice channel.- Type:
Optional[Union[
VoiceChannel,StageChannel]]
Emoji¶
- asyncdelete
- asyncedit
- defis_application_emoji
- defis_guild_emoji
- defis_usable
- asyncread
- asyncsave
- asyncto_file
- class nextcord.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.
- require_colons¶
If colons are required to use this emoji in the client (:PJSalt: vs PJSalt).
- Type:
- guild_id¶
The guild ID the emoji belongs to, if applicable. This is
`Nonefor application emojis.Changed in version 3.1: This attribute is now optional to account for application emojis.
- Type:
Optional[
int]
- user¶
The user that created the emoji. This can only be retrieved using
Guild.fetch_emoji()and having themanage_emojispermission.- Type:
Optional[
User]
- application_id¶
The ID of the application that this emoji belongs to, if applicable. This is
`Nonefor guild emojis.Added in version 3.1.
- Type:
Optional[
int]
- property created_at¶
Returns the emoji’s creation time in UTC.
- Type:
- property roles¶
A
listof roles that is allowed to use this emoji.If roles is empty, the emoji is unrestricted.
- Type:
List[
Role]
- is_usable()¶
bool: Whether the bot can use this emoji.Added in version 1.3.
Changed in version 3.1: This now accounts for application emojis as well by comparing the application ID.
- await delete(*, reason=None)¶
This function is a coroutine.
Deletes the custom emoji.
You must have
manage_emojispermission to do this.- Parameters:
reason (Optional[
str]) –The reason for deleting this emoji. Shows up on the audit log.
This is only available when deleting an emoji in a guild.
- Raises:
Forbidden – You are not allowed to delete emojis.
HTTPException – An error occurred deleting the emoji.
ValueError – The emoji does not belong to a guild or application.
- await edit(*, name=..., roles=..., reason=None)¶
This function is a coroutine.
Edits the custom emoji.
You must have
manage_emojispermission to do this.Changed in version 2.0: The newly updated emoji is returned.
- Parameters:
name (
str) – The new emoji name.roles (Optional[List[
Snowflake]]) –A list of roles that can use this emoji. An empty list can be passed to make it available to everyone.
This is only available when editing an emoji in a guild.
reason (Optional[
str]) –The reason for editing this emoji. Shows up on the audit log.
This is only available when editing an emoji in a guild.
- Raises:
Forbidden – You are not allowed to edit emojis.
HTTPException – An error occurred editing the emoji.
ValueError – The emoji does not belong to a guild or application
- Returns:
The newly updated emoji.
- Return type:
- await read()¶
This function is a coroutine.
Retrieves the content of this asset as a
bytesobject.- Raises:
DiscordException – There was no 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[
io.BufferedIOBase,os.PathLike]) – The file-like object to save this asset to or the filename to use. If a filename is passed then a file is created with that filename and used instead.seek_begin (
bool) – Whether to seek to the beginning of the file after saving is successfully done.
- Raises:
DiscordException – There was no internal connection state.
HTTPException – Downloading the asset failed.
NotFound – The asset was deleted.
- Returns:
The number of bytes written.
- Return type:
- await to_file(*, filename=..., description=None, spoiler=False, force_close=True)¶
This function is a coroutine.
Converts the asset into a
Filesuitable for sending viaabc.Messageable.send().Added in version 2.0.
- Parameters:
filename (Optional[
str]) – The filename of the file. If not provided, then the filename from the asset’s URL is used.description (Optional[
str]) – The description for the file.spoiler (
bool) – Whether the file is a spoiler.force_close (
bool) –Whether to forcibly close the bytes used to create the file when
.close()is called. This will also make the file bytes unusable by flushing it from memory after it is sent or used once. Keep this enabled if you don’t wish to reuse the same bytes.Added in version 2.2.
- Raises:
DiscordException – The asset does not have an associated state.
InvalidArgument – The asset is a unicode emoji.
TypeError – The asset is a sticker with lottie type.
HTTPException – Downloading the asset failed.
NotFound – The asset was deleted.
- Returns:
The asset as a file suitable for sending.
- Return type:
PartialEmoji¶
- clsPartialEmoji.from_str
- defis_custom_emoji
- defis_unicode_emoji
- asyncread
- asyncsave
- asyncto_file
- class nextcord.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
Noneif the emoji got deleted (e.g. removing a reaction with a deleted emoji).- Type:
Optional[
str]
- classmethod from_str(value)¶
Converts a Discord string representation of an emoji to a
PartialEmoji.The formats accepted are:
a:name:id<a:name:id>name:id<:name:id>
If the format does not match then it is assumed to be a unicode emoji.
Added in version 2.0.
- Parameters:
value (
str) – The string representation of an emoji.- Returns:
The partial emoji from this string.
- Return type:
- property created_at¶
Returns the emoji’s creation time in UTC, or None if Unicode emoji.
Added in version 1.6.
- Type:
Optional[
datetime.datetime]
- property url¶
Returns the URL of the emoji, if it is custom.
If this isn’t a custom emoji then an empty string is returned
- Type:
- await read()¶
This function is a coroutine.
Retrieves the content of this asset as a
bytesobject.- Raises:
DiscordException – There was no 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[
io.BufferedIOBase,os.PathLike]) – The file-like object to save this asset to or the filename to use. If a filename is passed then a file is created with that filename and used instead.seek_begin (
bool) – Whether to seek to the beginning of the file after saving is successfully done.
- Raises:
DiscordException – There was no internal connection state.
HTTPException – Downloading the asset failed.
NotFound – The asset was deleted.
- Returns:
The number of bytes written.
- Return type:
- await to_file(*, filename=..., description=None, spoiler=False, force_close=True)¶
This function is a coroutine.
Converts the asset into a
Filesuitable for sending viaabc.Messageable.send().Added in version 2.0.
- Parameters:
filename (Optional[
str]) – The filename of the file. If not provided, then the filename from the asset’s URL is used.description (Optional[
str]) – The description for the file.spoiler (
bool) – Whether the file is a spoiler.force_close (
bool) –Whether to forcibly close the bytes used to create the file when
.close()is called. This will also make the file bytes unusable by flushing it from memory after it is sent or used once. Keep this enabled if you don’t wish to reuse the same bytes.Added in version 2.2.
- Raises:
DiscordException – The asset does not have an associated state.
InvalidArgument – The asset is a unicode emoji.
TypeError – The asset is a sticker with lottie type.
HTTPException – Downloading the asset failed.
NotFound – The asset was deleted.
- Returns:
The asset as a file suitable for sending.
- Return type:
Role¶
- asyncdelete
- asyncedit
- defis_assignable
- defis_bot_managed
- defis_default
- defis_in_prompt
- defis_integration
- defis_premium_subscriber
- class nextcord.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.
- position¶
The position of the role. This number is usually positive. The bottom role has a position of 0.
Warning
Multiple roles can have the same position number. As a consequence of this, comparing via role position is prone to subtle bugs if checking for role hierarchy. The recommended and correct way to compare for roles in the hierarchy is using the comparison operators on the role objects themselves.
- Type:
- managed¶
Indicates if the role is managed by the guild through some form of integrations such as Twitch.
- Type:
bool: Whether the role is the premium subscriber, AKA “boost”, role for the guild.Added in version 1.6.
- is_assignable()¶
bool: Whether the role is able to be assigned or removed by the bot.Added in version 2.0.
- is_in_prompt()¶
bool: Whether the role can be selected in an onboarding prompt.Added in version 2.6.
- property permissions¶
Returns the role’s permissions.
- Type:
- property colours¶
Returns the role colours. An alias exists under
colors.Added in version 3.2.
- Type:
- property colors¶
Returns the role colors. An alias exists under
colours.Added in version 3.2.
- Type:
- property created_at¶
Returns the role’s creation time in UTC.
- Type:
- property icon¶
Returns the role’s icon asset or its unicode emoji, if available.
- await edit(*, name=..., permissions=..., colour=..., color=..., colours=..., colors=..., hoist=..., mentionable=..., position=..., reason=..., icon=...)¶
This function is a coroutine.
Edits the role.
You must have the
manage_rolespermission to use this.All fields are optional.
Changed in version 1.4: Can now pass
inttocolourkeyword-only parameter.Changed in version 2.0: Edits are no longer in-place, the newly edited role is returned instead.
Changed in version 2.1: The
iconparameter now acceptsAttachment, andAsset.Changed in version 3.2: Added the
coloursandcolorsparameters.- 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)colours (
RoleColours) – The new colours to change to. (aliased to colors 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.icon (Optional[Union[
str,bytes,File,Asset,Attachment]]) – The role’s icon imagereason (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, the default role was asked to be moved, or multiple colour parameters were passed.
- Returns:
The newly edited role.
- Return type:
- await delete(*, reason=None)¶
This function is a coroutine.
Deletes the role.
You must have the
manage_rolespermission 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.
RoleColours¶
- class nextcord.RoleColours¶
Represents the colours of a role.
There is an alias for this called
RoleColors.secondaryandtertiarycan only be set if the guild has theENHANCED_ROLE_COLORSfeature enabled.Added in version 3.2.
- secondary¶
The secondary colour of the role, if available.
This creates a gradient between the primary and secondary colours.
- Type:
Optional[
Colour]
- tertiary¶
The tertiary colour of the role, if available.
This creates a holographic effect with the three colours. Currently, there is only one holographic style, which can be accessed with
holographic().- Type:
Optional[
Colour]
- classmethod holographic()¶
Returns a
RoleColourswith a ‘holographic style’.This is the only known holographic style, with preset colour values.
PartialMessageable¶
- asyncfetch_message
- asyncforward
- defget_partial_message
- defhistory
- asyncsend
- asynctrigger_typing
- deftyping
- class nextcord.PartialMessageable¶
Represents a partial messageable to aid with working messageable channels when only a channel ID are present.
The only way to construct this class is through
Client.get_partial_messageable().Note that this class is trimmed down and has no rich attributes.
Added in version 2.0.
- x == y
Checks if two partial messageables are equal.
- x != y
Checks if two partial messageables are not equal.
- hash(x)
Returns the partial messageable’s hash.
- type¶
The channel type associated with this partial messageable, if given.
- Type:
Optional[
ChannelType]
- get_partial_message(message_id, /)¶
Creates a
PartialMessagefrom 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.
- 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
Messagefrom the destination.- 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 forward(message)¶
Forward a message to this channel.
- Parameters:
message (
Message) – The message to forward.note:: (..) – It is not possible to forward messages through interactions. It is only possible to forward a message to a channel as a message.
- Raises:
HTTPException – Forwarding/sending the message failed.
Forbidden – You do not have the proper permissions to send the message.
.. versionadded: – 3.0:
- history(*, limit=100, before=None, after=None, around=None, oldest_first=None)¶
This function returns an async iterator.
Returns an async iterator that enables receiving the destination’s message history.
You must have
read_message_historypermissions to use this.Examples
Usage
counter = 0 async for message in channel.history(limit=200): if message.author == client.user: counter += 1
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 datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.after (Optional[Union[
Snowflake,datetime.datetime]]) – Retrieve messages after this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.around (Optional[Union[
Snowflake,datetime.datetime]]) – Retrieve messages around this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time. When using this argument, the maximum limit is 101. Note that if the limit is an even number then this will return at most limit + 1 messages.oldest_first (Optional[
bool]) – If set toTrue, return messages in oldest->newest order. Defaults toTrueifafteris 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 send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, mention_author=None, view=None, flags=None, suppress_embeds=None)¶
This function is a coroutine.
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through
str(content). If the content is set toNone(the default), then theembedorembedsparameter must be provided.To upload a single file, the
fileparameter should be used with a singleFileobject. To upload multiple files, thefilesparameter should be used with alistofFileobjects. Specifying both parameters will lead to an exception.To upload a single embed, the
embedparameter should be used with a singleEmbedobject. To upload multiple embeds, theembedsparameter should be used with alistofEmbedobjects. Specifying both parameters will lead to an exception.- Parameters:
content (Optional[
str]) – The content of the message to send.tts (
bool) – Indicates if the message should be sent using text-to-speech.embed (
Embed) – The rich embed for the content.file (
File) – The file to upload.files (List[
File]) – A list of files to upload. Must be a maximum of 10.nonce (Union[
int,str]) – 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_mentionsare used instead.Added in version 1.4.
reference (Union[
Message,MessageReference,PartialMessage]) –A reference to the
Messageto 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_userattribute ofallowed_mentionsor by settingmention_author.Added in version 1.6.
mention_author (Optional[
bool]) –If set, overrides the
replied_userattribute ofallowed_mentions.Added in version 1.6.
view (
nextcord.ui.View) – A Discord UI View to add to the message.embeds (List[
Embed]) –A list of embeds to upload. Must be a maximum of 10.
Added in version 2.0.
stickers (Sequence[Union[
GuildSticker,StickerItem]]) –A list of stickers to upload. Must be a maximum of 3.
Added in version 2.0.
flags (Optional[
MessageFlags]) –The message flags being set for this message. Currently only
suppress_embedsis able to be set.Added in version 2.4.
suppress_embeds (Optional[
bool]) –Whether to suppress embeds on this message.
Added in version 2.4.
- Raises:
HTTPException – Sending the message failed.
Forbidden – You do not have the proper permissions to send the message.
InvalidArgument – The
fileslist is not of the appropriate size, you specified bothfileandfiles, or you specified bothembedandembeds, or thereferenceobject is not aMessage,MessageReferenceorPartialMessage
- 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.
- 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
withandasync withwork with this.Example Usage:
async with channel.typing(): # simulate something heavy await asyncio.sleep(10) await channel.send('done!')
TextChannel¶
- defarchived_threads
- asyncclone
- asynccreate_invite
- asynccreate_thread
- asynccreate_webhook
- asyncdelete
- asyncdelete_messages
- asyncedit
- asyncfetch_message
- asyncfollow
- asyncforward
- 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 nextcord.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.
- 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
0denotes that it is disabled. Bots and users withmanage_channelsormanage_messagesbypass slowmode.- Type:
- flags¶
Extra features of the channel.
..versionadded:: 2.1
- Type:
- nsfw¶
If the channel is marked as “not safe for work”.
Note
To check if the channel or the guild of that channel are marked as NSFW, consider
is_nsfw()instead.- Type:
- default_auto_archive_duration¶
The default auto archive duration in minutes for threads created in this channel.
Added in version 2.0.
- Type:
- default_thread_slowmode_delay¶
The default amount of seconds a user has to wait before creating another thread in this channel. This is set on every new thread in this channel.
Added in version 2.4.
- Type:
- async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)¶
This function returns an async iterator.
Returns an async iterator that enables receiving the destination’s message history.
You must have
read_message_historypermissions to use this.Examples
Usage
counter = 0 async for message in channel.history(limit=200): if message.author == client.user: counter += 1
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 datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.after (Optional[Union[
Snowflake,datetime.datetime]]) – Retrieve messages after this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.around (Optional[Union[
Snowflake,datetime.datetime]]) – Retrieve messages around this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time. When using this argument, the maximum limit is 101. Note that if the limit is an even number then this will return at most limit + 1 messages.oldest_first (Optional[
bool]) – If set toTrue, return messages in oldest->newest order. Defaults toTrueifafteris 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
withandasync withwork with this.Example Usage:
async with channel.typing(): # simulate something heavy await asyncio.sleep(10) await channel.send('done!')
- property type¶
The channel’s Discord type.
- Type:
- permissions_for(obj, /)¶
Handles permission resolution for the
MemberorRole.This function takes into consideration the following cases:
Guild owner
Guild roles
Channel overrides
Member overrides
Timed-out members
If a
Roleis passed, then it checks the permissions someone with that role would have, which is essentially:The default role permissions
The permissions of the role used as a parameter
The default role permission overwrites
The permission overwrites of the role used as a parameter
Changed in version 2.3: Only
view_channelandread_message_historycan be returned for timed-out membersChanged in version 2.0: The object passed in can now be a role object.
- property threads¶
Returns all the threads that you can see.
Added in version 2.0.
- Type:
List[
Thread]
- 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_idattribute.- Returns:
The last message in this channel or
Noneif not found.- Return type:
Optional[
Message]
- await edit(*, reason=None, **options)¶
This function is a coroutine.
Edits the channel.
You must have the
manage_channelspermission to use this.Changed in version 1.3: The
overwriteskeyword-only parameter was added.Changed in version 1.4: The
typekeyword-only parameter was added.Changed in version 2.0: Edits are no longer in-place, the newly edited channel is returned instead.
- 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 beNoneto remove the category.slowmode_delay (
int) – Specifies the slowmode rate limit for user in this channel, in seconds. A value of0disables slowmode. The maximum value possible is21600.type (
ChannelType) – Change the type of this text channel. Currently, only conversion betweenChannelType.textandChannelType.newsis supported. This is only available to guilds that containNEWSinGuild.features.reason (Optional[
str]) – The reason for editing this channel. Shows up on the audit log.overwrites (
Mapping) – AMappingof target (either a role or a member) toPermissionOverwriteto apply to the channel.default_auto_archive_duration (
int) – The new default auto archive duration in minutes for threads created in this channel. Must be one of60,1440,4320, or10080.default_thread_slowmode_delay (
int) –The new default rate limit per user for threads created in this channel. This sets a new default but does not change the rate limits of existing threads.
Added in version 2.4.
- 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.
- Returns:
The newly edited text channel. If the edit was only positional then
Noneis returned instead.- Return type:
Optional[
TextChannel]
- 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_channelspermission to do this.Added 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_messagespermission to use this.- 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.
NotFound – If single delete, then the message was already deleted.
HTTPException – Deleting the messages failed.
- await purge(*, limit=100, check=..., 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 acheckis not provided then all messages are deleted without discrimination.You must have the
manage_messagespermission to delete messages even if they are your own. Theread_message_historypermission is also needed to retrieve message history.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(f'Deleted {len(deleted)} message(s)')
- 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 aMessageas its sole parameter.before (Optional[Union[
abc.Snowflake,datetime.datetime]]) – Same asbeforeinhistory().after (Optional[Union[
abc.Snowflake,datetime.datetime]]) – Same asafterinhistory().around (Optional[Union[
abc.Snowflake,datetime.datetime]]) – Same asaroundinhistory().oldest_first (Optional[
bool]) – Same asoldest_firstinhistory().bulk (
bool) – IfTrue, use bulk delete. Setting this toFalseis useful for mass-deleting a bot’s own messages withoutPermissions.manage_messages. WhenTrue, will fall back to single delete 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_webhookspermissions.
- await create_webhook(*, name, avatar=None, reason=None)¶
This function is a coroutine.
Creates a webhook for this channel.
Requires
manage_webhookspermissions.Changed in version 1.1: Added the
reasonkeyword-only parameter.Changed in version 2.1: The
avatarparameter now acceptsFile,Attachment, andAsset.- Parameters:
name (
str) – The webhook’s name.avatar (Optional[Union[
bytes,Asset,Attachment,File]]) – A bytes-like object,File,Attachment, orAssetrepresenting 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.
Added 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.
Added 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
PartialMessagefrom 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.
Added in version 1.6.
- Parameters:
message_id (
int) – The message ID to create a partial message for.- Returns:
The partial message.
- Return type:
- get_thread(thread_id, /)¶
Returns a thread with the given ID.
Added in version 2.0.
- await create_thread(*, name, message=None, auto_archive_duration=..., type=None, invitable=True, reason=None)¶
This function is a coroutine.
Creates a thread in this text channel.
To create a public thread, you must have
create_public_threads. For a private thread,create_private_threadsis needed instead.Added in version 2.0.
- Parameters:
name (
str) – The name of the thread.message (Optional[
abc.Snowflake]) – A snowflake representing the message to create the thread with. IfNoneis passed then a private thread is created. Defaults toNone.auto_archive_duration (
int) – The duration in minutes before a thread is automatically archived for inactivity. If not provided, the channel’s default auto archive duration is used.type (Optional[
ChannelType]) – The type of thread to create. If amessageis passed then this parameter is ignored, as a thread created with a message is always a public thread. By default this creates a private thread if this isNone.invitable (
bool) – Whether non-moderators can add other non-moderators to this thread. Only available for private threads and threads created without amessage.reason (
str) – The reason for creating a new thread. Shows up on the audit log.
- Raises:
Forbidden – You do not have permissions to create a thread.
HTTPException – Starting the thread failed.
- Returns:
The created thread
- Return type:
- archived_threads(*, private=False, joined=False, limit=50, before=None)¶
This function returns an async iterator.
Returns an async iterator that iterates over all archived threads in the guild.
You must have
read_message_historyto use this. If iterating over private threads thenmanage_threadsis also required.Added in version 2.0.
- Parameters:
limit (Optional[
int]) – The number of threads to retrieve. IfNone, retrieves every archived thread in the channel. Note, however, that this would make it a slow operation. This defaults to50.before (Optional[Union[
abc.Snowflake,datetime.datetime]]) – Retrieve archived channels before the given date or ID.private (
bool) – Whether to retrieve private archived threads. This defaults toFalse.joined (
bool) –Whether to retrieve private archived threads that you’ve joined. This defaults to
False.Warning
You cannot set
joinedtoTrueandprivatetoFalse.
- Raises:
Forbidden – You do not have permissions to get archived threads.
HTTPException – The request to get the archived threads failed.
- Yields:
Thread– The archived threads.
- 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
rolesattribute.- Type:
List[
Role]
- await create_invite(*, reason=None, max_age=0, max_uses=0, temporary=False, unique=True, target_type=None, target_user=None, target_application_id=None)¶
This function is a coroutine.
Creates an instant invite from a text or voice channel.
You must have the
create_instant_invitepermission 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 toFalsethen it will return a previously created invite.reason (Optional[
str]) – The reason for creating this invite. Shows up on the audit log.target_type (Optional[
InviteTarget]) –The type of target for the voice channel invite, if any.
Added in version 2.0.
target_user (Optional[
User]) –The user whose stream to display for this invite, required if
target_typeisInviteTarget.stream. The user must be streaming in the channel.Added in version 2.0.
target_application_id: –
Optional[
int]: The id of the embedded application for the invite, required iftarget_typeisInviteTarget.embedded_application.Added in version 2.0.
- 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:
- property created_at¶
Returns the channel’s creation time in UTC.
- Type:
- await delete(*, reason=None)¶
This function is a coroutine.
Deletes the channel.
You must have
manage_channelspermission 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
Messagefrom the destination.- 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 forward(message)¶
Forward a message to this channel.
- Parameters:
message (
Message) – The message to forward.note:: (..) – It is not possible to forward messages through interactions. It is only possible to forward a message to a channel as a message.
- Raises:
HTTPException – Forwarding/sending the message failed.
Forbidden – You do not have the proper permissions to send the message.
.. versionadded: – 3.0:
- await invites()¶
This function is a coroutine.
Returns a list of all active instant invites from this channel.
You must have
manage_channelsto 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 jump_url¶
Returns a URL that allows the client to jump to this channel.
Added in version 2.0.
- Type:
- await move(*, beginning=None, end=None, before=None, after=None, offset=0, category=..., sync_permissions=False, reason=None)¶
This function is a coroutine.
A rich interface to help move a channel relative to other channels.
If exact position movement is required,
editshould be used instead.You must have the
manage_channelspermission to do this.Note
Voice channels will always be sorted below text channels. This is a Discord limitation.
Added in version 1.7.
Changed in version 2.4:
beginning,end,before,afterandreasonnow acceptNone.- Parameters:
beginning (Optional[
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 (Optional[
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 (Optional[
Snowflake]) – The channel that should be before our current channel. This is mutually exclusive withbeginning,end, andafter.after (Optional[
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 of2withbeginning=Truewould 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, andafterparameters.category (Optional[
Snowflake]) – The category to move this channel under. IfNoneis 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 (Optional[
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
Roleor aMemberand the value is the overwrite as aPermissionOverwrite.- Returns:
The channel’s permission overwrites.
- Return type:
Dict[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.Added 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
Messageobjects returned by this method do not contain completeMessage.reactionsdata.- 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, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, mention_author=None, view=None, flags=None, suppress_embeds=None)¶
This function is a coroutine.
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through
str(content). If the content is set toNone(the default), then theembedorembedsparameter must be provided.To upload a single file, the
fileparameter should be used with a singleFileobject. To upload multiple files, thefilesparameter should be used with alistofFileobjects. Specifying both parameters will lead to an exception.To upload a single embed, the
embedparameter should be used with a singleEmbedobject. To upload multiple embeds, theembedsparameter should be used with alistofEmbedobjects. Specifying both parameters will lead to an exception.- Parameters:
content (Optional[
str]) – The content of the message to send.tts (
bool) – Indicates if the message should be sent using text-to-speech.embed (
Embed) – The rich embed for the content.file (
File) – The file to upload.files (List[
File]) – A list of files to upload. Must be a maximum of 10.nonce (Union[
int,str]) – 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_mentionsare used instead.Added in version 1.4.
reference (Union[
Message,MessageReference,PartialMessage]) –A reference to the
Messageto 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_userattribute ofallowed_mentionsor by settingmention_author.Added in version 1.6.
mention_author (Optional[
bool]) –If set, overrides the
replied_userattribute ofallowed_mentions.Added in version 1.6.
view (
nextcord.ui.View) – A Discord UI View to add to the message.embeds (List[
Embed]) –A list of embeds to upload. Must be a maximum of 10.
Added in version 2.0.
stickers (Sequence[Union[
GuildSticker,StickerItem]]) –A list of stickers to upload. Must be a maximum of 3.
Added in version 2.0.
flags (Optional[
MessageFlags]) –The message flags being set for this message. Currently only
suppress_embedsis able to be set.Added in version 2.4.
suppress_embeds (Optional[
bool]) –Whether to suppress embeds on this message.
Added in version 2.4.
- Raises:
HTTPException – Sending the message failed.
Forbidden – You do not have the proper permissions to send the message.
InvalidArgument – The
fileslist is not of the appropriate size, you specified bothfileandfiles, or you specified bothembedandembeds, or thereferenceobject is not aMessage,MessageReferenceorPartialMessage
- Returns:
The message that was sent.
- Return type:
- await set_permissions(target, *, reason=None, **kwargs)¶
This function is a coroutine.
Sets the channel specific permission overwrites for a target in the channel.
The
targetparameter should either be aMemberor aRolethat belongs to guild.The
overwriteparameter, if given, must either beNoneorPermissionOverwrite. For convenience, you can pass in keyword arguments denotingPermissionsattributes. If this is done, then you cannot mix the keyword arguments with theoverwriteparameter.If the
overwriteparameter isNone, then the permission overwrites are deleted.You must have the
manage_rolespermission to use this.Note
This method replaces the old overwrites with the ones given.
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
PermissionOverwriteoverwrite = nextcord.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, orNoneto 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
RoleorMember.
Thread¶
- applied_tag_ids
- applied_tags
- archive_timestamp
- archived
- archiver_id
- auto_archive_duration
- category
- category_id
- create_timestamp
- created_at
- guild
- id
- invitable
- jump_url
- last_message
- last_message_id
- locked
- me
- member_count
- members
- mention
- message_count
- name
- owner
- owner_id
- parent
- parent_id
- slowmode_delay
- type
- asyncadd_user
- asyncdelete
- asyncdelete_messages
- asyncedit
- asyncfetch_members
- asyncfetch_message
- asyncforward
- defget_partial_message
- defhistory
- defis_news
- defis_nsfw
- defis_private
- asyncjoin
- asyncleave
- defpermissions_for
- asyncpins
- asyncpurge
- asyncremove_user
- asyncsend
- asynctrigger_typing
- deftyping
- class nextcord.Thread¶
Represents a Discord thread.
- x == y
Checks if two threads are equal.
- x != y
Checks if two threads are not equal.
- hash(x)
Returns the thread’s hash.
- str(x)
Returns the thread’s name.
Added in version 2.0.
- parent_id¶
The parent
TextChannelID this thread belongs to.- Type:
- last_message_id¶
The last message ID of the message sent to this thread. It may not point to an existing or valid message.
- Type:
Optional[
int]
- slowmode_delay¶
The number of seconds a member must wait between sending messages in this thread. A value of
0denotes that it is disabled. Bots and users withmanage_channelsormanage_messagesbypass slowmode.- Type:
- me¶
A thread member representing yourself, if you’ve joined the thread. This could not be available.
- Type:
Optional[
ThreadMember]
- invitable¶
Whether non-moderators can add other non-moderators to this thread. This is always
Truefor public threads.- Type:
- auto_archive_duration¶
The duration in minutes until the thread is automatically archived due to inactivity. Usually a value of 60, 1440, 4320 and 10080.
- Type:
- archive_timestamp¶
An aware timestamp of when the thread’s archived status was last updated in UTC.
- Type:
- create_timestamp¶
Returns the threads’s creation time in UTC. This is
Noneif the thread was created before January 9th, 2021.Added in version 2.0.
- Type:
Optional[
datetime.datetime]
- applied_tag_ids¶
A list of tag IDs that have been applied to this thread.
Added in version 2.4.
- Type:
List[
int]
- async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)¶
This function returns an async iterator.
Returns an async iterator that enables receiving the destination’s message history.
You must have
read_message_historypermissions to use this.Examples
Usage
counter = 0 async for message in channel.history(limit=200): if message.author == client.user: counter += 1
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 datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.after (Optional[Union[
Snowflake,datetime.datetime]]) – Retrieve messages after this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.around (Optional[Union[
Snowflake,datetime.datetime]]) – Retrieve messages around this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time. When using this argument, the maximum limit is 101. Note that if the limit is an even number then this will return at most limit + 1 messages.oldest_first (Optional[
bool]) – If set toTrue, return messages in oldest->newest order. Defaults toTrueifafteris 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
withandasync withwork with this.Example Usage:
async with channel.typing(): # simulate something heavy await asyncio.sleep(10) await channel.send('done!')
- property created_at¶
Returns the threads’s creation time in UTC. This is
Noneif the thread was created before January 9th, 2021.Added in version 2.0.
- Type:
Optional[
datetime.datetime]
- property type¶
The channel’s Discord type.
- Type:
- property parent¶
The parent channel this thread belongs to.
- Type:
Optional[Union[
TextChannel,ForumChannel]]
- property members¶
A list of thread members in this thread.
This requires
Intents.membersto be properly filled. Most of the time however, this data is not provided by the gateway and a call tofetch_members()is needed.- Type:
List[
ThreadMember]
- 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_idattribute.- Returns:
The last message in this channel or
Noneif not found.- Return type:
Optional[
Message]
- property category¶
The category channel the parent channel belongs to, if applicable.
- Raises:
ClientException – The parent channel was not cached and returned
None.- Returns:
The parent channel’s category.
- Return type:
Optional[
CategoryChannel]
- property category_id¶
The category channel ID the parent channel belongs to, if applicable.
- Raises:
ClientException – The parent channel was not cached and returned
None.- Returns:
The parent channel’s category ID.
- Return type:
Optional[
int]
- property jump_url¶
Returns a URL that allows the client to jump to this channel.
Added in version 2.0.
- Type:
- property applied_tags¶
A list of tags applied to this thread.
This is
Noneif the parent channel was not found in cache.Added in version 2.4.
- Type:
Optional[List[
ForumTag]]
- is_private()¶
bool: Whether the thread is a private thread.A private thread is only viewable by those that have been explicitly invited or have
manage_threads.
- is_news()¶
bool: Whether the thread is a news thread.A news thread is a thread that has a parent that is a news channel, i.e.
TextChannel.is_news()isTrue.
- is_nsfw()¶
bool: Whether the thread is NSFW or not.An NSFW thread is a thread that has a parent that is an NSFW channel, i.e.
TextChannel.is_nsfw()isTrue.
- permissions_for(obj, /)¶
Handles permission resolution for the
MemberorRole.Since threads do not have their own permissions, they inherit them from the parent channel. This is a convenience method for calling
permissions_for()on the parent channel.- Parameters:
obj (Union[
Member,Role]) – The object to resolve permissions for. This could be either a member or a role. If it’s a role then member overwrites are not computed.- Raises:
ClientException – The parent channel was not cached and returned
None- Returns:
The resolved permissions for the member or role.
- 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_messagespermission 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=..., 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 acheckis not provided then all messages are deleted without discrimination.You must have the
manage_messagespermission to delete messages even if they are your own (unless you are a user account). Theread_message_historypermission is also needed to retrieve message history.Examples
Deleting bot’s messages
def is_me(m): return m.author == client.user deleted = await thread.purge(limit=100, check=is_me) await thread.send(f'Deleted {len(deleted)} message(s)')
- 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 aMessageas its sole parameter.before (Optional[Union[
abc.Snowflake,datetime.datetime]]) – Same asbeforeinhistory().after (Optional[Union[
abc.Snowflake,datetime.datetime]]) – Same asafterinhistory().around (Optional[Union[
abc.Snowflake,datetime.datetime]]) – Same asaroundinhistory().oldest_first (Optional[
bool]) – Same asoldest_firstinhistory().bulk (
bool) – IfTrue, use bulk delete. Setting this toFalseis useful for mass-deleting a bot’s own messages withoutPermissions.manage_messages. WhenTrue, will fall back to single delete 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 edit(*, name=..., archived=..., locked=..., invitable=..., slowmode_delay=..., auto_archive_duration=..., flags=..., applied_tags=...)¶
This function is a coroutine.
Edits the thread.
Editing the thread requires
Permissions.manage_threads. The thread creator can also editname,archivedorauto_archive_duration. Note that if the thread is locked then only those withPermissions.manage_threadscan unarchive a thread.The thread must be unarchived to be edited.
- Parameters:
name (
str) – The new name of the thread.archived (
bool) – Whether to archive the thread or not.locked (
bool) – Whether to lock the thread or not.invitable (
bool) – Whether non-moderators can add other non-moderators to this thread. Only available for private threads.auto_archive_duration (
int) – The new duration in minutes before a thread is automatically archived for inactivity. Must be one of60,1440,4320, or10080.slowmode_delay (
int) – Specifies the slowmode rate limit for user in this thread, in seconds. A value of0disables slowmode. The maximum value possible is21600.flags (
ChannelFlags) –The new channel flags to use for this thread.
Added in version 2.1.
applied_tags (List[
ForumTag]) –The new tags to apply to this thread.
Added in version 2.4.
- Raises:
Forbidden – You do not have permissions to edit the thread.
HTTPException – Editing the thread failed.
- Returns:
The newly edited thread.
- Return type:
- await join()¶
This function is a coroutine.
Joins this thread.
You must have
send_messages_in_threadsto join a thread. If the thread is private,manage_threadsis also needed.- Raises:
Forbidden – You do not have permissions to join the thread.
HTTPException – Joining the thread failed.
- await leave()¶
This function is a coroutine.
Leaves this thread.
- Raises:
HTTPException – Leaving the thread failed.
- await add_user(user)¶
This function is a coroutine.
Adds a user to this thread.
You must have
send_messagesanduse_threadsto add a user to a public thread. If the thread is private thensend_messagesand eitheruse_private_threadsormanage_messagesis required to add a user to the thread.- Parameters:
user (
abc.Snowflake) – The user to add to the thread.- Raises:
Forbidden – You do not have permissions to add the user to the thread.
HTTPException – Adding the user to the thread failed.
- await remove_user(user)¶
This function is a coroutine.
Removes a user from this thread.
You must have
manage_threadsor be the creator of the thread to remove a user.- Parameters:
user (
abc.Snowflake) – The user to add to the thread.- Raises:
Forbidden – You do not have permissions to remove the user from the thread.
HTTPException – Removing the user from the thread failed.
- await fetch_members()¶
This function is a coroutine.
Retrieves all
ThreadMemberthat are in this thread.This requires
Intents.membersto get information about members other than yourself.- Raises:
HTTPException – Retrieving the members failed.
- Returns:
All thread members in the thread.
- Return type:
List[
ThreadMember]
- await delete()¶
This function is a coroutine.
Deletes this thread.
You must have
manage_threadsto delete threads.- Raises:
Forbidden – You do not have permissions to delete this thread.
HTTPException – Deleting the thread failed.
- get_partial_message(message_id, /)¶
Creates a
PartialMessagefrom 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.
Added in version 2.0.
- 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
Messagefrom the destination.- 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 forward(message)¶
Forward a message to this channel.
- Parameters:
message (
Message) – The message to forward.note:: (..) – It is not possible to forward messages through interactions. It is only possible to forward a message to a channel as a message.
- Raises:
HTTPException – Forwarding/sending the message failed.
Forbidden – You do not have the proper permissions to send the message.
.. versionadded: – 3.0:
- 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
Messageobjects returned by this method do not contain completeMessage.reactionsdata.- 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, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, mention_author=None, view=None, flags=None, suppress_embeds=None)¶
This function is a coroutine.
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through
str(content). If the content is set toNone(the default), then theembedorembedsparameter must be provided.To upload a single file, the
fileparameter should be used with a singleFileobject. To upload multiple files, thefilesparameter should be used with alistofFileobjects. Specifying both parameters will lead to an exception.To upload a single embed, the
embedparameter should be used with a singleEmbedobject. To upload multiple embeds, theembedsparameter should be used with alistofEmbedobjects. Specifying both parameters will lead to an exception.- Parameters:
content (Optional[
str]) – The content of the message to send.tts (
bool) – Indicates if the message should be sent using text-to-speech.embed (
Embed) – The rich embed for the content.file (
File) – The file to upload.files (List[
File]) – A list of files to upload. Must be a maximum of 10.nonce (Union[
int,str]) – 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_mentionsare used instead.Added in version 1.4.
reference (Union[
Message,MessageReference,PartialMessage]) –A reference to the
Messageto 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_userattribute ofallowed_mentionsor by settingmention_author.Added in version 1.6.
mention_author (Optional[
bool]) –If set, overrides the
replied_userattribute ofallowed_mentions.Added in version 1.6.
view (
nextcord.ui.View) – A Discord UI View to add to the message.embeds (List[
Embed]) –A list of embeds to upload. Must be a maximum of 10.
Added in version 2.0.
stickers (Sequence[Union[
GuildSticker,StickerItem]]) –A list of stickers to upload. Must be a maximum of 3.
Added in version 2.0.
flags (Optional[
MessageFlags]) –The message flags being set for this message. Currently only
suppress_embedsis able to be set.Added in version 2.4.
suppress_embeds (Optional[
bool]) –Whether to suppress embeds on this message.
Added in version 2.4.
- Raises:
HTTPException – Sending the message failed.
Forbidden – You do not have the proper permissions to send the message.
InvalidArgument – The
fileslist is not of the appropriate size, you specified bothfileandfiles, or you specified bothembedandembeds, or thereferenceobject is not aMessage,MessageReferenceorPartialMessage
- Returns:
The message that was sent.
- Return type:
ThreadMember¶
- class nextcord.ThreadMember¶
Represents a Discord thread member.
- x == y
Checks if two thread members are equal.
- x != y
Checks if two thread members are not equal.
- hash(x)
Returns the thread member’s hash.
- str(x)
Returns the thread member’s name.
Added in version 2.0.
- joined_at¶
The time the member joined the thread in UTC.
- Type:
- await fetch_member()¶
Member: Retrieves theMemberof this thread member.Note
This method is an API call. If you have
Intents.membersand members cache enabled, considermemberinstead.
VoiceChannel¶
- asyncclone
- asyncconnect
- asynccreate_invite
- asynccreate_webhook
- asyncdelete
- asyncdelete_messages
- asyncedit
- asyncfetch_message
- asyncforward
- defhistory
- asyncinvites
- defis_nsfw
- asyncmove
- defoverwrites_for
- defpermissions_for
- asyncpurge
- asyncsend
- asyncset_permissions
- asynctrigger_typing
- deftyping
- asyncwebhooks
- class nextcord.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.
- 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
Noneindicates automatic voice region detection.Added in version 1.7.
- Type:
Optional[
VoiceRegion]
- video_quality_mode¶
The camera video quality for the voice channel’s participants.
Added in version 2.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.
Added in version 2.1.
- Type:
Optional[
int]
- nsfw¶
If the channel is marked as “not safe for work”.
Note
To check if the channel or the guild of that channel are marked as NSFW, consider
is_nsfw()instead.Added in version 2.1.
- Type:
- flags¶
Extra features of the channel.
..versionadded:: 2.1
- Type:
- property type¶
The channel’s Discord type.
- Type:
- 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_idattribute.Added in version 2.1.
- Returns:
The last message in this channel or
Noneif not found.- Return type:
Optional[
Message]
- 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_channelspermission to do this.Added 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_channelspermission to use this.Changed in version 1.3: The
overwriteskeyword-only parameter was added.Changed in version 2.0: Edits are no longer in-place, the newly edited channel is returned instead.
- Parameters:
name (
str) – The new channel’s name.bitrate (
int) – The new channel’s bitrate.user_limit (
int) –The new channel’s user limit.
This must be a number between
0and99.0indicates no 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 beNoneto remove the category.reason (Optional[
str]) – The reason for editing this channel. Shows up on the audit log.overwrites (
Mapping) – AMappingof target (either a role or a member) toPermissionOverwriteto apply to the channel.rtc_region (Optional[
VoiceRegion]) –The new region for the voice channel’s voice communication. A value of
Noneindicates automatic voice region detection.Added in version 1.7.
video_quality_mode (
VideoQualityMode) –The camera video quality for the voice channel’s participants.
Added in version 2.0.
- 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.
- Returns:
The newly edited voice channel. If the edit was only positional then
Noneis returned instead.- Return type:
Optional[
VoiceChannel]
- 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_messagespermission to use this.Added in version 2.1.
- 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.
NotFound – If single delete, then the message was already deleted.
HTTPException – Deleting the messages failed.
- await purge(*, limit=100, check=..., 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 acheckis not provided then all messages are deleted without discrimination.You must have the
manage_messagespermission to delete messages even if they are your own. Theread_message_historypermission is also needed to retrieve message history.Added in version 2.1.
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(f'Deleted {len(deleted)} message(s)')
- 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 aMessageas its sole parameter.before (Optional[Union[
abc.Snowflake,datetime.datetime]]) – Same asbeforeinhistory().after (Optional[Union[
abc.Snowflake,datetime.datetime]]) – Same asafterinhistory().around (Optional[Union[
abc.Snowflake,datetime.datetime]]) – Same asaroundinhistory().oldest_first (Optional[
bool]) – Same asoldest_firstinhistory().bulk (
bool) – IfTrue, use bulk delete. Setting this toFalseis useful for mass-deleting a bot’s own messages withoutPermissions.manage_messages. WhenTrue, will fall back to single delete 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 create_webhook(*, name, avatar=None, reason=None)¶
This function is a coroutine.
Creates a webhook for this channel.
Requires
manage_webhookspermissions.Added in version 2.4.
- Parameters:
name (
str) – The webhook’s name.avatar (Optional[Union[
bytes,Asset,Attachment,File]]) – A bytes-like object,File,Attachment, orAssetrepresenting 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 webhooks()¶
This function is a coroutine.
Gets the list of webhooks from this channel.
Requires
manage_webhookspermissions.Added in version 3.0.
- 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
rolesattribute.- Type:
List[
Role]
- await connect(*, timeout=60.0, reconnect=True, cls=<class 'nextcord.voice_client.VoiceClient'>)¶
This function is a coroutine.
Connects to voice and creates a
VoiceClientto establish your connection to the voice server.This requires
Intents.voice_states.- 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 subclassesVoiceProtocolto 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, max_age=0, max_uses=0, temporary=False, unique=True, target_type=None, target_user=None, target_application_id=None)¶
This function is a coroutine.
Creates an instant invite from a text or voice channel.
You must have the
create_instant_invitepermission 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 toFalsethen it will return a previously created invite.reason (Optional[
str]) – The reason for creating this invite. Shows up on the audit log.target_type (Optional[
InviteTarget]) –The type of target for the voice channel invite, if any.
Added in version 2.0.
target_user (Optional[
User]) –The user whose stream to display for this invite, required if
target_typeisInviteTarget.stream. The user must be streaming in the channel.Added in version 2.0.
target_application_id: –
Optional[
int]: The id of the embedded application for the invite, required iftarget_typeisInviteTarget.embedded_application.Added in version 2.0.
- 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:
- property created_at¶
Returns the channel’s creation time in UTC.
- Type:
- await delete(*, reason=None)¶
This function is a coroutine.
Deletes the channel.
You must have
manage_channelspermission 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
Messagefrom the destination.- 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 forward(message)¶
Forward a message to this channel.
- Parameters:
message (
Message) – The message to forward.note:: (..) – It is not possible to forward messages through interactions. It is only possible to forward a message to a channel as a message.
- Raises:
HTTPException – Forwarding/sending the message failed.
Forbidden – You do not have the proper permissions to send the message.
.. versionadded: – 3.0:
- history(*, limit=100, before=None, after=None, around=None, oldest_first=None)¶
This function returns an async iterator.
Returns an async iterator that enables receiving the destination’s message history.
You must have
read_message_historypermissions to use this.Examples
Usage
counter = 0 async for message in channel.history(limit=200): if message.author == client.user: counter += 1
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 datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.after (Optional[Union[
Snowflake,datetime.datetime]]) – Retrieve messages after this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.around (Optional[Union[
Snowflake,datetime.datetime]]) – Retrieve messages around this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time. When using this argument, the maximum limit is 101. Note that if the limit is an even number then this will return at most limit + 1 messages.oldest_first (Optional[
bool]) – If set toTrue, return messages in oldest->newest order. Defaults toTrueifafteris 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_channelsto 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 jump_url¶
Returns a URL that allows the client to jump to this channel.
Added in version 2.0.
- Type:
- property members¶
Returns all members that are currently inside this voice channel.
- Type:
List[
Member]
- await move(*, beginning=None, end=None, before=None, after=None, offset=0, category=..., sync_permissions=False, reason=None)¶
This function is a coroutine.
A rich interface to help move a channel relative to other channels.
If exact position movement is required,
editshould be used instead.You must have the
manage_channelspermission to do this.Note
Voice channels will always be sorted below text channels. This is a Discord limitation.
Added in version 1.7.
Changed in version 2.4:
beginning,end,before,afterandreasonnow acceptNone.- Parameters:
beginning (Optional[
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 (Optional[
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 (Optional[
Snowflake]) – The channel that should be before our current channel. This is mutually exclusive withbeginning,end, andafter.after (Optional[
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 of2withbeginning=Truewould 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, andafterparameters.category (Optional[
Snowflake]) – The category to move this channel under. IfNoneis 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 (Optional[
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
Roleor aMemberand the value is the overwrite as aPermissionOverwrite.- Returns:
The channel’s permission overwrites.
- Return type:
Dict[Union[
Role,Member],PermissionOverwrite]
- overwrites_for(obj)¶
Returns the channel-specific overwrites for a member or a role.
- permissions_for(obj, /)¶
Handles permission resolution for the
MemberorRole.This function takes into consideration the following cases:
Guild owner
Guild roles
Channel overrides
Member overrides
Timed-out members
If a
Roleis passed, then it checks the permissions someone with that role would have, which is essentially:The default role permissions
The permissions of the role used as a parameter
The default role permission overwrites
The permission overwrites of the role used as a parameter
Changed in version 2.3: Only
view_channelandread_message_historycan be returned for timed-out membersChanged in version 2.0: The object passed in can now be a role object.
- property permissions_synced¶
Whether or not the permissions for this channel are synced with the category it belongs to.
If there is no category then this is
False.Added in version 1.3.
- Type:
- await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, mention_author=None, view=None, flags=None, suppress_embeds=None)¶
This function is a coroutine.
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through
str(content). If the content is set toNone(the default), then theembedorembedsparameter must be provided.To upload a single file, the
fileparameter should be used with a singleFileobject. To upload multiple files, thefilesparameter should be used with alistofFileobjects. Specifying both parameters will lead to an exception.To upload a single embed, the
embedparameter should be used with a singleEmbedobject. To upload multiple embeds, theembedsparameter should be used with alistofEmbedobjects. Specifying both parameters will lead to an exception.- Parameters:
content (Optional[
str]) – The content of the message to send.tts (
bool) – Indicates if the message should be sent using text-to-speech.embed (
Embed) – The rich embed for the content.file (
File) – The file to upload.files (List[
File]) – A list of files to upload. Must be a maximum of 10.nonce (Union[
int,str]) – 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_mentionsare used instead.Added in version 1.4.
reference (Union[
Message,MessageReference,PartialMessage]) –A reference to the
Messageto 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_userattribute ofallowed_mentionsor by settingmention_author.Added in version 1.6.
mention_author (Optional[
bool]) –If set, overrides the
replied_userattribute ofallowed_mentions.Added in version 1.6.
view (
nextcord.ui.View) – A Discord UI View to add to the message.embeds (List[
Embed]) –A list of embeds to upload. Must be a maximum of 10.
Added in version 2.0.
stickers (Sequence[Union[
GuildSticker,StickerItem]]) –A list of stickers to upload. Must be a maximum of 3.
Added in version 2.0.
flags (Optional[
MessageFlags]) –The message flags being set for this message. Currently only
suppress_embedsis able to be set.Added in version 2.4.
suppress_embeds (Optional[
bool]) –Whether to suppress embeds on this message.
Added in version 2.4.
- Raises:
HTTPException – Sending the message failed.
Forbidden – You do not have the proper permissions to send the message.
InvalidArgument – The
fileslist is not of the appropriate size, you specified bothfileandfiles, or you specified bothembedandembeds, or thereferenceobject is not aMessage,MessageReferenceorPartialMessage
- Returns:
The message that was sent.
- Return type:
- await set_permissions(target, *, reason=None, **kwargs)¶
This function is a coroutine.
Sets the channel specific permission overwrites for a target in the channel.
The
targetparameter should either be aMemberor aRolethat belongs to guild.The
overwriteparameter, if given, must either beNoneorPermissionOverwrite. For convenience, you can pass in keyword arguments denotingPermissionsattributes. If this is done, then you cannot mix the keyword arguments with theoverwriteparameter.If the
overwriteparameter isNone, then the permission overwrites are deleted.You must have the
manage_rolespermission to use this.Note
This method replaces the old overwrites with the ones given.
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
PermissionOverwriteoverwrite = nextcord.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, orNoneto 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
RoleorMember.
- 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
withandasync withwork with this.Example Usage:
async with channel.typing(): # simulate something heavy await asyncio.sleep(10) await channel.send('done!')
- property voice_states¶
Returns a mapping of member IDs who have voice states in this channel.
Added in version 1.3.
Note
This function is intentionally low level to replace
memberswhen the member cache is unavailable.- Returns:
The mapping of member ID to a voice state.
- Return type:
Mapping[
int,VoiceState]
StageChannel¶
- asyncclone
- asyncconnect
- asynccreate_instance
- asynccreate_invite
- asyncdelete
- asyncedit
- asyncfetch_instance
- asyncfetch_message
- asyncforward
- defhistory
- asyncinvites
- defis_nsfw
- asyncmove
- defoverwrites_for
- defpermissions_for
- asyncsend
- asyncset_permissions
- asynctrigger_typing
- deftyping
- asyncwebhooks
- class nextcord.StageChannel¶
Represents a Discord guild stage channel.
Added 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.
- 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
Noneindicates automatic voice region detection.- Type:
Optional[
VoiceRegion]
- video_quality_mode¶
The camera video quality for the stage channel’s participants.
Added in version 2.0.
- Type:
- flags¶
Extra features of the channel.
..versionadded:: 2.1
- Type:
- nsfw¶
If the channel is marked as “not safe for work”.
Added in version 2.6.
Note
To check if the channel or the guild of that channel are marked as NSFW, consider
is_nsfw()instead.- Type:
- property requesting_to_speak¶
A list of members who are requesting to speak in the stage channel.
- Type:
List[
Member]
- property speakers¶
A list of members who have been permitted to speak in the stage channel.
Added in version 2.0.
- Type:
List[
Member]
- property listeners¶
A list of members who are listening in the stage channel.
Added in version 2.0.
- Type:
List[
Member]
- property moderators¶
A list of members who are moderating the stage channel.
Added in version 2.0.
- Type:
List[
Member]
- property type¶
The channel’s Discord type.
- Type:
- await clone(*, name=None, reason=None)¶
This function is a coroutine.
Clones this channel. This creates a channel with the same properties as this channel.
You must have the
manage_channelspermission to do this.Added 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:
- property instance¶
The running stage instance of the stage channel.
Added in version 2.0.
- Type:
Optional[
StageInstance]
- await create_instance(*, topic, privacy_level=..., send_start_notification=False, scheduled_event=..., reason=None)¶
This function is a coroutine.
Create a stage instance.
You must have the
manage_channelspermission to use this.Added in version 2.0.
- Parameters:
topic (
str) – The stage instance’s topic.privacy_level (
StagePrivacyLevel) – The stage instance’s privacy level. Defaults toStagePrivacyLevel.guild_only.send_start_notification (
bool) –Whether to notify
@everyonethat the stage instance has started. Defaults toFalse.Added in version 3.0.
scheduled_event (
abc.Snowflake) –The scheduled event associated with this stage instance.
Added in version 3.0.
reason (
str) – The reason the stage instance was created. Shows up on the audit log.
- Raises:
InvalidArgument – If the
privacy_levelparameter is not the proper type.Forbidden – You do not have permissions to create a stage instance.
HTTPException – Creating a stage instance failed.
- Returns:
The newly created stage instance.
- Return type:
- await fetch_instance()¶
This function is a coroutine.
Gets the running
StageInstance.Added in version 2.0.
- Raises:
.NotFound – The stage instance or channel could not be found.
.HTTPException – Getting the stage instance failed.
- Returns:
The stage instance.
- Return type:
- await edit(*, reason=None, **options)¶
This function is a coroutine.
Edits the channel.
You must have the
manage_channelspermission to use this.Changed in version 2.0: The
topicparameter must now be set viacreate_instance.Changed in version 2.0: Edits are no longer in-place, the newly edited channel is returned instead.
- Parameters:
name (
str) – The new channel’s name.position (
int) – The new channel’s position.sync_permissions (
bool) – Whether to sync permissions with the channel’s new or pre-existing category. Defaults toFalse.category (Optional[
CategoryChannel]) – The new category for this channel. Can beNoneto remove the category.reason (Optional[
str]) – The reason for editing this channel. Shows up on the audit log.overwrites (
Mapping) – AMappingof target (either a role or a member) toPermissionOverwriteto apply to the channel.rtc_region (Optional[
VoiceRegion]) – The new region for the stage channel’s voice communication. A value ofNoneindicates automatic voice region detection.video_quality_mode (
VideoQualityMode) –The camera video quality for the stage channel’s participants.
Added in version 2.0.
user_limit (
int) –The maximum number of users allowed in the stage channel.
This must be between
0and10,000. A value of0indicates no limit.Added in version 2.6.
- 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.
- Returns:
The newly edited stage channel. If the edit was only positional then
Noneis returned instead.- Return type:
Optional[
StageChannel]
- await webhooks()¶
This function is a coroutine.
Gets the list of webhooks from this channel.
Requires
manage_webhookspermissions.Added in version 3.0.
- 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
rolesattribute.- Type:
List[
Role]
- await connect(*, timeout=60.0, reconnect=True, cls=<class 'nextcord.voice_client.VoiceClient'>)¶
This function is a coroutine.
Connects to voice and creates a
VoiceClientto establish your connection to the voice server.This requires
Intents.voice_states.- 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 subclassesVoiceProtocolto 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, max_age=0, max_uses=0, temporary=False, unique=True, target_type=None, target_user=None, target_application_id=None)¶
This function is a coroutine.
Creates an instant invite from a text or voice channel.
You must have the
create_instant_invitepermission 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 toFalsethen it will return a previously created invite.reason (Optional[
str]) – The reason for creating this invite. Shows up on the audit log.target_type (Optional[
InviteTarget]) –The type of target for the voice channel invite, if any.
Added in version 2.0.
target_user (Optional[
User]) –The user whose stream to display for this invite, required if
target_typeisInviteTarget.stream. The user must be streaming in the channel.Added in version 2.0.
target_application_id: –
Optional[
int]: The id of the embedded application for the invite, required iftarget_typeisInviteTarget.embedded_application.Added in version 2.0.
- 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:
- property created_at¶
Returns the channel’s creation time in UTC.
- Type:
- await delete(*, reason=None)¶
This function is a coroutine.
Deletes the channel.
You must have
manage_channelspermission 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
Messagefrom the destination.- 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 forward(message)¶
Forward a message to this channel.
- Parameters:
message (
Message) – The message to forward.note:: (..) – It is not possible to forward messages through interactions. It is only possible to forward a message to a channel as a message.
- Raises:
HTTPException – Forwarding/sending the message failed.
Forbidden – You do not have the proper permissions to send the message.
.. versionadded: – 3.0:
- history(*, limit=100, before=None, after=None, around=None, oldest_first=None)¶
This function returns an async iterator.
Returns an async iterator that enables receiving the destination’s message history.
You must have
read_message_historypermissions to use this.Examples
Usage
counter = 0 async for message in channel.history(limit=200): if message.author == client.user: counter += 1
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 datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.after (Optional[Union[
Snowflake,datetime.datetime]]) – Retrieve messages after this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.around (Optional[Union[
Snowflake,datetime.datetime]]) – Retrieve messages around this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time. When using this argument, the maximum limit is 101. Note that if the limit is an even number then this will return at most limit + 1 messages.oldest_first (Optional[
bool]) – If set toTrue, return messages in oldest->newest order. Defaults toTrueifafteris 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_channelsto 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 jump_url¶
Returns a URL that allows the client to jump to this channel.
Added in version 2.0.
- Type:
- property members¶
Returns all members that are currently inside this voice channel.
- Type:
List[
Member]
- await move(*, beginning=None, end=None, before=None, after=None, offset=0, category=..., sync_permissions=False, reason=None)¶
This function is a coroutine.
A rich interface to help move a channel relative to other channels.
If exact position movement is required,
editshould be used instead.You must have the
manage_channelspermission to do this.Note
Voice channels will always be sorted below text channels. This is a Discord limitation.
Added in version 1.7.
Changed in version 2.4:
beginning,end,before,afterandreasonnow acceptNone.- Parameters:
beginning (Optional[
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 (Optional[
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 (Optional[
Snowflake]) – The channel that should be before our current channel. This is mutually exclusive withbeginning,end, andafter.after (Optional[
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 of2withbeginning=Truewould 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, andafterparameters.category (Optional[
Snowflake]) – The category to move this channel under. IfNoneis 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 (Optional[
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
Roleor aMemberand the value is the overwrite as aPermissionOverwrite.- Returns:
The channel’s permission overwrites.
- Return type:
Dict[Union[
Role,Member],PermissionOverwrite]
- overwrites_for(obj)¶
Returns the channel-specific overwrites for a member or a role.
- permissions_for(obj, /)¶
Handles permission resolution for the
MemberorRole.This function takes into consideration the following cases:
Guild owner
Guild roles
Channel overrides
Member overrides
Timed-out members
If a
Roleis passed, then it checks the permissions someone with that role would have, which is essentially:The default role permissions
The permissions of the role used as a parameter
The default role permission overwrites
The permission overwrites of the role used as a parameter
Changed in version 2.3: Only
view_channelandread_message_historycan be returned for timed-out membersChanged in version 2.0: The object passed in can now be a role object.
- property permissions_synced¶
Whether or not the permissions for this channel are synced with the category it belongs to.
If there is no category then this is
False.Added in version 1.3.
- Type:
- await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, mention_author=None, view=None, flags=None, suppress_embeds=None)¶
This function is a coroutine.
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through
str(content). If the content is set toNone(the default), then theembedorembedsparameter must be provided.To upload a single file, the
fileparameter should be used with a singleFileobject. To upload multiple files, thefilesparameter should be used with alistofFileobjects. Specifying both parameters will lead to an exception.To upload a single embed, the
embedparameter should be used with a singleEmbedobject. To upload multiple embeds, theembedsparameter should be used with alistofEmbedobjects. Specifying both parameters will lead to an exception.- Parameters:
content (Optional[
str]) – The content of the message to send.tts (
bool) – Indicates if the message should be sent using text-to-speech.embed (
Embed) – The rich embed for the content.file (
File) – The file to upload.files (List[
File]) – A list of files to upload. Must be a maximum of 10.nonce (Union[
int,str]) – 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_mentionsare used instead.Added in version 1.4.
reference (Union[
Message,MessageReference,PartialMessage]) –A reference to the
Messageto 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_userattribute ofallowed_mentionsor by settingmention_author.Added in version 1.6.
mention_author (Optional[
bool]) –If set, overrides the
replied_userattribute ofallowed_mentions.Added in version 1.6.
view (
nextcord.ui.View) – A Discord UI View to add to the message.embeds (List[
Embed]) –A list of embeds to upload. Must be a maximum of 10.
Added in version 2.0.
stickers (Sequence[Union[
GuildSticker,StickerItem]]) –A list of stickers to upload. Must be a maximum of 3.
Added in version 2.0.
flags (Optional[
MessageFlags]) –The message flags being set for this message. Currently only
suppress_embedsis able to be set.Added in version 2.4.
suppress_embeds (Optional[
bool]) –Whether to suppress embeds on this message.
Added in version 2.4.
- Raises:
HTTPException – Sending the message failed.
Forbidden – You do not have the proper permissions to send the message.
InvalidArgument – The
fileslist is not of the appropriate size, you specified bothfileandfiles, or you specified bothembedandembeds, or thereferenceobject is not aMessage,MessageReferenceorPartialMessage
- Returns:
The message that was sent.
- Return type:
- await set_permissions(target, *, reason=None, **kwargs)¶
This function is a coroutine.
Sets the channel specific permission overwrites for a target in the channel.
The
targetparameter should either be aMemberor aRolethat belongs to guild.The
overwriteparameter, if given, must either beNoneorPermissionOverwrite. For convenience, you can pass in keyword arguments denotingPermissionsattributes. If this is done, then you cannot mix the keyword arguments with theoverwriteparameter.If the
overwriteparameter isNone, then the permission overwrites are deleted.You must have the
manage_rolespermission to use this.Note
This method replaces the old overwrites with the ones given.
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
PermissionOverwriteoverwrite = nextcord.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, orNoneto 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
RoleorMember.
- 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
withandasync withwork with this.Example Usage:
async with channel.typing(): # simulate something heavy await asyncio.sleep(10) await channel.send('done!')
- property voice_states¶
Returns a mapping of member IDs who have voice states in this channel.
Added in version 1.3.
Note
This function is intentionally low level to replace
memberswhen the member cache is unavailable.- Returns:
The mapping of member ID to a voice state.
- Return type:
Mapping[
int,VoiceState]
StageInstance¶
- class nextcord.StageInstance¶
Represents a stage instance of a stage channel in a guild.
Added in version 2.0.
- x == y
Checks if two stage instances are equal.
- x != y
Checks if two stage instances are not equal.
- hash(x)
Returns the stage instance’s hash.
- privacy_level¶
The privacy level of the stage instance.
- Type:
- scheduled_event_id¶
The ID of the scheduled event for this stage instance.
Added in version 3.0.
- Type:
Optional[
int]
- channel¶
The channel that stage instance is running in.
- Type:
Optional[
StageChannel]
- scheduled_event¶
The scheduled event for this stage instance.
Added in version 3.0.
- Type:
Optional[
ScheduledEvent]
- await edit(*, topic=..., privacy_level=..., reason=None)¶
This function is a coroutine.
Edits the stage instance.
You must have the
manage_channelspermission to use this.- Parameters:
topic (
str) – The stage instance’s new topic.privacy_level (
StagePrivacyLevel) – The stage instance’s new privacy level.reason (
str) – The reason the stage instance was edited. Shows up on the audit log.
- Raises:
InvalidArgument – If the
privacy_levelparameter is not the proper type.Forbidden – You do not have permissions to edit the stage instance.
HTTPException – Editing a stage instance failed.
- await delete(*, reason=None)¶
This function is a coroutine.
Deletes the stage instance.
You must have the
manage_channelspermission to use this.- Parameters:
reason (
str) – The reason the stage instance was deleted. Shows up on the audit log.- Raises:
Forbidden – You do not have permissions to delete the stage instance.
HTTPException – Deleting the stage instance failed.
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 nextcord.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:
- nsfw¶
If the channel is marked as “not safe for work”.
Note
To check if the channel or the guild of that channel are marked as NSFW, consider
is_nsfw()instead.- Type:
- flags¶
Extra features of the channel.
..versionadded:: 2.1
- Type:
- property type¶
The channel’s Discord type.
- Type:
- await clone(*, name=None, reason=None)¶
This function is a coroutine.
Clones this channel. This creates a channel with the same properties as this channel.
You must have the
manage_channelspermission to do this.Added 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_channelspermission to use this.Changed in version 1.3: The
overwriteskeyword-only parameter was added.Changed in version 2.0: Edits are no longer in-place, the newly edited channel is returned instead.
- 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 (
Mapping) – AMappingof target (either a role or a member) toPermissionOverwriteto 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.
- Returns:
The newly edited category channel. If the edit was only positional then
Noneis returned instead.- Return type:
Optional[
CategoryChannel]
- await move(*, beginning=None, end=None, before=None, after=None, offset=0, category=..., sync_permissions=False, reason=None)¶
This function is a coroutine.
A rich interface to help move a channel relative to other channels.
If exact position movement is required,
editshould be used instead.You must have the
manage_channelspermission to do this.Note
Voice channels will always be sorted below text channels. This is a Discord limitation.
Added in version 1.7.
Changed in version 2.4:
beginning,end,before,afterandreasonnow acceptNone.- Parameters:
beginning (Optional[
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 (Optional[
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 (Optional[
Snowflake]) – The channel that should be before our current channel. This is mutually exclusive withbeginning,end, andafter.after (Optional[
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 of2withbeginning=Truewould 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, andafterparameters.category (Optional[
Snowflake]) – The category to move this channel under. IfNoneis 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 (Optional[
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 stage channels that are under this category.
Added in version 1.7.
- Type:
List[
StageChannel]
- await create_text_channel(name, **options)¶
This function is a coroutine.
A shortcut method to
Guild.create_text_channel()to create aTextChannelin the category.- Returns:
The channel that was just created.
- Return type:
- await create_voice_channel(name, **options)¶
This function is a coroutine.
A shortcut method to
Guild.create_voice_channel()to create aVoiceChannelin the category.- Returns:
The channel that was just created.
- Return type:
- await create_stage_channel(name, **options)¶
This function is a coroutine.
A shortcut method to
Guild.create_stage_channel()to create aStageChannelin the category.Added in version 1.7.
- Returns:
The channel that was just created.
- Return type:
- await create_forum_channel(name, **options)¶
This function is a coroutine.
A shortcut method to
Guild.create_forum_channel()to create aForumChannelin the category.Added in version 2.1.
- 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
rolesattribute.- Type:
List[
Role]
- await create_invite(*, reason=None, max_age=0, max_uses=0, temporary=False, unique=True, target_type=None, target_user=None, target_application_id=None)¶
This function is a coroutine.
Creates an instant invite from a text or voice channel.
You must have the
create_instant_invitepermission 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 toFalsethen it will return a previously created invite.reason (Optional[
str]) – The reason for creating this invite. Shows up on the audit log.target_type (Optional[
InviteTarget]) –The type of target for the voice channel invite, if any.
Added in version 2.0.
target_user (Optional[
User]) –The user whose stream to display for this invite, required if
target_typeisInviteTarget.stream. The user must be streaming in the channel.Added in version 2.0.
target_application_id: –
Optional[
int]: The id of the embedded application for the invite, required iftarget_typeisInviteTarget.embedded_application.Added in version 2.0.
- 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:
- property created_at¶
Returns the channel’s creation time in UTC.
- Type:
- await delete(*, reason=None)¶
This function is a coroutine.
Deletes the channel.
You must have
manage_channelspermission 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_channelsto 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 jump_url¶
Returns a URL that allows the client to jump to this channel.
Added in version 2.0.
- Type:
- 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
Roleor aMemberand the value is the overwrite as aPermissionOverwrite.- Returns:
The channel’s permission overwrites.
- Return type:
Dict[Union[
Role,Member],PermissionOverwrite]
- overwrites_for(obj)¶
Returns the channel-specific overwrites for a member or a role.
- permissions_for(obj, /)¶
Handles permission resolution for the
MemberorRole.This function takes into consideration the following cases:
Guild owner
Guild roles
Channel overrides
Member overrides
Timed-out members
If a
Roleis passed, then it checks the permissions someone with that role would have, which is essentially:The default role permissions
The permissions of the role used as a parameter
The default role permission overwrites
The permission overwrites of the role used as a parameter
Changed in version 2.3: Only
view_channelandread_message_historycan be returned for timed-out membersChanged in version 2.0: The object passed in can now be a role object.
- property permissions_synced¶
Whether or not the permissions for this channel are synced with the category it belongs to.
If there is no category then this is
False.Added in version 1.3.
- Type:
- await set_permissions(target, *, reason=None, **kwargs)¶
This function is a coroutine.
Sets the channel specific permission overwrites for a target in the channel.
The
targetparameter should either be aMemberor aRolethat belongs to guild.The
overwriteparameter, if given, must either beNoneorPermissionOverwrite. For convenience, you can pass in keyword arguments denotingPermissionsattributes. If this is done, then you cannot mix the keyword arguments with theoverwriteparameter.If the
overwriteparameter isNone, then the permission overwrites are deleted.You must have the
manage_rolespermission to use this.Note
This method replaces the old overwrites with the ones given.
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
PermissionOverwriteoverwrite = nextcord.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, orNoneto 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
RoleorMember.
DMChannel¶
- asyncfetch_message
- asyncforward
- defget_partial_message
- defhistory
- defpermissions_for
- asyncpins
- asyncsend
- asynctrigger_typing
- deftyping
- class nextcord.DMChannel¶
Represents a Discord direct message channel.
- x == y
Checks if two channels are equal.
- x != y
Checks if two channels are not equal.
- hash(x)
Returns the channel’s hash.
- str(x)
Returns a string representation of the channel
- recipient¶
The user you are participating with in the direct message channel. If this channel is received through the gateway, the recipient information may not be always available.
- Type:
Optional[
User]
- me¶
The user presenting yourself.
- Type:
- async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)¶
This function returns an async iterator.
Returns an async iterator that enables receiving the destination’s message history.
You must have
read_message_historypermissions to use this.Examples
Usage
counter = 0 async for message in channel.history(limit=200): if message.author == client.user: counter += 1
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 datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.after (Optional[Union[
Snowflake,datetime.datetime]]) – Retrieve messages after this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.around (Optional[Union[
Snowflake,datetime.datetime]]) – Retrieve messages around this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time. When using this argument, the maximum limit is 101. Note that if the limit is an even number then this will return at most limit + 1 messages.oldest_first (Optional[
bool]) – If set toTrue, return messages in oldest->newest order. Defaults toTrueifafteris 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
withandasync withwork with this.Example Usage:
async with channel.typing(): # simulate something heavy await asyncio.sleep(10) await channel.send('done!')
- property type¶
The channel’s Discord type.
- Type:
- property created_at¶
Returns the direct message channel’s creation time in UTC.
- Type:
- permissions_for(obj=None, /)¶
Handles permission resolution for a
User.This function is there for compatibility with other channel types.
Actual direct messages do not really have the concept of permissions.
This returns all the Text related permissions set to
Trueexcept:send_tts_messages: You cannot send TTS messages in a DM.manage_messages: You cannot delete others messages in a DM.
- Parameters:
obj (
User) – The user to check permissions for. This parameter is ignored but kept for compatibility with otherpermissions_formethods.- Returns:
The resolved permissions.
- Return type:
- get_partial_message(message_id, /)¶
Creates a
PartialMessagefrom 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.
Added 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
Messagefrom the destination.- 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 forward(message)¶
Forward a message to this channel.
- Parameters:
message (
Message) – The message to forward.note:: (..) – It is not possible to forward messages through interactions. It is only possible to forward a message to a channel as a message.
- Raises:
HTTPException – Forwarding/sending the message failed.
Forbidden – You do not have the proper permissions to send the message.
.. versionadded: – 3.0:
- property jump_url¶
Returns a URL that allows the client to jump to the referenced messageable.
Added in version 2.0.
- 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
Messageobjects returned by this method do not contain completeMessage.reactionsdata.- 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, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, mention_author=None, view=None, flags=None, suppress_embeds=None)¶
This function is a coroutine.
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through
str(content). If the content is set toNone(the default), then theembedorembedsparameter must be provided.To upload a single file, the
fileparameter should be used with a singleFileobject. To upload multiple files, thefilesparameter should be used with alistofFileobjects. Specifying both parameters will lead to an exception.To upload a single embed, the
embedparameter should be used with a singleEmbedobject. To upload multiple embeds, theembedsparameter should be used with alistofEmbedobjects. Specifying both parameters will lead to an exception.- Parameters:
content (Optional[
str]) – The content of the message to send.tts (
bool) – Indicates if the message should be sent using text-to-speech.embed (
Embed) – The rich embed for the content.file (
File) – The file to upload.files (List[
File]) – A list of files to upload. Must be a maximum of 10.nonce (Union[
int,str]) – 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_mentionsare used instead.Added in version 1.4.
reference (Union[
Message,MessageReference,PartialMessage]) –A reference to the
Messageto 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_userattribute ofallowed_mentionsor by settingmention_author.Added in version 1.6.
mention_author (Optional[
bool]) –If set, overrides the
replied_userattribute ofallowed_mentions.Added in version 1.6.
view (
nextcord.ui.View) – A Discord UI View to add to the message.embeds (List[
Embed]) –A list of embeds to upload. Must be a maximum of 10.
Added in version 2.0.
stickers (Sequence[Union[
GuildSticker,StickerItem]]) –A list of stickers to upload. Must be a maximum of 3.
Added in version 2.0.
flags (Optional[
MessageFlags]) –The message flags being set for this message. Currently only
suppress_embedsis able to be set.Added in version 2.4.
suppress_embeds (Optional[
bool]) –Whether to suppress embeds on this message.
Added in version 2.4.
- Raises:
HTTPException – Sending the message failed.
Forbidden – You do not have the proper permissions to send the message.
InvalidArgument – The
fileslist is not of the appropriate size, you specified bothfileandfiles, or you specified bothembedandembeds, or thereferenceobject is not aMessage,MessageReferenceorPartialMessage
- Returns:
The message that was sent.
- Return type:
GroupChannel¶
- asyncfetch_message
- asyncforward
- defhistory
- asyncleave
- defpermissions_for
- asyncpins
- asyncsend
- asynctrigger_typing
- deftyping
- class nextcord.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
- me¶
The user presenting yourself.
- Type:
- async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)¶
This function returns an async iterator.
Returns an async iterator that enables receiving the destination’s message history.
You must have
read_message_historypermissions to use this.Examples
Usage
counter = 0 async for message in channel.history(limit=200): if message.author == client.user: counter += 1
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 datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.after (Optional[Union[
Snowflake,datetime.datetime]]) – Retrieve messages after this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.around (Optional[Union[
Snowflake,datetime.datetime]]) – Retrieve messages around this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time. When using this argument, the maximum limit is 101. Note that if the limit is an even number then this will return at most limit + 1 messages.oldest_first (Optional[
bool]) – If set toTrue, return messages in oldest->newest order. Defaults toTrueifafteris 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
withandasync withwork with this.Example Usage:
async with channel.typing(): # simulate something heavy await asyncio.sleep(10) await channel.send('done!')
- property type¶
The channel’s Discord type.
- Type:
- property created_at¶
Returns the channel’s creation time in UTC.
- Type:
- permissions_for(obj, /)¶
Handles permission resolution for a
User.This function is there for compatibility with other channel types.
Actual direct messages do not really have the concept of permissions.
This returns all the Text related permissions set to
Trueexcept: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:
obj (
Snowflake) – The user to check permissions for.- Returns:
The resolved permissions for the user.
- Return type:
- 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
Messagefrom the destination.- 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 forward(message)¶
Forward a message to this channel.
- Parameters:
message (
Message) – The message to forward.note:: (..) – It is not possible to forward messages through interactions. It is only possible to forward a message to a channel as a message.
- Raises:
HTTPException – Forwarding/sending the message failed.
Forbidden – You do not have the proper permissions to send the message.
.. versionadded: – 3.0:
- property jump_url¶
Returns a URL that allows the client to jump to the referenced messageable.
Added in version 2.0.
- 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
Messageobjects returned by this method do not contain completeMessage.reactionsdata.- 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, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, mention_author=None, view=None, flags=None, suppress_embeds=None)¶
This function is a coroutine.
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through
str(content). If the content is set toNone(the default), then theembedorembedsparameter must be provided.To upload a single file, the
fileparameter should be used with a singleFileobject. To upload multiple files, thefilesparameter should be used with alistofFileobjects. Specifying both parameters will lead to an exception.To upload a single embed, the
embedparameter should be used with a singleEmbedobject. To upload multiple embeds, theembedsparameter should be used with alistofEmbedobjects. Specifying both parameters will lead to an exception.- Parameters:
content (Optional[
str]) – The content of the message to send.tts (
bool) – Indicates if the message should be sent using text-to-speech.embed (
Embed) – The rich embed for the content.file (
File) – The file to upload.files (List[
File]) – A list of files to upload. Must be a maximum of 10.nonce (Union[
int,str]) – 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_mentionsare used instead.Added in version 1.4.
reference (Union[
Message,MessageReference,PartialMessage]) –A reference to the
Messageto 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_userattribute ofallowed_mentionsor by settingmention_author.Added in version 1.6.
mention_author (Optional[
bool]) –If set, overrides the
replied_userattribute ofallowed_mentions.Added in version 1.6.
view (
nextcord.ui.View) – A Discord UI View to add to the message.embeds (List[
Embed]) –A list of embeds to upload. Must be a maximum of 10.
Added in version 2.0.
stickers (Sequence[Union[
GuildSticker,StickerItem]]) –A list of stickers to upload. Must be a maximum of 3.
Added in version 2.0.
flags (Optional[
MessageFlags]) –The message flags being set for this message. Currently only
suppress_embedsis able to be set.Added in version 2.4.
suppress_embeds (Optional[
bool]) –Whether to suppress embeds on this message.
Added in version 2.4.
- Raises:
HTTPException – Sending the message failed.
Forbidden – You do not have the proper permissions to send the message.
InvalidArgument – The
fileslist is not of the appropriate size, you specified bothfileandfiles, or you specified bothembedandembeds, or thereferenceobject is not aMessage,MessageReferenceorPartialMessage
- Returns:
The message that was sent.
- Return type:
ForumChannel¶
- available_tags
- category
- category_id
- changed_roles
- created_at
- default_auto_archive_duration
- default_forum_layout
- default_reaction
- default_sort_order
- default_thread_slowmode_delay
- flags
- guild
- id
- jump_url
- last_message
- last_message_id
- members
- mention
- name
- nsfw
- overwrites
- permissions_synced
- position
- slowmode_delay
- threads
- topic
- type
- defarchived_threads
- asyncclone
- asynccreate_invite
- asynccreate_thread
- asynccreate_webhook
- asyncdelete
- asyncedit
- defget_tag
- defget_thread
- asyncinvites
- defis_nsfw
- asyncmove
- defoverwrites_for
- defpermissions_for
- asyncset_permissions
- asyncwebhooks
- class nextcord.ForumChannel¶
Represents a Discord guild forum channel.
Added in version 2.1.
- 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 ID of the
CategoryChannelthis channel belongs to, if any.- Type:
Optional[
int]
- topic¶
The topic of this channel, if any. This is what is shown in the “Guidelines” section visually.
- Type:
- flags¶
The flags that detail features of this channel.
- Type:
- default_auto_archive_duration¶
The archive duration which threads from this channel inherit by default.
- Type:
- last_message_id¶
The snowflake ID of the message starting the last thread in this channel.
- Type:
- default_sort_order¶
The default sort order type used to sort posts in forum channels.
Added in version 2.3.
- Type:
- default_forum_layout¶
The default layout type used to display posts in this forum.
Added in version 2.4.
- Type:
- default_thread_slowmode_delay¶
The default amount of seconds a user has to wait before creating another thread in this channel. This is set on every new thread in this channel.
Added in version 2.4.
- Type:
- default_reaction¶
The emoji that is used to add a reaction to every post in this forum.
Added in version 2.4.
- Type:
Optional[
PartialEmoji]
- property type¶
The channel’s Discord type.
- Type:
- permissions_for(obj, /)¶
Handles permission resolution for the
MemberorRole.This function takes into consideration the following cases:
Guild owner
Guild roles
Channel overrides
Member overrides
Timed-out members
If a
Roleis passed, then it checks the permissions someone with that role would have, which is essentially:The default role permissions
The permissions of the role used as a parameter
The default role permission overwrites
The permission overwrites of the role used as a parameter
Changed in version 2.3: Only
view_channelandread_message_historycan be returned for timed-out membersChanged in version 2.0: The object passed in can now be a role object.
- property last_message¶
Fetches the message that started the last thread 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_idattribute.- Returns:
The message that started the last thread in this channel or
Noneif not found.- Return type:
Optional[
Message]
- property available_tags¶
Returns all the tags available in this channel.
Added in version 2.4.
- Type:
List[
ForumTag]
- get_tag(id, /)¶
Returns a tag from this channel by its ID.
Added in version 2.4.
- await edit(*, reason=None, **options)¶
This function is a coroutine.
Edits the channel.
You must have the
manage_channelspermission to use this.- Parameters:
name (
str) – The new channel name.topic (
str) – The new channel’s topic.position (
int) – The new channel’s position.nsfw (
bool) – To mark the channel as NSFW or not.sync_permissions (
bool) – Whether to sync permissions with the channel’s new or pre-existing category. Defaults toFalse.category (Optional[
CategoryChannel]) – The new category for this channel. Can beNoneto remove the category.slowmode_delay (
int) – Specifies the slowmode rate limit for user in this channel, in seconds. A value of0disables slowmode. The maximum value possible is21600.reason (Optional[
str]) – The reason for editing this channel. Shows up on the audit log.overwrites (
Mapping) – AMappingof target (either a role or a member) toPermissionOverwriteto apply to the channel.default_auto_archive_duration (
int) – The new default auto archive duration in minutes for threads created in this channel. Must be one of60,1440,4320, or10080.flags (
ChannelFlags) –The new channel flags.
Added in version 2.1.
default_sort_order (
SortOrderType) –The default sort order type used to sort posts in forum channels.
Added in version 2.3.
default_forum_layout (
ForumLayoutType) –The default layout type used to display posts in.
Added in version 2.4.
default_thread_slowmode_delay (
int) –The new default slowmode delay for threads created in this channel. This is not retroactively applied to old posts. Must be between
0and21600.Added in version 2.4.
available_tags (List[
ForumTag]) –The new list of tags available in this channel.
Added in version 2.4.
default_reaction (Optional[Union[
Emoji,PartialEmoji,str]]) –The new default reaction for threads created in this channel.
Added in version 2.4.
- 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.
- Returns:
The newly edited forum channel.
- Return type:
- get_thread(thread_id, /)¶
Returns a thread with the given ID.
- await create_thread(*, name, auto_archive_duration=..., slowmode_delay=0, content=None, embed=None, embeds=None, file=None, files=None, stickers=None, nonce=None, allowed_mentions=None, mention_author=None, view=None, reason=None, applied_tags=None, flags=None, suppress_embeds=None)¶
This function is a coroutine.
Creates a thread in this forum channel.
To create a public thread, you must have
create_public_threads. For a private thread,create_private_threadsis needed instead.- Parameters:
name (
str) – The name of the thread.auto_archive_duration (
int) – The duration in minutes before a thread is automatically archived for inactivity. If not provided, the channel’s default auto archive duration is used.reason (
str) – The reason for creating a new thread. Shows up on the audit log.content (Optional[
str]) – The content of the message to send.embed (Optional[
Embed]) – The rich embed for the content.embeds (Optional[List[
Embed]]) – A list of rich embeds for the content.file (
File) – The file to upload.files (Optional[List[
File]]) – A list of files to upload. Must be a maximum of 10.nonce (Optional[
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.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_mentionsare used instead.mention_author (Optional[
bool]) – Whether to mention the author of the message being replied to. Defaults toTrue.view (Optional[
View]) – The view to send with the message.stickers (Optional[Sequence[Union[
GuildSticker,StickerItem]]]) – A list of stickers to send with the message.applied_tags (Optional[List[
ForumTag]]) –A list of tags to apply to the thread.
Added in version 2.4.
flags (Optional[
MessageFlags]) – The message flags being set for this message. Currently onlysuppress_embedsis able to be set. .. versionadded:: 2.4suppress_embeds (Optional[
bool]) – Whether to suppress embeds on this message. .. versionadded:: 2.4
- Raises:
Forbidden – You do not have permissions to create a thread.
HTTPException – Starting the thread failed.
InvalidArgument – You cannot pass both
embedandembedsparameters.
- Returns:
The created thread.
- Return type:
- archived_threads(*, private=False, joined=False, limit=50, before=None)¶
This function returns an async iterator.
Returns an async iterator that iterates over all archived threads in the guild.
You must have
read_message_historyto use this. If iterating over private threads thenmanage_threadsis also required.- Parameters:
limit (Optional[
bool]) – The number of threads to retrieve. IfNone, retrieves every archived thread in the channel. Note, however, that this would make it a slow operation.before (Optional[Union[
abc.Snowflake,datetime.datetime]]) – Retrieve archived channels before the given date or ID.private (
bool) – Whether to retrieve private archived threads.joined (
bool) – Whether to retrieve private archived threads that you’ve joined. This defaults toFalse.note:: (..) – You cannot set
joinedtoTrueandprivatetoFalse.
- Raises:
Forbidden – You do not have permissions to get archived threads.
HTTPException – The request to get the archived threads failed.
- Yields:
Thread– The archived threads.
- await create_webhook(*, name, avatar=None, reason=None)¶
This function is a coroutine.
Creates a webhook for this channel.
Requires
manage_webhookspermissions.Added in version 2.4.
- Parameters:
name (
str) – The webhook’s name.avatar (Optional[Union[
bytes,Asset,Attachment,File]]) – A bytes-like object,File,Attachment, orAssetrepresenting 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 webhooks()¶
This function is a coroutine.
Gets the list of webhooks from this channel.
Requires
manage_webhookspermissions.Added in version 3.0.
- 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
rolesattribute.- Type:
List[
Role]
- 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_channelspermission to do this.Added 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 create_invite(*, reason=None, max_age=0, max_uses=0, temporary=False, unique=True, target_type=None, target_user=None, target_application_id=None)¶
This function is a coroutine.
Creates an instant invite from a text or voice channel.
You must have the
create_instant_invitepermission 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 toFalsethen it will return a previously created invite.reason (Optional[
str]) – The reason for creating this invite. Shows up on the audit log.target_type (Optional[
InviteTarget]) –The type of target for the voice channel invite, if any.
Added in version 2.0.
target_user (Optional[
User]) –The user whose stream to display for this invite, required if
target_typeisInviteTarget.stream. The user must be streaming in the channel.Added in version 2.0.
target_application_id: –
Optional[
int]: The id of the embedded application for the invite, required iftarget_typeisInviteTarget.embedded_application.Added in version 2.0.
- 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:
- property created_at¶
Returns the channel’s creation time in UTC.
- Type:
- await delete(*, reason=None)¶
This function is a coroutine.
Deletes the channel.
You must have
manage_channelspermission 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_channelsto 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 jump_url¶
Returns a URL that allows the client to jump to this channel.
Added in version 2.0.
- Type:
- await move(*, beginning=None, end=None, before=None, after=None, offset=0, category=..., sync_permissions=False, reason=None)¶
This function is a coroutine.
A rich interface to help move a channel relative to other channels.
If exact position movement is required,
editshould be used instead.You must have the
manage_channelspermission to do this.Note
Voice channels will always be sorted below text channels. This is a Discord limitation.
Added in version 1.7.
Changed in version 2.4:
beginning,end,before,afterandreasonnow acceptNone.- Parameters:
beginning (Optional[
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 (Optional[
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 (Optional[
Snowflake]) – The channel that should be before our current channel. This is mutually exclusive withbeginning,end, andafter.after (Optional[
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 of2withbeginning=Truewould 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, andafterparameters.category (Optional[
Snowflake]) – The category to move this channel under. IfNoneis 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 (Optional[
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
Roleor aMemberand the value is the overwrite as aPermissionOverwrite.- Returns:
The channel’s permission overwrites.
- Return type:
Dict[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.Added in version 1.3.
- Type:
- await set_permissions(target, *, reason=None, **kwargs)¶
This function is a coroutine.
Sets the channel specific permission overwrites for a target in the channel.
The
targetparameter should either be aMemberor aRolethat belongs to guild.The
overwriteparameter, if given, must either beNoneorPermissionOverwrite. For convenience, you can pass in keyword arguments denotingPermissionsattributes. If this is done, then you cannot mix the keyword arguments with theoverwriteparameter.If the
overwriteparameter isNone, then the permission overwrites are deleted.You must have the
manage_rolespermission to use this.Note
This method replaces the old overwrites with the ones given.
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
PermissionOverwriteoverwrite = nextcord.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, orNoneto 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
RoleorMember.
PartialInviteGuild¶
- class nextcord.PartialInviteGuild¶
Represents a “partial” invite guild.
This model will be given when the user is not part of the guild the
Inviteresolves 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.
- verification_level¶
The partial guild’s verification level.
- Type:
- features¶
A list of features the guild has. See
Guild.featuresfor more information.- Type:
List[
str]
- property created_at¶
Returns the guild’s creation time in UTC.
- Type:
PartialInviteChannel¶
- class nextcord.PartialInviteChannel¶
Represents a “partial” invite channel.
This model will be given when the user is not part of the guild the
Inviteresolves 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.
- type¶
The partial channel’s type.
- Type:
- property created_at¶
Returns the channel’s creation time in UTC.
- Type:
Invite¶
- asyncdelete
- class nextcord.Invite¶
Represents a Discord
Guildorabc.GuildChannelinvite.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
Client.fetch_invite()withwith_countsenabledClient.fetch_invite()withwith_countsenabledClient.fetch_invite()withwith_expirationenabledIf it’s not in the table above then it is available by all methods.
- max_age¶
How long before the invite expires in seconds. A value of
0indicates that it doesn’t expire.- Type:
- guild¶
The guild the invite is for. Can be
Noneif it’s from a group direct message.- Type:
Optional[Union[
Guild,Object,PartialInviteGuild]]
- created_at¶
An aware UTC datetime object denoting the time the invite was created.
- Type:
- 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
0indicates that it has unlimited uses.- Type:
- approximate_presence_count¶
The approximate number of members currently active in the guild. This includes idle, dnd, online, and invisible members. Offline members are excluded.
- Type:
Optional[
int]
- expires_at¶
The expiration date of the invite. If the value is
Nonewhen received throughClient.fetch_invite()withwith_expirationenabled, the invite will never expire.Added in version 2.0.
- Type:
Optional[
datetime.datetime]
- channel¶
The channel the invite is for.
- Type:
Union[
abc.GuildChannel,Object,PartialInviteChannel]
- target_type¶
The type of target for the voice channel invite.
Added in version 2.0.
- Type:
- target_user¶
The user whose stream to display for this invite, if any.
Added in version 2.0.
- Type:
Optional[
User]
- target_application¶
The embedded application the invite targets, if any.
Added in version 2.0.
- Type:
Optional[
PartialAppInfo]
- type¶
The type of invite.
Added in version 3.0.
- Type:
- property id¶
Returns the proper code portion of the invite.
Note
This may be
Noneif it is the vanity invite the code is not set.- Type:
Optional[
str]
- property url¶
A property that retrieves the invite URL.
Note
This may be an empty string if it is the vanity URL and the code is not set
- Type:
- await delete(*, reason=None)¶
This function is a coroutine.
Revokes the instant invite.
You must have the
manage_channelspermission 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 nextcord.Template¶
Represents a Discord template.
Added in version 1.4.
- created_at¶
An aware datetime in UTC representing when the template was created.
- Type:
- updated_at¶
An aware datetime in UTC representing when the template was last updated. This is referred to as “last synced” in the official Discord client.
- Type:
- await create_guild(name, region=None, icon=None)¶
This function is a coroutine.
Creates a
Guildusing the template.Bot accounts in more than 10 guilds are not allowed to create guilds.
Changed in version 2.1: The
iconparameter now acceptsFile,Attachment, andAsset.- Parameters:
name (
str) – The name of the guild.region (
VoiceRegion) – The region for the voice communication server. Defaults toVoiceRegion.us_west.icon (Optional[Union[
bytes,Asset,Attachment,File]]) – The bytes-like object,File,Attachment, orAssetrepresenting 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_guildpermission in the source guild to do this.Added in version 1.7.
Changed in version 2.0: The template is no longer edited in-place, instead it is returned.
- Raises:
HTTPException – Editing the template failed.
Forbidden – You don’t have permissions to edit the template.
NotFound – This template does not exist.
- Returns:
The newly edited template.
- Return type:
- await edit(*, name=..., description=...)¶
This function is a coroutine.
Edit the template metadata.
You must have the
manage_guildpermission in the source guild to do this.Added in version 1.7.
Changed in version 2.0: The template is no longer edited in-place, instead it is returned.
- Parameters:
- Raises:
HTTPException – Editing the template failed.
Forbidden – You don’t have permissions to edit the template.
NotFound – This template does not exist.
- Returns:
The newly edited template.
- Return type:
- await delete()¶
This function is a coroutine.
Delete the template.
You must have the
manage_guildpermission in the source guild to do this.Added 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 nextcord.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.
- property created_at¶
Returns the channel’s creation time in UTC.
- Type:
WidgetMember¶
- defmentioned_in
- class nextcord.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.
- activity¶
The member’s activity.
- Type:
Optional[Union[
BaseActivity,Spotify]]
- connected_channel¶
Which channel the member is connected to.
- Type:
Optional[
WidgetChannel]
- property display_name¶
Returns the user’s display name.
This will return the name using the following hierarchy:
Guild specific nickname
Global Name (also known as ‘Display Name’ in the Discord UI)
Unique username
- Type:
- property accent_color¶
Returns the user’s accent color, if applicable.
There is an alias for this named
accent_colour.Added in version 2.0.
Note
This information is only available via
Client.fetch_user().- Type:
Optional[
Colour]
- property accent_colour¶
Returns the user’s accent colour, if applicable.
There is an alias for this named
accent_color.Added in version 2.0.
Note
This information is only available via
Client.fetch_user().- Type:
Optional[
Colour]
- property avatar_decoration¶
Returns the user’s avatar decoration, if applicable.
You can get the asset of the avatar decoration via
AvatarDecoration.asset.Added in version 3.2.
- Type:
Optional[
AvatarDecoration]
- property banner¶
Returns the user’s banner asset, if available.
Added in version 2.0.
Note
This information is only available via
Client.fetch_user().- 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.
- ..versionchanged:: 2.6
Added handling for the new username system for users without a discriminator.
- Type:
- property display_avatar¶
Returns the user’s display avatar.
For regular users this is just their default avatar or uploaded avatar.
Added in version 2.0.
- Type:
- mentioned_in(message)¶
Checks if the user is mentioned in the specified message.
- property public_flags¶
The publicly available flags the user has.
- Type:
Widget¶
- asyncfetch_invite
- class nextcord.Widget¶
Represents a
Guildwidget.- 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:
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:
List[
Member]
- property created_at¶
Returns the member’s creation time in UTC.
- Type:
- await fetch_invite(*, with_counts=True)¶
This function is a coroutine.
Retrieves an
Invitefrom the widget’s invite URL. 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_countandInvite.approximate_presence_countfields.- Returns:
The invite from the widget’s invite URL.
- Return type:
StickerPack¶
- class nextcord.StickerPack¶
Represents a sticker pack.
Added in version 2.0.
- str(x)
Returns the name of the sticker pack.
- x == y
Checks if the sticker pack is equal to another sticker pack.
- x != y
Checks if the sticker pack is not equal to another sticker pack.
- stickers¶
The stickers of this sticker pack.
- Type:
List[
StandardSticker]
- cover_sticker¶
The sticker used for the cover of the sticker pack.
- Type:
StickerItem¶
- class nextcord.StickerItem¶
Represents a sticker item.
Added in version 2.0.
- str(x)
Returns the name of the sticker item.
- x == y
Checks if the sticker item is equal to another sticker item.
- x != y
Checks if the sticker item is not equal to another sticker item.
- format¶
The format for the sticker’s image.
- Type:
- await fetch()¶
This function is a coroutine.
Attempts to retrieve the full sticker data of the sticker item.
- Raises:
HTTPException – Retrieving the sticker failed.
- Returns:
The retrieved sticker.
- Return type:
Union[
StandardSticker,GuildSticker]
Sticker¶
- class nextcord.Sticker¶
Represents a sticker.
Added 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.
- format¶
The format for the sticker’s image.
- Type:
- property created_at¶
Returns the sticker’s creation time in UTC.
- Type:
StandardSticker¶
- asyncpack
- class nextcord.StandardSticker¶
Represents a sticker that is found in a standard sticker pack.
Added in version 2.0.
- str(x)
Returns the name of the sticker.
- x == y
Checks if the sticker is equal to another sticker.
- x != y
Checks if the sticker is not equal to another sticker.
- format¶
The format for the sticker’s image.
- Type:
- await pack()¶
This function is a coroutine.
Retrieves the sticker pack that this sticker belongs to.
- Raises:
InvalidData – The corresponding sticker pack was not found.
HTTPException – Retrieving the sticker pack failed.
- Returns:
The retrieved sticker pack.
- Return type:
GuildSticker¶
- class nextcord.GuildSticker¶
Represents a sticker that belongs to a guild.
Added in version 2.0.
- str(x)
Returns the name of the sticker.
- x == y
Checks if the sticker is equal to another sticker.
- x != y
Checks if the sticker is not equal to another sticker.
- format¶
The format for the sticker’s image.
- Type:
- user¶
The user that created this sticker. This can only be retrieved using
Guild.fetch_sticker()and having themanage_emojis_and_stickerspermission.- Type:
Optional[
User]
- guild¶
The guild that this sticker is from. Could be
Noneif the bot is not in the guild.Added in version 2.0.
- Type:
Optional[
Guild]
- await edit(*, name=..., description=..., emoji=..., reason=None)¶
This function is a coroutine.
Edits a
GuildStickerfor the guild.- Parameters:
name (
str) – The sticker’s new name. Must be at least 2 characters.description (Optional[
str]) – The sticker’s new description. Can beNone.emoji (
str) – The name of a unicode emoji that represents the sticker’s expression.reason (
str) – The reason for editing this sticker. Shows up on the audit log.
- Raises:
Forbidden – You are not allowed to edit stickers.
HTTPException – An error occurred editing the sticker.
- Returns:
The newly modified sticker.
- Return type:
- await delete(*, reason=None)¶
This function is a coroutine.
Deletes the custom
Stickerfrom the guild.You must have
manage_emojis_and_stickerspermission to do this.- Parameters:
reason (Optional[
str]) – The reason for deleting this sticker. Shows up on the audit log.- Raises:
Forbidden – You are not allowed to delete stickers.
HTTPException – An error occurred deleting the sticker.
RawTypingEvent¶
- class nextcord.RawTypingEvent¶
Represents the payload for a
on_raw_typing()event.Added in version 2.0.
- when¶
When the typing started as an aware datetime in UTC.
- Type:
RawMessageDeleteEvent¶
- class nextcord.RawMessageDeleteEvent¶
Represents the event payload for a
on_raw_message_delete()event.
RawBulkMessageDeleteEvent¶
- class nextcord.RawBulkMessageDeleteEvent¶
Represents the event payload for a
on_raw_bulk_message_delete()event.
RawMessageUpdateEvent¶
- class nextcord.RawMessageUpdateEvent¶
Represents the payload for a
on_raw_message_edit()event.- guild_id¶
The guild ID where the message got updated, if applicable.
Added 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 nextcord.RawReactionActionEvent¶
Represents the payload for a
on_raw_reaction_add()oron_raw_reaction_remove()event.- emoji¶
The custom or unicode emoji being used.
- Type:
RawReactionClearEvent¶
- class nextcord.RawReactionClearEvent¶
Represents the payload for a
on_raw_reaction_clear()event.
RawReactionClearEmojiEvent¶
- class nextcord.RawReactionClearEmojiEvent¶
Represents the payload for a
on_raw_reaction_clear_emoji()event.Added in version 1.3.
- emoji¶
The custom or unicode emoji being removed.
- Type:
RawIntegrationDeleteEvent¶
- class nextcord.RawIntegrationDeleteEvent¶
Represents the payload for a
on_raw_integration_delete()event.Added in version 2.0.
PartialWebhookGuild¶
- class nextcord.PartialWebhookGuild¶
Represents a partial guild for webhooks.
These are typically given for channel follower webhooks.
Added in version 2.0.
PartialWebhookChannel¶
ScheduledEvent¶
- asyncdelete
- asyncedit
- deffetch_users
- defget_user
- class nextcord.ScheduledEvent¶
Represents a Discord scheduled event
Added in version 2.0.
- x == y
Checks if two events are equal.
- x != y
Checks if two events are not equal.
- hash(x)
Returns the event’s hash.
- str(x)
Returns the event’s name.
- channel¶
The channel the event will take place, if any.
- Type:
Optional[
abc.GuildChannel]
- end_time¶
The scheduled end time for the event, if set.
- Type:
- metadata¶
The metadata for the event, if any.
- Type:
Optional[
EntityMetadata]
- privacy_level¶
The privacy level for the event.
- start_time¶
The scheduled start time for the event.
- Type:
- property users¶
The users who are interested in the event.
Note
This may not be accurate or populated until
fetch_users()is called- Type:
List[
ScheduledEventUser]
- await edit(*, channel=..., metadata=..., name=..., privacy_level=..., start_time=..., end_time=..., description=..., type=..., status=..., reason=None, image=...)¶
This function is a coroutine.
Edit the scheduled event.
Changed in version 2.1: The
imageparameter now acceptsFile,Attachment, andAsset.- Parameters:
channel (
abc.GuildChannel) – The new channel for the event.metadata (
EntityMetadata) – The new metadata for the event.name (
str) – The new name for the event.privacy_level (
ScheduledEventPrivacyLevel) – The new privacy level for the event.start_time (
datetime.datetime) – The new scheduled start time.end_time (
datetime.datetime) – The new scheduled end time.description (
str) – The new description for the event.type (
ScheduledEventEntityType) – The new type for the event.status (
ScheduledEventStatus) – The new status for the event.reason (Optional[
str]) –The reason for editing this scheduled event. Shows up in the audit logs.
Note
Only the following edits to an event’s status are permitted: scheduled -> active ; active -> completed ; scheduled -> canceled
image (Optional[Union[
bytes,Asset,Attachment,File]]) – A bytes-like object,File,Attachment, orAssetrepresenting the cover image. Could beNoneto denote removal of the cover image.
- Returns:
The updated event object.
- Return type:
- get_user(user_id)¶
Get a user that is interested.
Note
This may not be accurate or populated until
ScheduledEvent.fetch_users()is called.- Parameters:
user_id (
int) – The user id to get from cache.- Returns:
The user object, if found.
- Return type:
Optional[
ScheduledEventUser]
- fetch_users(*, limit=100, with_member=False, before=None, after=None)¶
This function returns an async iterator.
Fetch the users that are interested, returns an async iterator.
- Parameters:
limit (
int) – Amount of users to fetch, by default 100with_member (
bool) – If the user objects should contain members too, by default Falsebefore (Optional[
int]) – A snowflake id to start with, useful for chunks of users, by default Noneafter (Optional[
int]) – A snowflake id to end with, useful for chunks of usersby default None
- Yields:
ScheduledEventUser– A full event user object
- class nextcord.ScheduledEventUser¶
Represents a user in a scheduled event
- event¶
The event the user is interested in.
- Type:
- member¶
The related member object, if requested with
ScheduledEvent.fetch_users().- Type:
Optional[
Member]
Warning
user or member may be
None, this may occur if you don’t haveIntents.membersenabled.
AutoModerationRule¶
- class nextcord.AutoModerationRule¶
Represents a Discord auto moderation rule.
Added in version 2.1.
- x == y
Checks if two rules are equal.
- x != y
Checks if two rules are not equal.
- hash(x)
Returns the rules’s hash.
- str(x)
Returns the rules’s name.
- event_type¶
The event context in which this rule is checked.
- Type:
- trigger_type¶
The type of content that can trigger this rule.
- trigger_metadata¶
Additional data that is used when checking if this rule is triggered.
- actions¶
The actions which will execute when the rule is triggered.
- Type:
List[
AutoModerationAction]
- exempt_roles¶
The roles that should not be affected by the rule, if found in cache.
- Type:
List[
Role]
- exempt_channels¶
The channels that should not be affected by the rule, if found in cache.
- Type:
List[
abc.GuildChannel]
- await delete(*, reason=None)¶
This function is a coroutine.
Delete the current rule from its guild.
Requires the
manage_guildpermission.- Parameters:
reason (Optional[
str]) – The reason for deleting this rule. Shows up on the audit log.- Raises:
Forbidden – You do not have permission to delete this rule.
HTTPException – Deleting the rule failed.
- await edit(*, name=..., event_type=..., trigger_metadata=..., actions=..., enabled=..., exempt_roles=..., exempt_channels=..., reason=None)¶
Modify the current auto moderation rule.
Requires the
manage_guildpermission.- Parameters:
name (
str) – The new name for this rule.event_type (
AutoModerationEventType) – The new event context in which this rule is checked.trigger_metadata (
AutoModerationTriggerMetadata) – The new additional data that is used when checking if this rule is triggered.actions (List[
AutoModerationAction]) – The new actions which will execute when the rule is triggered.enabled (
bool) – Whether the rule is enabled.exempt_roles (List[
abc.Snowflake]) – The new roles that should not be affected by the rule.exempt_channels (List[
abc.Snowflake]) – The new channels that should not be affected by the rule.reason (Optional[
str]) – The reason for editing this rule. Shows in the audit log.
- Raises:
Forbidden – You do not have permission to edit this rule.
HTTPException – Editing the rule failed.
InvalidArgument – An incorrect type was passed.
- Returns:
The newly edited auto moderation rule.
- Return type:
AutoModerationActionExecution¶
- class nextcord.AutoModerationActionExecution¶
Represents the execution of an auto moderation action
Added in version 2.1.
- channel¶
The channel where this action was executed, if applicable and found in cache.
- Type:
Optional[
abc.GuildChannel]
- message¶
The message that executed this action, if it was not blocked and found in cache.
- Type:
Optional[
Message]
- action¶
The action that was executed.
- Type:
- rule_trigger_type¶
The type of rule that was executed.
- content¶
The content the user sent in the message
Note
This requires
Intents.message_contentto not be empty.- Type:
- matched_keyword¶
The keyword configured in the rule that matched this message, if applicable.
- Type:
Optional[
str]
- matched_content¶
The content in the message that matched the keyword, if applicable.
Note
This requires
Intents.message_contentto not be empty.- Type:
Optional[
str]
MessageRoleSubscription¶
- class nextcord.MessageRoleSubscription¶
Represents a message’s role subscription information.
This is accessed through the
Message.role_subscriptionattribute if theMessage.typeisMessageType.role_subscription_purchase.Added in version 3.2.
- role_subscription_listing_id¶
The ID of the SKU and listing that the user is subscribed to.
- Type:
- total_months_subscribed¶
The cumulative number of months that the user has been subscribed for.
- Type:
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 Object, which is made with
dynamic attributes in mind.
Object¶
- class nextcord.Object(id)¶
Represents a generic Discord object.
The purpose of this class is to allow you to create ‘miniature’ versions of data classes if you want to pass in just an ID. Most functions that take in a specific data class with an ID can also take in this class as a substitute instead. Note that even though this is the case, not all objects (if any) actually inherit from this class.
There are also some cases where some websocket events are received in strange order and when such events happened you would receive this class rather than the actual data class. These cases are extremely rare.
- x == y
Checks if two objects are equal.
- x != y
Checks if two objects are not equal.
- hash(x)
Returns the object’s hash.
- property created_at¶
Returns the snowflake’s creation time in UTC.
- Type:
Embed¶
- clsEmbed.from_dict
- defadd_field
- defclear_fields
- defcopy
- definsert_field_at
- defremove_author
- defremove_field
- defremove_footer
- defset_author
- defset_field_at
- defset_footer
- defset_image
- defset_thumbnail
- defto_dict
- class nextcord.Embed(*, colour=None, color=None, title=None, type='rich', url=None, description=None, timestamp=None)¶
Represents a Discord embed.
- len(x)
Returns the total size of the embed. Useful for checking if it’s within the 6000 character limit.
- bool(b)
Returns whether the embed has any data set.
Added in version 2.0.
Certain properties return an
EmbedProxy, a type that acts similar to a regulardictexcept using dotted access, e.g.embed.author.icon_url. If the attribute is invalid or empty, thenNoneis returned.For ease of use, all parameters that expect a
strare implicitly casted tostrfor you.Changed in version 2.2:
Embed.Emptyis now an alias forNonefor a non-breaking change, every field usesNoneand is typed asOptional[...]overEmbed.Empty. This also means that you can no longer uselen()on an empty field.Changed in version 3.0:
Embed.Emptyhas been removed in favor ofNone.- 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:
- url¶
The hyperlink of the embed title. This can be set during initialisation. This makes no effect if there is no
titlefield.- Type:
- timestamp¶
The timestamp of the embed content. This is an aware datetime. If a naive datetime is passed, it is converted to an aware datetime with the local timezone.
- Type:
- colour¶
The colour code of the embed. Aliased to
coloras well. This can be set during initialisation.
- classmethod from_dict(data)¶
Converts a
dictto aEmbedprovided it is in the format that Discord expects it to be in.You can find out about this format in the official Discord documentation.
- Parameters:
data (
dict) – The dictionary to convert into an embed.
- copy()¶
Returns a shallow copy of the embed.
Returns an
EmbedProxydenoting the footer contents.See
set_footer()for possible values you can access.If the attribute has no value then
Noneis returned.
Sets the footer for the embed content.
This function returns the class instance to allow for fluent-style chaining.
Clears embed’s footer information.
This function returns the class instance to allow for fluent-style chaining.
Added in version 2.0.
- property image¶
Returns an
EmbedProxydenoting the image contents.Possible attributes you can access are:
urlproxy_urlwidthheight
If the attribute has no value then
Noneis returned.
- 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
Noneremoves the image.- Parameters:
url (Optional[
str]) – The source URL for the image. Only HTTP(S) is supported.
- property thumbnail¶
Returns an
EmbedProxydenoting the thumbnail contents.Possible attributes you can access are:
urlproxy_urlwidthheight
If the attribute has no value then
Noneis returned.
- 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
Noneremoves the thumbnail.- Parameters:
url (Optional[
str]) – The source URL for the thumbnail. Only HTTP(S) is supported.
- property video¶
Returns an
EmbedProxydenoting the video contents.Possible attributes include:
urlfor the video URL.heightfor the video height.widthfor the video width.
If the attribute has no value then
Noneis returned.
- property provider¶
Returns an
EmbedProxydenoting the provider contents.The only attributes that might be accessed are
nameandurl.If the attribute has no value then
Noneis returned.
- property author¶
Returns an
EmbedProxydenoting the author contents.See
set_author()for possible values you can access.If the attribute has no value then
Noneis returned.
- set_author(*, name, url=None, icon_url=None)¶
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.
Added in version 1.4.
- property fields¶
Returns a
listofEmbedProxydenoting the field contents.See
add_field()for possible values you can access.If the attribute has no value then
Noneis returned.- Type:
List[Optional[
EmbedProxy]]
- 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.
Added in version 1.2.
- clear_fields()¶
Removes all fields from this embed.
This function returns the class instance to allow for fluent-style chaining.
- 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.
This function returns the class instance to allow for fluent-style chaining.
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.
- to_dict()¶
Converts this embed object into a dict.
AllowedMentions¶
- class nextcord.AllowedMentions(*, everyone=None, users=None, roles=None, replied_user=None)¶
A class that represents what mentions are allowed in a message.
This class can be set during
Clientinitialisation 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. IfFalsethen users are not mentioned at all. If a list ofabc.Snowflakeis 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. IfFalsethen roles are not mentioned at all. If a list ofabc.Snowflakeis 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.Added in version 1.6.
- Type:
- classmethod all()¶
A factory method that returns a
AllowedMentionswith all fields explicitly set toTrueAdded in version 1.5.
- classmethod none()¶
A factory method that returns a
AllowedMentionswith all fields set toFalseAdded in version 1.5.
MessageReference¶
- class nextcord.MessageReference(*, message_id, channel_id, type=MessageReferenceType.default, guild_id=None, fail_if_not_exists=True)¶
Represents a reference to a
Message.Added in version 1.5.
Changed in version 1.6: This class can now be constructed by users.
- fail_if_not_exists¶
Whether replying to the referenced message should raise
HTTPExceptionif the message no longer exists or Discord could not fetch the message.Added in version 1.7.
- Type:
- resolved¶
The message that this reference resolved to. If this is
Nonethen 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.
Added in version 1.6.
- Type:
Optional[Union[
Message,DeletedReferencedMessage]]
- type¶
The type of reference that the message is. Defaults to a reply.
Added in version 3.0.
- Type:
- classmethod from_message(message, *, type=MessageReferenceType.default, fail_if_not_exists=True)¶
Creates a
MessageReferencefrom an existingMessage.Added in version 1.6.
- Parameters:
message (
Message) – The message to be converted into a reference.type (
MessageReferenceType) –The type of reference that the message is. Defaults to the
replytype if not provided.Added in version 3.0.
fail_if_not_exists (
bool) –Whether replying to the referenced message should raise
HTTPExceptionif the message no longer exists or Discord could not fetch the message.Added in version 1.7.
- Returns:
A reference to the message.
- Return type:
MessageSnapshot¶
- class nextcord.MessageSnapshot(*, data, state)¶
Represents a message reference snapshot.
Added in version 3.0.
- type¶
The type of message.
- Type:
- attachments¶
The attachments the message contains.
- Type:
List[
Attachment]
- timestamp¶
The timestamp when the message was sent.
- Type:
- edited_timestamp¶
The timestamp when the message was last edited. Returns
Noneif it has not been edited.- Type:
Optional[
datetime.datetime]
- flags¶
The message’s flags.
- Type:
- sticker_items¶
A list of stickers packs that the message contains.
- Type:
List[
StickerItem]
PartialMessage¶
- asyncadd_reaction
- asyncclear_reaction
- asyncclear_reactions
- asyncdelete
- asyncedit
- asyncfetch
- asyncpin
- asyncpublish
- asyncremove_reaction
- asyncreply
- defto_reference
- asyncunpin
- class nextcord.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 the following:
Note that this class is trimmed down and has no rich attributes.
Added 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,Thread,DMChannel]
- 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_messagespermission.Changed in version 1.1: Added the new
delaykeyword-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 publish()¶
This function is a coroutine.
Publishes this message to your announcement channel.
You must have the
send_messagespermission to do this.If the message is not your own then the
manage_messagespermission is also 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_messagespermission 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.
Added 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_messagespermission 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.
Added 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_historypermission to use this. If nobody else has reacted to the message using this emoji, theadd_reactionspermission 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.
memberparameter is not you) then themanage_messagespermission is needed.The
memberparameter must represent a member and meet theabc.Snowflakeabc.- 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_messagespermission to use this.Added 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_messagespermission 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, **kwargs)¶
This function is a coroutine.
A shortcut method to
abc.Messageable.send()to reply to theMessage.Added in version 1.6.
- Raises:
HTTPException – Sending the message failed.
Forbidden – You do not have the proper permissions to send the message.
InvalidArgument – The
fileslist is not of the appropriate size or you specified bothfileandfiles.
- Returns:
The message that was sent.
- Return type:
- to_reference(*, fail_if_not_exists=True)¶
Creates a
MessageReferencefrom the current message.Added in version 1.6.
- Parameters:
fail_if_not_exists (
bool) –Whether replying using the message reference should raise
HTTPExceptionif the message no longer exists or Discord could not fetch the message.Added in version 1.7.
- Returns:
The reference to this message.
- Return type:
- property created_at¶
The partial message’s creation time in UTC.
- Type:
- 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(**fields)¶
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.7:
nextcord.Messageis returned instead ofNoneif an edit took place.- Parameters:
content (Optional[
str]) – The new content to replace the message with. Could beNoneto remove the content.embed (Optional[
Embed]) – The new embed to replace the original with. Could beNoneto remove the embed.embeds (List[
Embed]) –The new embeds to replace the original with. Must be a maximum of 10. To remove all embeds
[]should be passed.Added in version 2.0.
suppress (
bool) – Whether to suppress embeds for the message. This removes all the embeds if set toTrue. If set toFalsethis brings the embeds back if they were suppressed. Using this parameter requiresmanage_messages.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_mentionsare used instead.view (Optional[
View]) –The updated view to update this message with. If
Noneis passed then the view is removed.Added in version 2.0.
- Raises:
NotFound – The message was not found.
HTTPException – Editing the message failed.
Forbidden – Tried to suppress a message without permissions or edited a message’s content or embed that isn’t yours.
InvalidArgument – You specified both
embedandembeds.
- Returns:
The message that was edited.
- Return type:
Optional[
Message]
Intents¶
- auto_moderation
- auto_moderation_configuration
- auto_moderation_execution
- bans
- dm_messages
- dm_reactions
- dm_typing
- emojis
- emojis_and_stickers
- guild_messages
- guild_reactions
- guild_typing
- guilds
- integrations
- invites
- members
- message_content
- messages
- moderation
- presences
- reactions
- scheduled_events
- typing
- value
- voice_states
- webhooks
- clsIntents.all
- clsIntents.default
- clsIntents.none
- class nextcord.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
intentskeyword argument ofClient.Added 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 default()¶
A factory method that creates a
Intentswith everything enabled exceptpresences,members, andmessage_content.
- 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:
Guildand 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:
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:
- moderation¶
Whether guild moderation related events are enabled.
This corresponds to the following events:
on_audit_log_entry_create()
This does not correspond to any attributes or classes in the library in terms of cache.
- Type:
- bans¶
Alias of
moderation.Changed in version 2.4: Changed to an alias.
- Type:
- emojis¶
Alias of
emojis_and_stickers.Changed in version 2.0: Changed to an alias.
- Type:
- emojis_and_stickers¶
Whether guild emoji and sticker related events are enabled.
Added in version 2.0.
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:
Note
This intent is required to connect to voice.
- Type:
- presences¶
Whether guild presence related events are enabled.
This corresponds to the following events:
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_messagesanddm_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_messagesfor DMs ormessagesfor 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_messagesfor guilds ormessagesfor 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_reactionsanddm_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_reactionsfor DMs orreactionsfor 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_reactionsfor guilds orreactionsfor 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_typinganddm_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_typingfor DMs ortypingfor 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_typingfor guilds ortypingfor 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 most message content can be accessed.
Without this intent, the following attributes may appear empty - either an empty string or empty array depending on the data type:
A bot will always be able to get these attributes from:
Messages the bot sends
Messages the bot receives in DMs
Messages in which the bot is mentioned
For more information go to the message content intent documentation.
Note
As of September 1, 2022, 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 scheduled events 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:
- auto_moderation_configuration¶
Whether auto moderation configuration 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:
- auto_moderation_execution¶
Whether auto moderation execution 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:
- auto_moderation¶
Whether auto moderation related events are enabled.
This is a shortcut to set or get both
auto_moderation_configurationandauto_moderation_execution.This corresponds to the following events:
This does not correspond to any attributes or classes in the library in terms of cache.
- Type:
MemberCacheFlags¶
- class nextcord.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_flagsparameter inClient.Due to a quirk in how Discord works, in order to ensure proper cleanup of cache resources it is recommended to have
Intents.membersenabled. 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.
Added 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
MemberCacheFlagswith everything enabled.
- classmethod none()¶
A factory method that creates a
MemberCacheFlagswith everything disabled.
- 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
MemberCacheFlagsbased on the currently selectedIntents.- Parameters:
intents (
Intents) – The intents to select from.- Returns:
The resulting member cache flags.
- Return type:
ApplicationFlags¶
- class nextcord.ApplicationFlags(**kwargs)¶
Wraps up the Discord Application flags.
- x == y
Checks if two ApplicationFlags are equal.
- x != y
Checks if two ApplicationFlags 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.
Added in version 2.0.
- value¶
The raw value. You should query flags via the properties rather than using this raw value.
- Type:
- application_auto_moderation_rule_create¶
Returns
Trueif the application uses the Auto Moderation API.Added in version 2.6.
- Type:
- gateway_presence¶
Returns
Trueif the application is verified and is allowed to receive presence information over the gateway.- Type:
- gateway_presence_limited¶
Returns
Trueif the application is allowed to receive limited presence information over the gateway.- Type:
- gateway_guild_members¶
Returns
Trueif the application is verified and is allowed to receive guild members information over the gateway.- Type:
- gateway_guild_members_limited¶
Returns
Trueif the application is allowed to receive limited guild members information over the gateway.- Type:
- verification_pending_guild_limit¶
Returns
Trueif the application is currently pending verification and has hit the guild limit.- Type:
- gateway_message_content¶
Returns
Trueif the application is allowed to receive message content over the gateway.- Type:
- gateway_message_content_limited¶
Returns
Trueif the application is allowed to receive limited message content over the gateway.- Type:
RoleFlags¶
- class nextcord.RoleFlags(**kwargs)¶
Wraps up the Discord Guild Role Flags.
- x == y
Checks if two RoleFlags are equal.
- x != y
Checks if two RoleFlags 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.
Added in version 2.6.
- value¶
The raw value. You should query flags via the properties rather than using this raw value.
- Type:
File¶
- class nextcord.File(fp, filename=None, *, description=None, spoiler=False, force_close=None)¶
A parameter object used for
abc.Messageable.send()for sending file objects.Changed in version 2.5: You can now use nextcord.File as a context manager. This will automatically call
close()when the context manager exits scope. When using the context manager, force_close will default to True.Note
File objects are single use and are not meant to be reused in multiple
abc.Messageable.send()s.- Parameters:
fp (Union[str, bytes, os.PathLike, io.BufferedIOBase]) –
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
openthen the modes ‘rb’ should be used.To pass binary data, consider usage of
io.BytesIO.filename (Optional[
str]) – The filename to display when uploading to Discord. If this is not given then it defaults tofp.nameor iffpis a string then thefilenamewill default to the string given.description (Optional[
str]) – The description for the file. This is used to display alternative text in the Discord client.spoiler (
bool) – Whether the attachment is a spoiler.force_close (
bool) –Whether to forcibly close the bytes used to create the file when
.close()is called. This will also make the file bytes unusable by flushing it from memory after it is sent once. Enable this if you don’t wish to reuse the same bytes. Defaults toTruewhen using context manager.Added in version 2.2.
- fp¶
A file-like object opened in binary mode and read mode. This will be a
io.BufferedIOBaseif an object of typeio.IOBasewas passed, or aio.BufferedReaderif a filename was passed.- Type:
Union[
io.BufferedReader,io.BufferedIOBase]
Colour¶
- clsColour.blue
- clsColour.blurple
- clsColour.brand_green
- clsColour.brand_red
- 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.fuchsia
- clsColour.gold
- clsColour.green
- clsColour.greyple
- clsColour.light_gray
- clsColour.light_grey
- clsColour.lighter_gray
- clsColour.lighter_grey
- clsColour.magenta
- clsColour.og_blurple
- clsColour.orange
- clsColour.purple
- clsColour.random
- clsColour.red
- clsColour.teal
- clsColour.yellow
- defto_rgb
- class nextcord.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.
- int(x)
Returns the raw colour value.
- classmethod random(*, seed=None)¶
A factory method that returns a
Colourwith a random hue.Note
The random algorithm works by choosing a colour with a random hue but with maxed out saturation and value.
Added in version 1.6.
- classmethod brand_green()¶
A factory method that returns a
Colourwith a value of0x57F287.Added in version 2.0.
- classmethod brand_red()¶
A factory method that returns a
Colourwith a value of0xED4245.Added in version 2.0.
- classmethod dark_theme()¶
A factory method that returns a
Colourwith a value of0x313338. This will appear transparent on Discord’s dark theme.Added in version 1.5.
Changed in version 2.5: Colour was replaced by the new dark theme colour on the UI.
BaseActivity¶
- class nextcord.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.
Added in version 1.3.
- property created_at¶
When the user started doing this activity in UTC.
Added in version 1.3.
- Type:
Optional[
datetime.datetime]
Activity¶
- class nextcord.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:
- type¶
The type of activity currently being done.
- Type:
- 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:
- buttons¶
A list of dictionaries representing custom buttons shown in a rich presence. Each dictionary contains the following keys:
label: A string representing the text shown on the button.url: A string representing the URL opened upon clicking the button.
Added in version 2.0.
- Type:
List[
dict]
- 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]
Game¶
- class nextcord.Game(name, **extra)¶
A slimmed down version of
Activitythat 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.
- 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 nextcord.Streaming(*, name, url, **extra)¶
A slimmed down version of
Activitythat 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.
- platform¶
Where the user is streaming from (ie. YouTube, Twitch).
Added 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_imagekey of theStreaming.assetsdictionary if it starts withtwitch:. Typically set by the Discord client.- Type:
Optional[
str]
CustomActivity¶
- class nextcord.CustomActivity(name, *, _connection_state=None, 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.
Added in version 1.3.
- emoji¶
The emoji to pass to the activity, if any.
- Type:
Optional[
PartialEmoji]
- state¶
The custom status text.
namemust equal “Custom Status” for this to work.Changed in version 2.6: This falls back to
nameif not provided.- Type:
Optional[
str]
- 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_events
- create_expressions
- create_instant_invite
- create_private_threads
- create_public_threads
- deafen_members
- embed_links
- external_emojis
- external_stickers
- kick_members
- manage_channels
- manage_emojis
- manage_emojis_and_stickers
- manage_events
- manage_guild
- manage_messages
- manage_nicknames
- manage_permissions
- manage_roles
- 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_tts_messages
- send_voice_messages
- speak
- start_embedded_activities
- stream
- 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 nextcord.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
Permissionssimilar 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_subset(other)¶
Returns
Trueif self has the same or fewer permissions as other.
- is_superset(other)¶
Returns
Trueif self has the same or more permissions as other.
- is_strict_subset(other)¶
Returns
Trueif the permissions on other are a strict subset of those on self.
- is_strict_superset(other)¶
Returns
Trueif the permissions on other are a strict superset of those on self.
- classmethod none()¶
A factory method that creates a
Permissionswith all permissions set toFalse.
- classmethod all()¶
A factory method that creates a
Permissionswith all permissions set toTrue.
- classmethod all_channel()¶
A
Permissionswith all channel-specific permissions set toTrueand the guild-specific ones set toFalse. The guild-specific permissions are currently:Changed in version 1.7: Added
stream,priority_speakeranduse_slash_commandspermissions.Changed in version 2.0: Added
create_public_threads,create_private_threads,manage_threads,use_external_stickers,send_messages_in_threadsandrequest_to_speakpermissions.Changed in version 3.0: Added
start_embedded_activities,create_expressionspermissions.
- classmethod general()¶
A factory method that creates a
Permissionswith all “General” permissions from the official Discord UI set toTrue.Changed in version 1.7: Permission
read_messagesis now included in the general permissions, but permissionsadministrator,create_instant_invite,kick_members,ban_members,change_nicknameandmanage_nicknamesare no longer part of the general permissions.Changed in version 3.0: Added
create_expressionspermission.
- classmethod membership()¶
A factory method that creates a
Permissionswith all “Membership” permissions from the official Discord UI set toTrue.Added in version 1.7.
- classmethod text()¶
A factory method that creates a
Permissionswith all “Text” permissions from the official Discord UI set toTrue.Changed in version 1.7: Permission
read_messagesis no longer part of the text permissions. Addeduse_slash_commandspermission.Changed in version 2.0: Added
create_public_threads,create_private_threads,manage_threads,send_messages_in_threadsanduse_external_stickerspermissions.
- classmethod voice()¶
A factory method that creates a
Permissionswith all “Voice” permissions from the official Discord UI set toTrue.
- classmethod stage()¶
A factory method that creates a
Permissionswith all “Stage Channel” permissions from the official Discord UI set toTrue.Added in version 1.7.
- classmethod stage_moderator()¶
A factory method that creates a
Permissionswith all “Stage Moderator” permissions from the official Discord UI set toTrue.Added in version 1.7.
- classmethod advanced()¶
A factory method that creates a
Permissionswith all “Advanced” permissions from the official Discord UI set toTrue.Added 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
Trueif a user is an administrator. This role overrides all other permissions.This also bypasses all channel-specific overrides.
- Type:
- manage_channels¶
Returns
Trueif a user can edit, delete, or create channels in the guild.This also corresponds to the “Manage Channel” channel-specific override.
- Type:
- read_messages¶
Returns
Trueif a user can read messages from all or specific text channels.- Type:
- view_channel¶
An alias for
read_messages.Added in version 1.3.
- Type:
- send_messages¶
Returns
Trueif a user can send messages from all or specific text channels.This falls under
Create Postson the UI specifically for Forum Channels.- Type:
- send_tts_messages¶
Returns
Trueif a user can send TTS messages from all or specific text channels.- Type:
- manage_messages¶
Returns
Trueif 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:
- embed_links¶
Returns
Trueif a user’s messages will automatically be embedded by Discord.- Type:
- read_message_history¶
Returns
Trueif a user can read a text channel’s previous messages.- Type:
- mention_everyone¶
Returns
Trueif a user’s @everyone or @here will mention everyone in the text channel.- Type:
- use_external_emojis¶
An alias for
external_emojis.Added in version 1.3.
- Type:
- view_guild_insights¶
Returns
Trueif a user can view the guild’s insights.Added in version 1.3.
- Type:
- manage_roles¶
Returns
Trueif 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.Added in version 1.3.
- Type:
- manage_emojis_and_stickers¶
An alias for
manage_emojis.Added in version 2.0.
- Type:
- request_to_speak¶
Returns
Trueif a user can request to speak in a stage channel.Added in version 1.7.
- Type:
- create_public_threads¶
Returns
Trueif a user can create public threads.Added in version 2.0.
- Type:
- create_private_threads¶
Returns
Trueif a user can create private threads.Added in version 2.0.
- Type:
- external_stickers¶
Returns
Trueif a user can use stickers from other guilds.Added in version 2.0.
- Type:
- use_external_stickers¶
An alias for
external_stickers.Added in version 2.0.
- Type:
- send_messages_in_threads¶
Returns
Trueif a user can send messages in threads.This falls under
Send Messages in Postson the UI specifically for Forum channels.Added in version 2.0.
- Type:
- start_embedded_activities¶
Returns
Trueif a user can launch activities in a voice channel.Added in version 2.0.
- Type:
- moderate_members¶
Returns
Trueif a user can moderate members (add timeouts).Referred to as
Timeout Membersin the discord client.Added in version 2.0.
- Type:
- create_expressions¶
Returns
Trueif a user can create expressions.This includes creating emojis, stickers, and soundboard sounds.
Added in version 3.0.
- Type:
PermissionOverwrite¶
- clsPermissionOverwrite.from_pair
- defis_empty
- defpair
- defupdate
- class nextcord.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 toNoneand notFalse. Setting a value toFalseis explicitly denying that permission, while setting a value toTrueis explicitly allowing that permission.The values supported by this are the same as
Permissionswith 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
TrueorFalse.- 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 nextcord.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:
- join_notifications¶
Returns
Trueif the system channel is used for member join notifications.- Type:
Returns
Trueif the system channel is used for “Nitro boosting” notifications.- Type:
- guild_reminder_notifications¶
Returns
Trueif the system channel is used for server setup helpful tips notifications.Added in version 2.0.
- Type:
- join_notification_replies¶
Returns
Trueif the button to reply with a sticker to member join notifications is shown.Added in version 2.0.
- Type:
- role_subscription_purchase_notifications¶
Returns
Trueif the system channel is used for role subscription purchase notifications.Added in version 3.2.
- Type:
MessageFlags¶
- class nextcord.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.
Added 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
Trueif the source message for this crosspost has been deleted.- Type:
- urgent¶
Returns
Trueif the source message is an urgent message.An urgent message is one sent by Discord Trust and Safety.
- Type:
- has_thread¶
Returns
Trueif the source message is associated with a thread.Added in version 2.0.
- Type:
- loading¶
Returns
Trueif the source message is loading.This is represented in the UI as “bot is thinking…”.
Added in version 2.6.
- Type:
- failed_to_mention_roles¶
Returns
Trueif the message failed to mention some roles in a thread.This means that those members were not added.
Added in version 2.6.
- Type:
- suppress_notifications¶
Returns
Trueif the message does not trigger notifications.These are sent via @silent message prefixes in the UI.
Added in version 2.6.
- Type:
PublicUserFlags¶
- defall
- class nextcord.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.
Added 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.Added in version 1.5.
- Type:
- discord_certified_moderator¶
Returns
Trueif the user is a Discord Moderator Programs Alumni.Formally known as Discord Certified Moderator.
Added in version 2.0.
- Type:
MemberFlags¶
- class nextcord.MemberFlags¶
Wraps up the Discord Guild Member flags
Added in version 2.6.
- x == y
Checks if two MemberFlags are equal.
- x != y
Checks if two MemberFlags are not equal.
- hash(x)
Returns 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. You should query flags via the properties rather than using this raw value.
- Type:
- bypasses_verification¶
Returns
Trueif the member can bypass the guild verification requirements.- Type:
ChannelFlags¶
- class nextcord.ChannelFlags¶
Wraps up a Discord 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 channel flags easily.To construct an object you can pass keyword arguments denoting the flags to enable or disable.
Added in version 2.1.
- 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:
AutoModerationTriggerMetadata¶
- class nextcord.AutoModerationTriggerMetadata(*, keyword_filter=None, regex_patterns=None, presets=None, allow_list=None, mention_total_limit=None, mention_raid_protection_enabled=None)¶
Represents data about an auto moderation trigger rule.
Added in version 2.1.
- keyword_filter¶
A list of substrings which will be searched for in content.
Note
This is
Noneand cannot be provided if the trigger type of the rule is notAutoModerationTriggerType.keywordorAutoModerationTriggerType.member_profile.- Type:
List[
str]
- regex_patterns¶
A list of regex patterns which will be matched with content. Can only be up to 10 patterns.
Added in version 2.4.
Note
This is
Noneand cannot be provided if the trigger type of the rule is notAutoModerationTriggerType.keywordorAutoModerationTriggerType.member_profile.Warning
The flavor of regex used is Rust flavor and has no guarantees of working with the
remodule. Each regex pattern must be 75 characters or less.- Type:
Optional[List[
str]]
- presets¶
A list of Discord pre-defined wordsets which will be searched for in content.
Note
This is
Noneand cannot be provided if the trigger type of the rule is notAutoModerationTriggerType.keyword_preset.- Type:
List[
KeywordPresetType]
- allow_list¶
A list of exempt strings that will not trigger the preset type.
Note
This is
Noneand cannot be provided if the trigger type of the rule is notAutoModerationTriggerType.keyword_presetorAutoModerationTriggerType.member_profile.Warning
Wildcard syntax (*) is not supported here.
- Type:
List[
str]
- mention_total_limit¶
The maximum amount of mentions allowed in a messsage.
Added in version 2.3.
Note
This is
Noneand cannot be provided if the trigger type of this rule is notAutoModerationTriggerType.mention_spam.- Type:
Optional[
int]
- mention_raid_protection_enabled¶
Whether to automatically detect mention raids.
Added in version 2.6.
Note
This is
Noneand cannot be provided if the trigger type of this rule is notAutoModerationTriggerType.mention_spam.- Type:
Optional[
bool]
AutoModerationActionMetadata¶
- class nextcord.AutoModerationActionMetadata(*, channel=None, duration_seconds=None, custom_message=None)¶
Represents additional data that is used when an action is executed.
Added in version 2.1.
- channel¶
The channel to which message content should be logged.
Note
This is
Noneand cannot be provided if the action type of the rule is notAutoModerationActionType.send_alert_message.- Type:
Optional[
abc.Snowflake]
- duration_seconds¶
The duration of the timeout in seconds.
Note
This is
Noneand cannot be provided if the action type of the rule is notAutoModerationActionType.timeout.Note
The maximum value that can be used is
2419200seconds (4 weeks)- Type:
Optional[
int]
- custom_message¶
The message explaining why the message has been blocked.
Added in version 3.0.
Note
This is
Noneand cannot be provided if the action type of the rule is notAutoModerationActionType.block_message.Note
This message cannot exceed 150 characters.
- Type:
Optional[
str]
AutoModerationAction¶
- class nextcord.AutoModerationAction(*, type, metadata=None)¶
Represents an auto moderation action that will execute whenever a rule is triggered.
Added in version 2.1.
- Parameters:
type (
AutoModerationActionType) – The type to use for this action.metadata (
AutoModerationActionMetadata) – The additional data to use during execution of this action.
- type¶
The type of this action.
- Type:
- metadata¶
The additional metadata needed during execution for this specific action type.
ForumTag¶
- class nextcord.ForumTag(*, id=None, name, moderated=False, emoji=None)¶
Represents a tag in a forum channel that can be used to filter posts.
Added in version 2.4.
- moderated¶
Whether this tag can only be added to or removed from threads by a member with the
manage_threadspermission.- Type:
- emoji¶
The emoji that represents this tag.
- Type:
Optional[
PartialEmoji]
- Parameters:
id (
int) –The ID of the tag.
Warning
This should not really be passed when constructing this manually. This is only documented here for the sake of completeness.
name (
str) – The name of the tag.moderated (
bool) – Whether this tag can only be added to or removed from threads by a member with themanage_threadspermission.emoji (Optional[
PartialEmoji]) – The emoji that represents this tag.
RoleConnectionMetadata¶
Bot UI Kit¶
The library has helpers to help create component-based UIs.
View¶
- clsView.from_message
- defadd_item
- defclear_items
- asyncinteraction_check
- defis_dispatching
- defis_finished
- defis_persistent
- asyncon_error
- asyncon_timeout
- defremove_item
- defstop
- asyncwait
- class nextcord.ui.View(*, timeout=180.0, auto_defer=True, prevent_update=True)¶
Represents a UI view.
This object must be inherited to create a UI within Discord.
Added in version 2.0.
- Parameters:
timeout (Optional[
float]) – Timeout in seconds from last interaction with the UI before no longer accepting input. IfNonethen there is no timeout.auto_defer (
bool= True) – Whether or not to automatically defer the component interaction when the callback completes without responding to the interaction. Set this toFalseif you want to handle view interactions outside of the callback.
- timeout¶
Timeout from last interaction with the UI before no longer accepting input. If
Nonethen there is no timeout.- Type:
Optional[
float]
- auto_defer¶
Whether or not to automatically defer the component interaction when the callback completes without responding to the interaction. Set this to
Falseif you want to handle view interactions outside of the callback.- Type:
bool= True
- prevent_update¶
This option only affects persistent views. Whether or not to store the view separately for each message. The stored views are not automatically cleared, and can cause issues if you run the bot continously for long periods of time if views are not properly stopped. Setting this to False will force the client to find a persistent view added with Bot.add_view and not store the view separately.
- Type:
bool= True
- classmethod from_message(message, /, *, timeout=180.0)¶
Converts a message’s components into a
View.The
Message.componentsof a message are read-only and separate types from those in thenextcord.uinamespace. In order to modify and edit message components they must be converted into aViewfirst.- Parameters:
message (
nextcord.Message) – The message with components to convert into a view.timeout (Optional[
float]) – The timeout of the converted view.
- Returns:
The converted view. This always returns a
Viewand not one of its subclasses.- Return type:
- add_item(item)¶
Adds an item to the view.
- Parameters:
item (
Item) – The item to add to the view.- Raises:
ValueError – Maximum number of children has been exceeded (25) or the row the item is trying to be added to is full.
- remove_item(item)¶
Removes an item from the view.
- Parameters:
item (
Item) – The item to remove from the view.
- clear_items()¶
Removes all items from the view.
- await interaction_check(interaction)¶
This function is a coroutine.
A callback that is called when an interaction happens within the view that checks whether the view should process item callbacks for the interaction.
This is useful to override if, for example, you want to ensure that the interaction author is a given user.
The default implementation of this returns
True.Note
If an exception occurs within the body then the check is considered a failure and
on_error()is called.- Parameters:
interaction (
Interaction) – The interaction that occurred.- Returns:
Whether the view children’s callbacks should be called.
- Return type:
- await on_timeout()¶
This function is a coroutine.
A callback that is called when a view’s timeout elapses without being explicitly stopped.
- await on_error(error, item, interaction)¶
This function is a coroutine.
A callback that is called when an item’s callback or
interaction_check()fails with an error.The default implementation prints the traceback to stderr.
- Parameters:
error (
Exception) – The exception that was raised.item (
Item) – The item that failed the dispatch.interaction (
Interaction) – The interaction that led to the failure.
- stop()¶
Stops listening to interaction events from this view.
This operation cannot be undone.
Modal¶
- defadd_item
- asynccallback
- defclear_items
- defis_dispatching
- defis_finished
- defis_persistent
- asyncon_error
- asyncon_timeout
- defremove_item
- defstop
- asyncwait
- class nextcord.ui.Modal(title, *, timeout=None, custom_id=..., auto_defer=True)¶
Represents a Discord modal popup.
This object must be inherited to create a modal within Discord.
Added in version 2.0.
- Parameters:
title (
str) – The title of the modal.timeout (Optional[
float] = None) – Timeout in seconds from last interaction with the UI before no longer accepting input. IfNonethen there is no timeout.custom_id (
str= MISSING) – The ID of the modal that gets received during an interaction. If thecustom_idis MISSING, then a randomcustom_idis set.auto_defer (
bool= True) – Whether or not to automatically defer the modal when the callback completes without responding to the interaction. Set this toFalseif you want to handle the modal interaction outside of the callback.
- timeout¶
Timeout from last interaction with the UI before no longer accepting input. If
Nonethen there is no timeout.- Type:
Optional[
float]
- auto_defer¶
Whether or not to automatically defer the modal when the callback completes without responding to the interaction. Set this to
Falseif you want to handle the modal interaction outside of the callback.- Type:
bool= True
- add_item(item)¶
Adds an item to the modal.
- Parameters:
item (
Item) –The item to add to the modal.
Note
The only items that are currently supported are
TextInputs.- Raises:
ValueError – The row the item is trying to be added to is full.
- remove_item(item)¶
Removes an item from the modal.
- Parameters:
item (
Item) – The item to remove from the modal.
- clear_items()¶
Removes all items from the modal.
- await callback(interaction)¶
This function is a coroutine.
The callback that is called when the user press the submit button.
The default implementation does nothing and the user sees an error message on their screen, so you need to overwrite this function.
- Parameters:
interaction (
Interaction) – The interaction fired by the user.
- await on_timeout()¶
This function is a coroutine.
A callback that is called when a modal’s timeout elapses without being explicitly stopped.
- await on_error(error, interaction)¶
This function is a coroutine.
A callback that is called when an item’s callback or
interaction_check()fails with an error.The default implementation prints the traceback to stderr.
- Parameters:
error (
Exception) – The exception that was raised.item (
Item) – The item that failed the dispatch.interaction (
Interaction) – The interaction that led to the failure.
- stop()¶
Stops listening to interaction events from this modal.
This operation cannot be undone.
Item¶
- class nextcord.ui.Item¶
Represents the base UI item that all UI components inherit from.
The current UI items supported are:
Added in version 2.0.
- await callback(interaction)¶
This function is a coroutine.
The callback associated with this UI item.
This can be overridden by subclasses.
- Parameters:
interaction (
Interaction) – The interaction that triggered this UI item.
TextInput¶
- asynccallback
- class nextcord.ui.TextInput(label, *, style=TextInputStyle.short, custom_id=..., row=None, min_length=0, max_length=4000, required=None, default_value=None, placeholder=None)¶
Represent a UI text input.
Added in version 2.0.
- Parameters:
label (
str) – The label of the text inputstyle (
TextInputStyle) – The style of the text input. By default, the style isTextInputStyle.short, a one line input, but you can useTextInputStyle.paragraph, a multi line input.custom_id (Optional[
str]) – The ID of the text input that get received during an interaction.row (Optional[
int]) – The relative row this text input belongs to. A Discord component can only have 5 rows. By default, items are arranged automatically into those 5 rows. If you’d like to control the relative positioning of the row then passing an index is advised. For example, row=1 will show up before row=2. Defaults toNone, which is automatic ordering. The row number must be between 0 and 4 (i.e. zero indexed).min_length (Optional[
int]) – The minimal length of the user’s inputmax_length (Optional[
int]) – The maximal length of the user’s inputrequired (Optional[
bool]) – IfTrue, the user cannot send the form without filling this field.default_value (Optional[
str]) – The value already in the input when the user open the form.placeholder (Optional[
str]) – The text shown to the user when the text input is empty.
- property style¶
The style of the text input.
- Type:
- property custom_id¶
The ID of the text input that gets received during an interaction.
- Type:
Optional[
str]
- property default_value¶
The value already in the text input when the user open the form.
- Type:
Optional[
str]
- property value¶
The value sent by the user. This field is updated when an interaction is received.
TextInput.valueisNonewhen no interaction where received.- Type:
Optional[
str]
- await callback(interaction)¶
This function is a coroutine.
The callback associated with this UI item.
This can be overridden by subclasses.
- Parameters:
interaction (
Interaction) – The interaction that triggered this UI item.
StringSelect¶
- defadd_option
- defappend_option
- asynccallback
- class nextcord.ui.StringSelect(*, custom_id=..., placeholder=None, min_values=1, max_values=1, options=..., disabled=False, row=None)¶
Represents a UI string select menu.
This is usually represented as a drop down menu.
In order to get the selected items that the user has chosen, use
StringSelect.values.There is an alias for this class called
Select.Added in version 2.0.
- Parameters:
custom_id (
str) – The ID of the select menu that gets received during an interaction. If not given then one is generated for you.placeholder (Optional[
str]) – The placeholder text that is shown if nothing is selected, if any.min_values (
int) – The minimum number of items that must be chosen for this select menu. Defaults to 1 and must be between 1 and 25.max_values (
int) – The maximum number of items that must be chosen for this select menu. Defaults to 1 and must be between 1 and 25.options (List[
SelectOption]) – A list of options that can be selected in this menu.disabled (
bool) – Whether the select is disabled or not.row (Optional[
int]) – The relative row this select menu belongs to. A Discord component can only have 5 rows. By default, items are arranged automatically into those 5 rows. If you’d like to control the relative positioning of the row then passing an index is advised. For example, row=1 will show up before row=2. Defaults toNone, which is automatic ordering. The row number must be between 0 and 4 (i.e. zero indexed).
- property options¶
A list of options that can be selected in this menu.
- Type:
List[
SelectOption]
- add_option(*, label, value=..., description=None, emoji=None, default=False)¶
Adds an option to the select menu.
To append a pre-existing
SelectOptionuse theappend_option()method instead.- Parameters:
label (
str) – The label of the option. This is displayed to users. Can only be up to 100 characters.value (
str) – The value of the option. This is not displayed to users. If not given, defaults to the label. Can only be up to 100 characters.description (Optional[
str]) – An additional description of the option, if any. Can only be up to 100 characters.emoji (Optional[Union[
str,Emoji,PartialEmoji]]) – The emoji of the option, if available. This can either be a string representing the custom or unicode emoji or an instance ofPartialEmojiorEmoji.default (
bool) – Whether this option is selected by default.
- Raises:
ValueError – The number of options exceeds 25.
- append_option(option)¶
Appends an option to the select menu.
- Parameters:
option (
SelectOption) – The option to append to the select menu.- Raises:
ValueError – The number of options exceeds 25.
- await callback(interaction)¶
This function is a coroutine.
The callback associated with this UI item.
This can be overridden by subclasses.
- Parameters:
interaction (
Interaction) – The interaction that triggered this UI item.
- property max_values¶
The maximum number of items that must be chosen for this select menu.
- Type:
- property min_values¶
The minimum number of items that must be chosen for this select menu.
- Type:
- nextcord.ui.string_select(*, placeholder=None, custom_id=..., min_values=1, max_values=1, options=..., disabled=False, row=None)¶
A decorator that attaches a string select menu to a component.
There is an alias for this function called
select.The function being decorated should have three parameters,
selfrepresenting theui.View, theui.StringSelectbeing pressed and theInteractionyou receive.In order to get the selected items that the user has chosen within the callback use
StringSelect.values.- Parameters:
placeholder (Optional[
str]) – The placeholder text that is shown if nothing is selected, if any.custom_id (
str) – The ID of the select menu that gets received during an interaction. It is recommended not to set this parameter to prevent conflicts.row (Optional[
int]) – The relative row this select menu belongs to. A Discord component can only have 5 rows. By default, items are arranged automatically into those 5 rows. If you’d like to control the relative positioning of the row then passing an index is advised. For example, row=1 will show up before row=2. Defaults toNone, which is automatic ordering. The row number must be between 0 and 4 (i.e. zero indexed).min_values (
int) – The minimum number of items that must be chosen for this select menu. Defaults to 1 and must be between 1 and 25.max_values (
int) – The maximum number of items that must be chosen for this select menu. Defaults to 1 and must be between 1 and 25.options (List[
SelectOption]) – A list of options that can be selected in this menu.disabled (
bool) – Whether the select is disabled or not. Defaults toFalse.
- nextcord.ui.Select¶
alias of
StringSelect
- nextcord.ui.select(*, placeholder=None, custom_id=..., min_values=1, max_values=1, options=..., disabled=False, row=None)¶
alias of
string_select()
UserSelect¶
- asynccallback
- class nextcord.ui.UserSelect(*, custom_id=None, placeholder=None, min_values=1, max_values=1, disabled=False, row=None)¶
Represents a UI user select menu.
This is usually represented as a drop down menu.
In order to get the selected items that the user has chosen, use
UserSelect.values.Added in version 2.3.
- Parameters:
custom_id (
str) – The ID of the select menu that gets received during an interaction. If not given then one is generated for you.placeholder (Optional[
str]) – The placeholder text that is shown if nothing is selected, if any.min_values (
int) – The minimum number of items that must be chosen for this select menu. Defaults to 1 and must be between 1 and 25.max_values (
int) – The maximum number of items that must be chosen for this select menu. Defaults to 1 and must be between 1 and 25.disabled (
bool) – Whether the select is disabled or not. Defaults toFalse.row (Optional[
int]) – The relative row this select menu belongs to. A Discord component can only have 5 rows. By default, items are arranged automatically into those 5 rows. If you’d like to control the relative positioning of the row then passing an index is advised. For example, row=1 will show up before row=2. Defaults toNone, which is automatic ordering. The row number must be between 0 and 4 (i.e. zero indexed).
- property values¶
A list of Union[
Member,nextcord.User] that have been selected by the user.- Type:
- await callback(interaction)¶
This function is a coroutine.
The callback associated with this UI item.
This can be overridden by subclasses.
- Parameters:
interaction (
Interaction) – The interaction that triggered this UI item.
- property max_values¶
The maximum number of items that must be chosen for this select menu.
- Type:
- property min_values¶
The minimum number of items that must be chosen for this select menu.
- Type:
- nextcord.ui.user_select(*, placeholder=None, custom_id=..., min_values=1, max_values=1, disabled=False, row=None)¶
A decorator that attaches a user select menu to a component.
The function being decorated should have three parameters,
selfrepresenting theui.View, theui.UserSelectbeing pressed and theInteractionyou receive.In order to get the selected items that the user has chosen within the callback use
UserSelect.values.Added in version 2.3.
- Parameters:
placeholder (Optional[
str]) – The placeholder text that is shown if nothing is selected, if any.custom_id (
str) – The ID of the select menu that gets received during an interaction. It is recommended not to set this parameter to prevent conflicts.row (Optional[
int]) – The relative row this select menu belongs to. A Discord component can only have 5 rows. By default, items are arranged automatically into those 5 rows. If you’d like to control the relative positioning of the row then passing an index is advised. For example, row=1 will show up before row=2. Defaults toNone, which is automatic ordering. The row number must be between 0 and 4 (i.e. zero indexed).min_values (
int) – The minimum number of items that must be chosen for this select menu. Defaults to 1 and must be between 1 and 25.max_values (
int) – The maximum number of items that must be chosen for this select menu. Defaults to 1 and must be between 1 and 25.disabled (
bool) – Whether the select is disabled or not. Defaults toFalse.
- class nextcord.ui.UserSelectValues¶
Represents the values of a
ui.UserSelect.- property users¶
A list of users that were selected.
- Type:
List[
nextcord.User]
RoleSelect¶
- asynccallback
- class nextcord.ui.RoleSelect(*, custom_id=None, placeholder=None, min_values=1, max_values=1, disabled=False, row=None)¶
Represents a UI role select menu.
This is usually represented as a drop down menu.
In order to get the selected items that the user has chosen, use
RoleSelect.values.Added in version 2.3.
- Parameters:
custom_id (
str) – The ID of the select menu that gets received during an interaction. If not given then one is generated for you.placeholder (Optional[
str]) – The placeholder text that is shown if nothing is selected, if any.min_values (
int) – The minimum number of items that must be chosen for this select menu. Defaults to 1 and must be between 1 and 25.max_values (
int) – The maximum number of items that must be chosen for this select menu. Defaults to 1 and must be between 1 and 25.disabled (
bool) – Whether the select is disabled or not. Defaults toFalse.row (Optional[
int]) – The relative row this select menu belongs to. A Discord component can only have 5 rows. By default, items are arranged automatically into those 5 rows. If you’d like to control the relative positioning of the row then passing an index is advised. For example, row=1 will show up before row=2. Defaults toNone, which is automatic ordering. The row number must be between 0 and 4 (i.e. zero indexed).
- await callback(interaction)¶
This function is a coroutine.
The callback associated with this UI item.
This can be overridden by subclasses.
- Parameters:
interaction (
Interaction) – The interaction that triggered this UI item.
- property max_values¶
The maximum number of items that must be chosen for this select menu.
- Type:
- property min_values¶
The minimum number of items that must be chosen for this select menu.
- Type:
- nextcord.ui.role_select(*, placeholder=None, custom_id=..., min_values=1, max_values=1, disabled=False, row=None)¶
A decorator that attaches a role select menu to a component.
The function being decorated should have three parameters,
selfrepresenting theui.View, theui.RoleSelectbeing pressed and theInteractionyou receive.In order to get the selected items that the user has chosen within the callback use
RoleSelect.values.Added in version 2.3.
- Parameters:
placeholder (Optional[
str]) – The placeholder text that is shown if nothing is selected, if any.custom_id (
str) – The ID of the select menu that gets received during an interaction. It is recommended not to set this parameter to prevent conflicts.row (Optional[
int]) – The relative row this select menu belongs to. A Discord component can only have 5 rows. By default, items are arranged automatically into those 5 rows. If you’d like to control the relative positioning of the row then passing an index is advised. For example, row=1 will show up before row=2. Defaults toNone, which is automatic ordering. The row number must be between 0 and 4 (i.e. zero indexed).min_values (
int) – The minimum number of items that must be chosen for this select menu. Defaults to 1 and must be between 1 and 25.max_values (
int) – The maximum number of items that must be chosen for this select menu. Defaults to 1 and must be between 1 and 25.disabled (
bool) – Whether the select is disabled or not. Defaults toFalse.
- class nextcord.ui.RoleSelectValues¶
Represents the values of a
ui.RoleSelect.
MentionableSelect¶
- asynccallback
- class nextcord.ui.MentionableSelect(*, custom_id=None, placeholder=None, min_values=1, max_values=1, disabled=False, row=None)¶
Represents a UI mentionable select menu.
This is usually represented as a drop down menu.
In order to get the selected items that the user has chosen, use
MentionableSelect.values.Added in version 2.3.
- Parameters:
custom_id (
str) – The ID of the select menu that gets received during an interaction. If not given then one is generated for you.placeholder (Optional[
str]) – The placeholder text that is shown if nothing is selected, if any.min_values (
int) – The minimum number of items that must be chosen for this select menu. Defaults to 1 and must be between 1 and 25.max_values (
int) – The maximum number of items that must be chosen for this select menu. Defaults to 1 and must be between 1 and 25.disabled (
bool) – Whether the select is disabled or not. Defaults toFalse.row (Optional[
int]) – The relative row this select menu belongs to. A Discord component can only have 5 rows. By default, items are arranged automatically into those 5 rows. If you’d like to control the relative positioning of the row then passing an index is advised. For example, row=1 will show up before row=2. Defaults toNone, which is automatic ordering. The row number must be between 0 and 4 (i.e. zero indexed).
- property values¶
A list of Union[
Member,nextcord.User,Role] that have been selected by the user.
- await callback(interaction)¶
This function is a coroutine.
The callback associated with this UI item.
This can be overridden by subclasses.
- Parameters:
interaction (
Interaction) – The interaction that triggered this UI item.
- property max_values¶
The maximum number of items that must be chosen for this select menu.
- Type:
- property min_values¶
The minimum number of items that must be chosen for this select menu.
- Type:
- nextcord.ui.mentionable_select(*, placeholder=None, custom_id=..., min_values=1, max_values=1, disabled=False, row=None)¶
A decorator that attaches a mentionable select menu to a component.
The function being decorated should have three parameters,
selfrepresenting theui.View, theui.MentionableSelectbeing pressed and theInteractionyou receive.In order to get the selected items that the user has chosen within the callback use
MentionableSelect.values.Added in version 2.3.
- Parameters:
placeholder (Optional[
str]) – The placeholder text that is shown if nothing is selected, if any.custom_id (
str) – The ID of the select menu that gets received during an interaction. It is recommended not to set this parameter to prevent conflicts.row (Optional[
int]) – The relative row this select menu belongs to. A Discord component can only have 5 rows. By default, items are arranged automatically into those 5 rows. If you’d like to control the relative positioning of the row then passing an index is advised. For example, row=1 will show up before row=2. Defaults toNone, which is automatic ordering. The row number must be between 0 and 4 (i.e. zero indexed).min_values (
int) – The minimum number of items that must be chosen for this select menu. Defaults to 1 and must be between 1 and 25.max_values (
int) – The maximum number of items that must be chosen for this select menu. Defaults to 1 and must be between 1 and 25.disabled (
bool) – Whether the select is disabled or not. Defaults toFalse.
- class nextcord.ui.MentionableSelectValues¶
Represents the values of a
ui.MentionableSelect.- property users¶
A list of users that were selected.
- Type:
List[
nextcord.User]
ChannelSelect¶
- asynccallback
- class nextcord.ui.ChannelSelect(*, custom_id=None, placeholder=None, min_values=1, max_values=1, disabled=False, row=None, channel_types=...)¶
Represents a UI channel select menu.
This is usually represented as a drop down menu.
In order to get the selected items that the user has chosen, use
ChannelSelect.values.Added in version 2.3.
- Parameters:
custom_id (
str) – The ID of the select menu that gets received during an interaction. If not given then one is generated for you.placeholder (Optional[
str]) – The placeholder text that is shown if nothing is selected, if any.min_values (
int) – The minimum number of items that must be chosen for this select menu. Defaults to 1 and must be between 1 and 25.max_values (
int) – The maximum number of items that must be chosen for this select menu. Defaults to 1 and must be between 1 and 25.disabled (
bool) – Whether the select is disabled or not. Defaults toFalse.row (Optional[
int]) – The relative row this select menu belongs to. A Discord component can only have 5 rows. By default, items are arranged automatically into those 5 rows. If you’d like to control the relative positioning of the row then passing an index is advised. For example, row=1 will show up before row=2. Defaults toNone, which is automatic ordering. The row number must be between 0 and 4 (i.e. zero indexed).channel_types (List[
ChannelType]) – The types of channels that can be selected. If not given, all channel types are allowed.
- property values¶
A list of resolved
abc.GuildChannelthat have been selected by the user.- Type:
- await callback(interaction)¶
This function is a coroutine.
The callback associated with this UI item.
This can be overridden by subclasses.
- Parameters:
interaction (
Interaction) – The interaction that triggered this UI item.
- property max_values¶
The maximum number of items that must be chosen for this select menu.
- Type:
- property min_values¶
The minimum number of items that must be chosen for this select menu.
- Type:
- nextcord.ui.channel_select(*, placeholder=None, custom_id=..., min_values=1, max_values=1, disabled=False, row=None, channel_types=...)¶
A decorator that attaches a channel select menu to a component.
The function being decorated should have three parameters,
selfrepresenting theui.View, theui.ChannelSelectbeing pressed and theInteractionyou receive.In order to get the selected items that the user has chosen within the callback use
ChannelSelect.values.Added in version 2.3.
- Parameters:
placeholder (Optional[
str]) – The placeholder text that is shown if nothing is selected, if any.custom_id (
str) – The ID of the select menu that gets received during an interaction. It is recommended not to set this parameter to prevent conflicts.row (Optional[
int]) – The relative row this select menu belongs to. A Discord component can only have 5 rows. By default, items are arranged automatically into those 5 rows. If you’d like to control the relative positioning of the row then passing an index is advised. For example, row=1 will show up before row=2. Defaults toNone, which is automatic ordering. The row number must be between 0 and 4 (i.e. zero indexed).min_values (
int) – The minimum number of items that must be chosen for this select menu. Defaults to 1 and must be between 1 and 25.max_values (
int) – The maximum number of items that must be chosen for this select menu. Defaults to 1 and must be between 1 and 25.disabled (
bool) – Whether the select is disabled or not. Defaults toFalse.channel_types (List[
ChannelType]) – A list of channel types that can be selected in this menu.
- class nextcord.ui.ChannelSelectValues¶
Represents the values of a
ui.ChannelSelect.- property channels¶
The resolved channels.
- Type:
List[
abc.GuildChannel]
Low Level UI Components¶
These are relatively simple representations of Discord’s Component objects, able to be directly instantiated and sent with messages. While there are helper functions to aid with usage, they are intended to be rather bare and thus there are almost no safe guards nor data validation checks when creating or sending them. Higher level/friendlier UI Component objects can be found in the Bot UI Kit section.
Base Components¶
Base component classes. Not intended to be instantiated by users, but can be used for isinstance() checks.
- class nextcord.Component(*, component_type, component_id=...)¶
Represents a basic component object.
Base class for all components. Intended to be abstract and not instantiated by users, but will be used internally if no other component class is available.
Added in version 2.0.
- Parameters:
component_type – Type of the component.
component_id – Per-message unique ID of the component. If not provided, it will be generated by Discord when sent.
- type¶
The type of component.
- id¶
ID of the component. Can be
MISSING.
- asyncwait_for_interaction
- class nextcord.InteractiveComponent(custom_id=..., *, component_type, component_id=...)¶
Bases:
ComponentBase class for components with the
custom_idattribute and should have callback-related helper methods.This class is intended to be abstract and not instantiated by users.
Added in version 3.2.
- custom_id¶
Custom ID of the component, received in
Interactiondata. Can beMISSING
- await wait_for_interaction(bot, callback, timeout=180.0)¶
This function is a coroutine.
Helper method, waits for an interaction with the matching
custom_idto be received by the given bot/Client.- Parameters:
bot – Bot/Client object to listen for received interactions.
callback – Awaitable callback to execute when the custom ID is found.
timeout – Time in seconds to wait before timing out and raising
asyncio.TimeoutError.
- Raises:
asyncio.TimeoutError – If a timeout is provided and it was reached.
- Returns:
Returns the return value of the given callback.
- Return type:
Any
- type¶
The type of component.
- id¶
ID of the component. Can be
MISSING.
- class nextcord.HolderComponent(components, *, component_type, component_id=...)¶
Bases:
ComponentBase class for components with the
componentsattribute that are designed to hold other components.This class is intended to be abstract and not instantiated by users.
Added in version 3.2.
- components¶
List of child components.
- type¶
The type of component.
- id¶
ID of the component. Can be
MISSING.
Action Row¶
- class nextcord.ActionRow(components, *, component_id=...)¶
Bases:
HolderComponentRepresents an Action Row component object.
This is a component that holds up to 5 children components in a row.
Added in version 2.0.
Changed in version 3.2:
ActionRowis now user init-able.- property children¶
The children components that this holds, if any. Alias for
components.
- components¶
List of child components.
- type¶
The type of component.
- id¶
ID of the component. Can be
MISSING.
Button¶
- class nextcord.Button(style, *, label=..., emoji=..., custom_id=..., sku_id=..., url=..., disabled=..., component_id=...)¶
Bases:
InteractiveComponentRepresents a Button component object.
Note
Due to the conflicting options present in
__init__, it is recommended to use the various classmethods such asas_primary(),as_secondary(), etc.Added in version 2.0.
Changed in version 3.2:
Buttonis now user init-able.- style¶
The style of the button.
- label¶
The label of the button. Can be
MISSING.
- emoji¶
The emoji of the button. Can be
MISSING.
- sku_id¶
ID of a purchasable SKU, only for premium-style buttons. Can be
MISSING.
- url¶
The URL this button sends you to, only for link-style buttons. Can be
MISSING.
- disabled¶
Whether the button is disabled or not. Can be
MISSING.
- await wait_for_interaction(bot, callback, timeout=180.0)¶
This function is a coroutine.
Helper method, waits for an interaction with the matching
custom_idto be received by the given bot/Client.- Parameters:
bot – Bot/Client object to listen for received interactions.
callback – Awaitable callback to execute when the custom ID is found.
timeout – Time in seconds to wait before timing out and raising
asyncio.TimeoutError.
- Raises:
asyncio.TimeoutError – If a timeout is provided and it was reached.
- Returns:
Returns the return value of the given callback.
- Return type:
Any
- classmethod as_primary(custom_id=None, *, label=..., emoji=..., disabled=..., component_id=...)¶
Creates a primary-styled button.
Unspecified parameters will use Discord defaults.
- Parameters:
custom_id – Optionally supplied custom ID for the button.
label – Text to display on the button. Required unless
emojiis specified.emoji – Emoji to display on the button. Required unless
labelis specified.disabled – Whether the button should be disabled or not.
component_id – ID of the component.
- Returns:
Button with the primary style.
- Return type:
- classmethod as_secondary(custom_id=None, *, label=..., emoji=..., disabled=..., component_id=...)¶
Creates a secondary-styled button.
Unspecified parameters will use Discord defaults.
- Parameters:
custom_id – Optionally supplied custom ID for the button.
label – Text to display on the button. Required unless
emojiis specified.emoji – Emoji to display on the button. Required unless
labelis specified.disabled – Whether the button should be disabled or not.
component_id – ID of the component.
- Returns:
Button with the secondary style.
- Return type:
- classmethod as_success(custom_id=None, *, label=..., emoji=..., disabled=..., component_id=...)¶
Creates a success-styled button.
Unspecified parameters will use Discord defaults.
- Parameters:
custom_id – Optionally supplied custom ID for the button.
label – Text to display on the button. Required unless
emojiis specified.emoji – Emoji to display on the button. Required unless
labelis specified.disabled – Whether the button should be disabled or not.
component_id – ID of the component.
- Returns:
Button with the success style.
- Return type:
- classmethod as_danger(custom_id=None, *, label=..., emoji=..., disabled=..., component_id=...)¶
Creates a danger-styled button.
Unspecified parameters will use Discord defaults.
- Parameters:
custom_id – Optionally supplied custom ID for the button.
label – Text to display on the button. Required unless
emojiis specified.emoji – Emoji to display on the button. Required unless
labelis specified.disabled – Whether the button should be disabled or not.
component_id – ID of the component.
- Returns:
Button with the danger style.
- Return type:
- classmethod as_link(url, *, label=..., emoji=..., disabled=..., component_id=...)¶
Creates a link-styled button.
Unspecified non-required parameters will use Discord defaults.
- Parameters:
url – The URL the button should send you to.
label – Text to display on the button. Required unless
emojiis specified.emoji – Emoji to display on the button. Required unless
labelis specified.disabled – Whether the button should be disabled or not.
component_id – ID of the component.
- Returns:
Button with the link style.
- Return type:
Creates a premium-styled button.
Unspecified non-required parameters will use Discord defaults.
- Parameters:
sku_id – ID of a purchasable SKU.
disabled – Whether the button should be disabled or not.
component_id – ID of the component.
- Returns:
Button with the premium style.
- Return type:
- custom_id¶
Custom ID of the component, received in
Interactiondata. Can beMISSING
- type¶
The type of component.
- id¶
ID of the component. Can be
MISSING.
String Select¶
- defadd_option
- asyncwait_for_interaction
- class nextcord.StringSelect(custom_id=None, options=None, *, placeholder=..., min_values=..., max_values=..., disabled=..., component_id=...)¶
Bases:
InteractiveComponentRepresents a String Select component object.
A select menu is functionally the same as a dropdown, however on mobile it renders a bit differently.
There are 2 aliases for this class.
StringSelectMenufor compatibility purposes andSelectMenu.Added in version 2.0.
Changed in version 3.2:
StringSelectis now user init-able.Renamed from
StringSelectMenutoStringSelectto match Discord’s name, and an alias for the old name added.
- options¶
A list of options that can be selected in this menu.
- placeholder¶
The placeholder text that is shown if nothing is selected, if any. Can be
MISSING
- min_values¶
The minimum number of items that must be chosen for this select menu. Can be
MISSING
- max_values¶
The maximum number of items that must be chosen for this select menu. Can be
MISSING
- disabled¶
Whether the select is disabled or not. Can be
MISSING
- add_option(label, value=..., *, description=..., emoji=..., default=...)¶
Helper method to add an option to the
optionslist.- Parameters:
label – User-facing name of the option.
value – Dev-defined/Bot-facing value of the option. Defaults to the value of
labelif unspecified.description – Description for the option.
emoji – Emoji to display with the option.
default – If this option will be selected by default.
- Return type:
None
- await wait_for_interaction(bot, callback, timeout=180.0)¶
This function is a coroutine.
Helper method, waits for an interaction with the matching
custom_idto be received by the given bot/Client.- Parameters:
bot – Bot/Client object to listen for received interactions.
callback – Awaitable callback to execute when the custom ID is found.
timeout – Time in seconds to wait before timing out and raising
asyncio.TimeoutError.
- Raises:
asyncio.TimeoutError – If a timeout is provided and it was reached.
- Returns:
Returns the return value of the given callback.
- Return type:
Any
- custom_id¶
Custom ID of the component, received in
Interactiondata. Can beMISSING
- type¶
The type of component.
- id¶
ID of the component. Can be
MISSING.
Text Input¶
- class nextcord.TextInput(style, label, custom_id=None, *, min_length=..., max_length=..., required=..., value=..., placeholder=..., component_id=...)¶
Bases:
InteractiveComponentRepresents a Text Input component object.
Allows for users to enter free-form text responses, and supports both single-line and multi-line inputs. Can only be used within modals.
Added in version 2.0.
Changed in version 3.2:
TextInputis now user init-able.- style¶
Style of the text input.
- label¶
Label of the text input.
- min_length¶
The minimal length of the user’s input. Can be
MISSING.
- max_length¶
The maximal length of the user’s input. Can be
MISSING.
- required¶
If
True, the user cannot send the form without filling this field. Can beMISSING.
- value¶
Pre-filled value for the component. Can be
MISSING.
- placeholder¶
The text shown to the user when the text input is empty. Can be
MISSING.
- classmethod as_short(label, custom_id=None, *, min_length=..., max_length=..., required=..., value=..., placeholder=..., component_id=...)¶
Creates a short-styled, single-line text input.
Unspecified non-required parameters will use Discord defaults.
- Parameters:
label – Label of the text input.
custom_id – Optionally supplied custom ID for the text input.
min_length – The minimal length of the user’s input.
max_length – The maximal length of the user’s input.
required – If
True, the user cannot send the form without filling this field.value – Pre-filled value for the component.
placeholder – The text shown to the user when the text input is empty.
component_id – ID of the component.
- Returns:
Text input with the short style.
- Return type:
- classmethod as_paragraph(label, custom_id=None, *, min_length=..., max_length=..., required=..., value=..., placeholder=..., component_id=...)¶
Creates a paragraph-styled, multi-line text input.
Unspecified non-required parameters will use Discord defaults.
- Parameters:
label – Label of the text input.
custom_id – Optionally supplied custom ID for the text input.
min_length – The minimal length of the user’s input.
max_length – The maximal length of the user’s input.
required – If
True, the user cannot send the form without filling this field.value – Pre-filled value for the component.
placeholder – The text shown to the user when the text input is empty.
component_id – ID of the component.
- Returns:
Text input with the paragraph style.
- Return type:
- await wait_for_interaction(bot, callback, timeout=180.0)¶
This function is a coroutine.
Helper method, waits for an interaction with the matching
custom_idto be received by the given bot/Client.- Parameters:
bot – Bot/Client object to listen for received interactions.
callback – Awaitable callback to execute when the custom ID is found.
timeout – Time in seconds to wait before timing out and raising
asyncio.TimeoutError.
- Raises:
asyncio.TimeoutError – If a timeout is provided and it was reached.
- Returns:
Returns the return value of the given callback.
- Return type:
Any
- custom_id¶
Custom ID of the component, received in
Interactiondata. Can beMISSING
- type¶
The type of component.
- id¶
ID of the component. Can be
MISSING.
User Select¶
- class nextcord.UserSelect(custom_id=None, *, placeholder=..., default_values=..., min_values=..., max_values=..., disabled=..., component_id=...)¶
Bases:
_SelectComponentRepresents a User Select component object.
A user select menu is functionally the same as a dropdown, however on mobile it renders a bit differently.
Added in version 2.3.
Changed in version 3.2:
UserSelectis now user init-able.Renamed from
UserSelectMenutoUserSelectto match Discord’s name, and an alias for the old name added.Added
default_valuesattribute.
- add_default_value(value_id, value_type=SelectDefaultValueType.user)¶
Adds a default value to be pre-populated in the Select dropdown of the given ID and type.
- await wait_for_interaction(bot, callback, timeout=180.0)¶
This function is a coroutine.
Helper method, waits for an interaction with the matching
custom_idto be received by the given bot/Client.- Parameters:
bot – Bot/Client object to listen for received interactions.
callback – Awaitable callback to execute when the custom ID is found.
timeout – Time in seconds to wait before timing out and raising
asyncio.TimeoutError.
- Raises:
asyncio.TimeoutError – If a timeout is provided and it was reached.
- Returns:
Returns the return value of the given callback.
- Return type:
Any
- placeholder¶
Placeholder text if nothing is selected. Can be
MISSING.
- default_values¶
List of pre-populated values. Can be
MISSING.
- min_values¶
Minimum amount of chosen values. Can be
MISSING.
- max_values¶
Maximum amount of chosen values. Can be
MISSING.
- disabled¶
If the menu is disabled. Can be
MISSING.
- custom_id¶
Custom ID of the component, received in
Interactiondata. Can beMISSING
- type¶
The type of component.
- id¶
ID of the component. Can be
MISSING.
Role Select¶
- class nextcord.RoleSelect(custom_id=None, *, placeholder=..., default_values=..., min_values=..., max_values=..., disabled=..., component_id=...)¶
Bases:
_SelectComponentRepresents a Role Select component object.
A role select menu is functionally the same as a dropdown, however on mobile it renders a bit differently.
Added in version 2.3.
Changed in version 3.2:
RoleSelectis now user init-able.Renamed from
RoleSelectMenutoRoleSelectto match Discord’s name, and an alias for the old name added.Added
default_valuesattribute.
- add_default_value(value_id, value_type=SelectDefaultValueType.role)¶
Adds a default value to be pre-populated in the Select dropdown of the given ID and type.
- await wait_for_interaction(bot, callback, timeout=180.0)¶
This function is a coroutine.
Helper method, waits for an interaction with the matching
custom_idto be received by the given bot/Client.- Parameters:
bot – Bot/Client object to listen for received interactions.
callback – Awaitable callback to execute when the custom ID is found.
timeout – Time in seconds to wait before timing out and raising
asyncio.TimeoutError.
- Raises:
asyncio.TimeoutError – If a timeout is provided and it was reached.
- Returns:
Returns the return value of the given callback.
- Return type:
Any
- placeholder¶
Placeholder text if nothing is selected. Can be
MISSING.
- default_values¶
List of pre-populated values. Can be
MISSING.
- min_values¶
Minimum amount of chosen values. Can be
MISSING.
- max_values¶
Maximum amount of chosen values. Can be
MISSING.
- disabled¶
If the menu is disabled. Can be
MISSING.
- custom_id¶
Custom ID of the component, received in
Interactiondata. Can beMISSING
- type¶
The type of component.
- id¶
ID of the component. Can be
MISSING.
Mentionable Select¶
- class nextcord.MentionableSelect(custom_id=None, *, placeholder=..., default_values=..., min_values=..., max_values=..., disabled=..., component_id=...)¶
Bases:
_SelectComponentRepresents a Mentionable Select componeont object.
A mentionable select menu is functionally the same as a dropdown, however on mobile it renders a bit differently.
Added in version 2.3.
Changed in version 3.2:
MentionableSelectis now user init-able.Renamed from
MentionableSelectMenutoMentionableSelectto match Discord’s name, and an alias for the old name added.Added
default_valuesattribute.
- add_default_value(value_id, value_type)¶
Adds a default value to be pre-populated in the Select dropdown of the given ID and type.
- await wait_for_interaction(bot, callback, timeout=180.0)¶
This function is a coroutine.
Helper method, waits for an interaction with the matching
custom_idto be received by the given bot/Client.- Parameters:
bot – Bot/Client object to listen for received interactions.
callback – Awaitable callback to execute when the custom ID is found.
timeout – Time in seconds to wait before timing out and raising
asyncio.TimeoutError.
- Raises:
asyncio.TimeoutError – If a timeout is provided and it was reached.
- Returns:
Returns the return value of the given callback.
- Return type:
Any
- placeholder¶
Placeholder text if nothing is selected. Can be
MISSING.
- default_values¶
List of pre-populated values. Can be
MISSING.
- min_values¶
Minimum amount of chosen values. Can be
MISSING.
- max_values¶
Maximum amount of chosen values. Can be
MISSING.
- disabled¶
If the menu is disabled. Can be
MISSING.
- custom_id¶
Custom ID of the component, received in
Interactiondata. Can beMISSING
- type¶
The type of component.
- id¶
ID of the component. Can be
MISSING.
Channel Select¶
- class nextcord.ChannelSelect(custom_id=None, *, channel_types=..., placeholder=..., default_values=..., min_values=..., max_values=..., disabled=..., component_id=...)¶
Bases:
_SelectComponentRepresents a Channel Select component object.
A channel select menu is functionally the same as a dropdown, however on mobile it renders a bit differently.
Added in version 2.3.
Changed in version 3.2:
ChannelSelectis now user init-able.Renamed from
ChannelSelectMenutoChannelSelectto match Discord’s name, and an alias for the old name added.Added
default_valuesattribute.
- channel_types¶
The types of channels that can be selected. If
MISSING, all channel types are allowed.
- add_default_value(value_id, value_type=SelectDefaultValueType.channel)¶
Adds a default value to be pre-populated in the Select dropdown of the given ID and type.
- await wait_for_interaction(bot, callback, timeout=180.0)¶
This function is a coroutine.
Helper method, waits for an interaction with the matching
custom_idto be received by the given bot/Client.- Parameters:
bot – Bot/Client object to listen for received interactions.
callback – Awaitable callback to execute when the custom ID is found.
timeout – Time in seconds to wait before timing out and raising
asyncio.TimeoutError.
- Raises:
asyncio.TimeoutError – If a timeout is provided and it was reached.
- Returns:
Returns the return value of the given callback.
- Return type:
Any
- placeholder¶
Placeholder text if nothing is selected. Can be
MISSING.
- default_values¶
List of pre-populated values. Can be
MISSING.
- min_values¶
Minimum amount of chosen values. Can be
MISSING.
- max_values¶
Maximum amount of chosen values. Can be
MISSING.
- disabled¶
If the menu is disabled. Can be
MISSING.
- custom_id¶
Custom ID of the component, received in
Interactiondata. Can beMISSING
- type¶
The type of component.
- id¶
ID of the component. Can be
MISSING.
Section¶
- class nextcord.Section(accessory, components, *, component_id=...)¶
Bases:
HolderComponentRepresents a Section component object.
Holds up to 3
TextDisplaycomponents, with a singleButtonorThumbnailaccessory displayed to the side.Added in version 3.2.
- Parameters:
accessory (nextcord.components.Component) – Component to display on the side. Currently, Discord only supports
ButtonorThumbnailcomponents to be used as accessories.components (list[nextcord.components.TextDisplay | nextcord.components.Component]) – List of components to be primarily displayed. Currently, Discord only supports up to 3
TextDisplaycomponents to be used.component_id – Per-message unique ID of the component. If not provided, it will be generated by Discord when sent.
- components¶
List of components to be primarily displayed.
- accessory¶
Component displayed to the side.
- type¶
The type of component.
- id¶
ID of the component. Can be
MISSING.
Text Display¶
- class nextcord.TextDisplay(content, *, component_id=...)¶
Bases:
ComponentRepresents a Text Display component object.
Allows you to add text to your component message, supporting markdown and user + role mentions.
Added in version 3.2.
- Parameters:
content (str) – Text to be displayed.
component_id – Per-message unique ID of the component. If not provided, it will be generated by Discord when sent.
- content¶
Text to be displayed.
- type¶
The type of component.
- id¶
ID of the component. Can be
MISSING.
Thumbnail¶
- class nextcord.Thumbnail(media, *, description=..., spoiler=..., component_id=...)¶
Bases:
ComponentRepresents a Thumbnail component object.
Displays a small image, currently only usable in a
Sectioncomponent as the accessory.Added in version 3.2.
- Parameters:
media (nextcord.components.UnfurledMedia) – Media to be displayed.
description (str) – Alt text for the media.
spoiler (bool) – Whether the media should be spoilered/blurred out.
component_id – Per-message unique ID of the component. If not provided, it will be generated by Discord when sent.
- type¶
The type of component.
- id¶
ID of the component. Can be
MISSING.
- media¶
Media to be displayed.
- description¶
Alt text for the media. Can be
MISSING
- spoiler¶
Whether the media should be spoilered/blurred out. Can be
MISSING
- classmethod from_url(url, *, description=..., spoiler=..., component_id=...)¶
Simple helper method, inits this with an UnfurledMedia set to the given url.
Media Gallery¶
- class nextcord.MediaGallery(items, *, component_id=...)¶
Bases:
ComponentRepresents a Media Gallery component object.
Allows displaying between 1 and 10
MediaGalleryItemattachments in an organized gallery format.Added in version 3.2.
- Parameters:
items (list[nextcord.components.MediaGalleryItem]) – List of items to display in the gallery.
component_id – Per-message unique ID of the component. If not provided, it will be generated by Discord when sent.
- type¶
The type of component.
- id¶
ID of the component. Can be
MISSING.
- items¶
List of
MediaGalleryItemobjects to display.
File Display¶
- class nextcord.FileDisplay(file, *, spoiler=..., component_id=...)¶
Bases:
ComponentRepresents a File component object.
Allows referencing/displaying a file that was uploaded as an attachment to the message.
Added in version 3.2.
- Parameters:
file (nextcord.components.UnfurledMedia) – Attachment/media to be displayed, only supports
attachment://<filename>style references.spoiler (bool) – Whether the media should be spoilered/blurred out.
component_id – Per-message unique ID of the component. If not provided, it will be generated by Discord when sent.
- type¶
The type of component.
- id¶
ID of the component. Can be
MISSING.
- file¶
Attachment to be displayed.
- spoiler¶
Whether the attachment should be spoilered/blurred out. Can be
MISSING
- classmethod from_url(url, *, spoiler=..., component_id=...)¶
Simple helper method, inits this with an UnfurledMedia set to the given url.
Must use the
attachment://<filename>syntax
- classmethod from_file(file, *, spoiler=..., component_id=...)¶
Simple helper method. inits this with a DiscordFile.
Separator¶
- class nextcord.Separator(divider=..., spacing=..., *, component_id=...)¶
Bases:
ComponentRepresents a Separator component object.
Adds vertical padding and optionally a visual divider between components.
Added in version 3.2.
- Parameters:
divider (bool) – Whether a visual divider should be displayed.
spacing (nextcord.enums.SeparatorSpacingSize) – Size of the separator padding.
component_id – Per-message unique ID of the component. If not provided, it will be generated by Discord when sent.
- type¶
The type of component.
- id¶
ID of the component. Can be
MISSING.
- divider¶
Whether a visual divider should be displayed. Can be
MISSING
- spacing¶
Size of the separator padding. Can be
MISSING
Container¶
- class nextcord.Container(components, accent_color=..., spoiler=..., *, component_id=...)¶
Bases:
HolderComponentRepresents a Container component object.
Holds other components with a visually distinct background and can have an accent color on the side, similar to
Embedobjects.Added in version 3.2.
- Parameters:
components (list[nextcord.components.Component]) – List of components to display.
accent_color (int | None) – Accent color to display on the side.
spoiler (bool) – Whether the container should be spoilered/blurred out.
component_id – Per-message unique ID of the component. If not provided, it will be generated by Discord when sent.
- components¶
List of child components.
- type¶
The type of component.
- id¶
ID of the component. Can be
MISSING.
- accent_color¶
Accent color displayed on the side. Can be
MISSING
- spoiler¶
Whether the container should be spoilered/blurred out. Can be
MISSING
Component Data Objects¶
While these are not components, they are required to create/populate certain components. Components for components, if you will.
- class nextcord.SelectOption(label, value=..., *, description=..., emoji=..., default=...)¶
Represents an option for the selects that use it.
Currently only used by
StringSelect.Added in version 2.0.
- Parameters:
label (str) – The label of the option. This is displayed to users. Can only be up to 100 characters.
value (str) – The value of the option. This is not displayed to users. If not provided when constructed then it defaults to the label. Can only be up to 100 characters.
description (str) – An additional description of the option, if any. Can only be up to 100 characters.
emoji (nextcord.partial_emoji.PartialEmoji) – The emoji of the option, if available.
default (bool) – Whether this option is selected by default.
- label¶
User-facing name of the option.
- value¶
Dev-defined/Bot-facing value of the option.
- description¶
Description of the option. Can be
MISSING
- emoji¶
The emoji of the option. Can be
MISSING
- default¶
Whether this option is selected by default. Can be
MISSING
- class nextcord.SelectDefaultValue(value_id, value_type)¶
Represents a default value for the selects that use it.
Used in
UserSelect,RoleSelect,MentionableSelect, andChannelSelect.Added in version 3.2.
- Parameters:
value_id – ID/Snowflake of the default value.
value_type – Type of object the
value_idcorresponds to.
- id¶
ID/Snowflake
- class nextcord.UnfurledMedia(url, *, proxy_url=..., height=..., width=..., content_type=..., attachment_id=...)¶
Represents a reference to some media.
The referenced media can either be an external link or an attachment included in the message.
Added in version 3.2.
- Parameters:
url (str) – Source of the media. Can either be an arbitrary URL, or use the
attachment://<filename>syntax to reference an included attachment.
- url¶
Source of the media.
- proxy_url¶
Proxy URL of the media, provided by Discord. Can be
MISSING
- height¶
Height of the media, provided by Discord. Can be
MISSING
- width¶
Width of the media, provided by Discord. Can be
MISSING
- content_type¶
Type of the media, provided by Discord. Can be
MISSING
- attachment_id¶
ID of the referenced attachment, provided by Discord if the media references an attachment. Can be
MISSING
- class nextcord.MediaGalleryItem(media, *, description=..., spoiler=...)¶
Represents an item in a
MediaGallerycomponent.Essentially acts as a wrapper around
UnfurledMediawith the ability to add a description and/or spoiler it.Added in version 3.2.
- Parameters:
media (nextcord.components.UnfurledMedia) – Media to be displayed.
description (str) – Alt text for the media.
spoiler (bool) – Whether the media should be spoilered/blurred out.
- media¶
Media to be displayed.
- description¶
Alt text for the media. Can be
MISSING
- spoiler¶
Whether the media should be spoilered/blurred out. Can be
MISSING
- classmethod from_url(url, *, description=..., spoiler=...)¶
Simple helper method, inits this with an UnfurledMedia set to the given url.
Application Commands¶
The library has helpers to easily create and manipulate application commands.
Base Commands¶
- defadd_check
- defadd_guild_rollout
- defafter_invoke
- defbefore_invoke
- asynccall
- asynccall_from_interaction
- asynccan_run
- deferror
- deffrom_callback
- defget_payload
- defget_rollout_signatures
- defget_signature
- defget_signatures
- defhas_error_handler
- asyncinvoke_callback
- asyncinvoke_callback_with_hooks
- asyncinvoke_error
- defis_interaction_valid
- defis_payload_valid
- defparse_discord_response
- defremove_check
- class nextcord.BaseApplicationCommand(name=None, description=None, *, cmd_type, name_localizations=None, description_localizations=None, callback=None, guild_ids=..., default_member_permissions=None, nsfw=False, integration_types=None, contexts=None, parent_cog=None, force_global=False)¶
Base class for all application commands.
- checks¶
A list of predicates that verifies if the command could be executed with the given
Interactionas the sole parameter. If an exception is necessary to be thrown to signal failure, then one inherited fromApplicationErrorshould be used. Note that if the checks fail thenApplicationCheckFailureexception is raised to theon_application_command_error()event.- Type:
List[Union[Callable[[
ClientCog,Interaction], MaybeCoro[bool]], Callable[[Interaction], MaybeCoro[bool]]]]
- integration_types¶
Where the command is available, only for globally-scoped commands.
Added in version 3.0.
- Type:
Optional[Iterable[Union[
IntegrationType,int]]]
- contexts¶
Where the command can be used, only for globally-scoped commands.
Added in version 3.0.
- Type:
Optional[Iterable[Union[
InteractionContextType,int]]]
- command_ids¶
Dict[Optional[
int],int]: Command IDs that this application command currently has. Schema: {Guild ID (None for global): command ID}
- property required_permissions¶
Returns the permissions required to run this command.
Note
This returns the permissions set with
ext.application_checks.has_permissions().Added in version 2.6.
- property required_bot_permissions¶
Returns the permissions the bot needs to run this command.
Note
This returns the permissions set with
ext.application_checks.bot_has_permissions().Added in version 2.6.
- property required_guild_permissions¶
Returns the guild permissions needed to run this command.
Note
This returns the permissions set with
ext.application_checks.has_guild_permissions().Added in version 2.6.
- property required_bot_guild_permissions¶
Returns the permissions the bot needs to have in this guild in order to run this command.
Note
This returns the permissions set with
ext.application_checks.bot_has_guild_permissions().Added in version 2.6.
- property qualified_name¶
Retrieves the fully qualified command name.
Added in version 2.1.
- Type:
- property description¶
The description the command should have in Discord. Should be 1-100 characters long.
- property is_guild¶
Returns
Trueif this command is or should be registered to any guilds.- Type:
- add_guild_rollout(guild)¶
Adds a Guild to the command to be rolled out to when the rollout is run.
- get_signature(guild_id=None)¶
Returns a command signature with the given guild ID.
- get_rollout_signatures()¶
Returns all signatures that this command wants to roll out to.
Command signatures are made up of the command name, command type, and Guild ID (
Nonefor global).
- get_signatures()¶
Returns all the signatures that this command has.
Command signatures are made up of the command name, command type, and Guild ID (
Nonefor global).
- get_payload(guild_id)¶
Makes an Application Command payload for this command to upsert to Discord with the given Guild ID.
- parse_discord_response(state, data)¶
Parses the application command creation/update response from Discord.
- Parameters:
state (
ConnectionState) – Connection state to use internally in the command.data (Union[
ApplicationCommandInteractionData,ApplicationCommand]) – Raw dictionary data from Discord.
- is_payload_valid(raw_payload, guild_id=None)¶
Checks if the given raw application command interaction payload from Discord is possibly valid for this command. Note that while this may return
Truefor a given payload, that doesn’t mean that the payload is fully correct for this command. Discord doesn’t send data for parameters that are optional and aren’t supplied by the user.- Parameters:
- Returns:
Trueif the given payload is possibly valid for this command.Falseotherwise.- Return type:
- is_interaction_valid(interaction)¶
Checks if the interaction given is possibly valid for this command. If the command has more parameters (especially optionals) than the interaction coming in, this may cause a desync between your bot and Discord.
- Parameters:
interaction (
Interaction) – Interaction to validate.- Returns:
TrueIf the interaction could possibly be for this command,Falseotherwise.- Return type:
- from_callback(callback=None, option_class=<class 'nextcord.application_command.BaseCommandOption'>)¶
Creates objects of type
option_classwith the parameters of the function, and stores them in the options attribute.- Parameters:
callback (Optional[
Callable]) – Callback to create options from. Must be a coroutine function.option_class (Optional[Type[
BaseCommandOption]]) – Class to create the options using. Should either be or subclassBaseCommandOption. Defaults toBaseCommandOption.
- Returns:
Self for possible chaining.
- Return type:
CallbackMixin
- await call_from_interaction(interaction)¶
This function is a coroutine. Calls the callback via the given
Interaction, relying on the locally storedConnectionStateobject.- Parameters:
interaction (
Interaction) – Interaction corresponding to the use of the command.
- await call(state, interaction)¶
This function is a coroutine. Calls the callback via the given
Interaction, using the givenConnectionStateto get resolved objects if needed and available.- Parameters:
state (
ConnectionState) – State object to get resolved objects from.interaction (
Interaction) – Interaction corresponding to the use of the command.
- add_check(func)¶
Adds a check to the application command. Returns the application command for method chaining.
- Parameters:
func (
ApplicationCheck) – The function that will be used as a check.
- after_invoke(coro)¶
Sets the callback that should be run after the command callback is invoked.
- Parameters:
coro (Callable[[
Interaction], Coroutine]) – Coroutine to set as the after_invoke hook.- Returns:
The coroutine to allow multiple commands to share the function.
- Return type:
Callable[[
Interaction], Coroutine]
- before_invoke(coro)¶
Sets the callback that should be run before the command callback is invoked.
- Parameters:
coro (Callable[[
Interaction], Coroutine]) – Coroutine to set as the before_invoke hook.- Returns:
The coroutine to allow multiple commands to share the function.
- Return type:
Callable[[
Interaction], Coroutine]
- await can_run(interaction)¶
This function is a coroutine.
Checks if the command can be executed by checking all the predicates inside the
checksattribute, as well as all global and cog checks.- Parameters:
interaction (
Interaction) – The interaction of the command currently being invoked.- Raises:
ApplicationError – Any application command error that was raised during a check call will be propagated by this function.
- Returns:
A boolean indicating if the command can be invoked.
- Return type:
- property cog_after_invoke¶
Returns the cog_application_command_after_invoke method for the cog that this command is in.
- Returns:
after_invokemethod from the parent cog.Noneif not the method is not found.- Return type:
Optional[
ApplicationHook]
- property cog_before_invoke¶
Returns the cog_application_command_before_invoke method for the cog that this command is in. Returns
Noneif not the method is not found.- Returns:
before_invokemethod from the parent cog.Noneif not the method is not found.- Return type:
Optional[
ApplicationHook]
- error(callback)¶
Decorates a function, setting it as a callback to be called when a
ApplicationErroror any of its subclasses is raised inside theApplicationCommand.- Parameters:
callback (Callable[[
Interaction,ApplicationError],asyncio.Awaitable[Any]]) – The callback to call when an error occurs.
- property error_name¶
Returns a string containing the class name, command name, and the callback to use in raising exceptions.
Examples
>>> print(app_cmd.error_name) SlashApplicationCommand reloadme <function TinyTest.reloadme at 0x7f4b3b563e20>
- Returns:
String containing the class name, command name, and callback object.
- Return type:
- await invoke_callback(interaction, *args, **kwargs)¶
This function is a coroutine. Invokes the callback, injecting
selfif available.
- await invoke_callback_with_hooks(state, interaction, args=None, kwargs=None)¶
This function is a coroutine. Invokes the callback with all hooks and checks.
- await invoke_error(interaction, error)¶
This function is a coroutine. Invokes the error handler if available.
- remove_check(func)¶
Removes a check from the ApplicationCommand. Returns the application command for method chaining.
This function is idempotent and will not raise an exception if the function is not in the command’s checks.
- Parameters:
func (
ApplicationCheck) – The function to remove from the checks.
- class nextcord.BaseCommandOption(parameter, command, parent_cog=None)¶
Represents an application command option, but takes a
ParameterandClientCogas an argument.- Parameters:
parameter (
Parameter) – Function parameter to construct the command option with.command (Union[
BaseApplicationCommand,SlashApplicationSubcommand]) – Application Command this option is for.parent_cog (
ClientCog) – Class that the function the option is for resides in.
- functional_name¶
Name of the kwarg in the function/method
Slash Commands¶
- defadd_check
- defadd_guild_rollout
- defafter_invoke
- defbefore_invoke
- asynccall
- asynccall_autocomplete
- asynccall_autocomplete_from_interaction
- asynccall_from_interaction
- asynccan_run
- deferror
- deffrom_autocomplete
- deffrom_callback
- defget_mention
- defget_payload
- defget_rollout_signatures
- defget_signature
- defget_signatures
- defhas_error_handler
- asyncinvoke_callback
- asyncinvoke_callback_with_hooks
- asyncinvoke_error
- defis_interaction_valid
- defis_payload_valid
- defon_autocomplete
- defparse_discord_response
- defremove_check
- defsubcommand
- class nextcord.SlashApplicationCommand(name=None, description=None, *, name_localizations=None, description_localizations=None, callback=None, guild_ids=None, default_member_permissions=None, nsfw=False, integration_types=None, contexts=None, parent_cog=None, force_global=False)¶
Class representing a slash command.
- property description¶
The description the command should have in Discord. Should be 1-100 characters long.
- get_payload(guild_id)¶
Makes an Application Command payload for this command to upsert to Discord with the given Guild ID.
- await call(state, interaction)¶
This function is a coroutine. Calls the callback via the given
Interaction, using the givenConnectionStateto get resolved objects if needed and available.- Parameters:
state (
ConnectionState) – State object to get resolved objects from.interaction (
Interaction) – Interaction corresponding to the use of the command.
- from_callback(callback=None, option_class=<class 'nextcord.application_command.SlashCommandOption'>, call_children=True)¶
Creates objects of type
option_classwith the parameters of the function, and stores them in the options attribute.- Parameters:
callback (Optional[
Callable]) – Callback to create options from. Must be a coroutine function.option_class (Optional[Type[
BaseCommandOption]]) – Class to create the options using. Should either be or subclassBaseCommandOption. Defaults toBaseCommandOption.
- Returns:
Self for possible chaining.
- Return type:
CallbackMixin
- subcommand(name=None, description=None, *, name_localizations=None, description_localizations=None, inherit_hooks=False)¶
Takes the decorated callback and turns it into a
SlashApplicationSubcommandadded as a subcommand.- Parameters:
name (
str) – Name of the command that users will see. If not set, it defaults to the name of the callback.description (
str) – Description of the command that users will see. If not specified, the docstring will be used. If no docstring is found for the command callback, it defaults to “No description provided”.name_localizations (Dict[Union[
Locale,str],str]) – Name(s) of the command for users of specific locales. The locale code should be the key, with the localized name as the value.description_localizations (Dict[Union[
Locale,str],str]) – Description(s) of the subcommand for users of specific locales. The locale code should be the key, with the localized description as the value.inherit_hooks (
bool) – If the subcommand should inherit the parent commandsbefore_invokeandafter_invokecallbacks. Defaults toFalse.
- add_check(func)¶
Adds a check to the application command. Returns the application command for method chaining.
- Parameters:
func (
ApplicationCheck) – The function that will be used as a check.
- add_guild_rollout(guild)¶
Adds a Guild to the command to be rolled out to when the rollout is run.
- after_invoke(coro)¶
Sets the callback that should be run after the command callback is invoked.
- Parameters:
coro (Callable[[
Interaction], Coroutine]) – Coroutine to set as the after_invoke hook.- Returns:
The coroutine to allow multiple commands to share the function.
- Return type:
Callable[[
Interaction], Coroutine]
- before_invoke(coro)¶
Sets the callback that should be run before the command callback is invoked.
- Parameters:
coro (Callable[[
Interaction], Coroutine]) – Coroutine to set as the before_invoke hook.- Returns:
The coroutine to allow multiple commands to share the function.
- Return type:
Callable[[
Interaction], Coroutine]
- await call_autocomplete(state, interaction, option_data=None)¶
This function is a coroutine. Calls the autocomplete callback with the given interaction and option data.
- await call_autocomplete_from_interaction(interaction)¶
This function is a coroutine. Calls the autocomplete callback with the given interaction.
- await call_from_interaction(interaction)¶
This function is a coroutine. Calls the callback via the given
Interaction, relying on the locally storedConnectionStateobject.- Parameters:
interaction (
Interaction) – Interaction corresponding to the use of the command.
- await can_run(interaction)¶
This function is a coroutine.
Checks if the command can be executed by checking all the predicates inside the
checksattribute, as well as all global and cog checks.- Parameters:
interaction (
Interaction) – The interaction of the command currently being invoked.- Raises:
ApplicationError – Any application command error that was raised during a check call will be propagated by this function.
- Returns:
A boolean indicating if the command can be invoked.
- Return type:
- property children¶
Returns the sub-commands and sub-command groups of the command.
Changed in version 2.3:
.childrenis now a read-only property.
- property cog_after_invoke¶
Returns the cog_application_command_after_invoke method for the cog that this command is in.
- Returns:
after_invokemethod from the parent cog.Noneif not the method is not found.- Return type:
Optional[
ApplicationHook]
- property cog_before_invoke¶
Returns the cog_application_command_before_invoke method for the cog that this command is in. Returns
Noneif not the method is not found.- Returns:
before_invokemethod from the parent cog.Noneif not the method is not found.- Return type:
Optional[
ApplicationHook]
- error(callback)¶
Decorates a function, setting it as a callback to be called when a
ApplicationErroror any of its subclasses is raised inside theApplicationCommand.- Parameters:
callback (Callable[[
Interaction,ApplicationError],asyncio.Awaitable[Any]]) – The callback to call when an error occurs.
- property error_name¶
Returns a string containing the class name, command name, and the callback to use in raising exceptions.
Examples
>>> print(app_cmd.error_name) SlashApplicationCommand reloadme <function TinyTest.reloadme at 0x7f4b3b563e20>
- Returns:
String containing the class name, command name, and callback object.
- Return type:
- from_autocomplete()¶
Processes the found autocomplete callbacks and associates them to their corresponding options.
- Raises:
ValueError – If a found arg name doesn’t correspond to an autocomplete function.
- get_mention(guild=None)¶
Returns a string that allows you to mention the slash command.
Added in version 2.2.
- Parameters:
guild (Optional[
Snowflake]) – TheGuildof the command to mention. IfNone, then the global command will be mentioned.- Returns:
The string that allows you to mention the slash command.
- Return type:
- Raises:
ValueError – If no guild was provided and the command is not registered globally, or the command is not registered in the guild provided.
- get_rollout_signatures()¶
Returns all signatures that this command wants to roll out to.
Command signatures are made up of the command name, command type, and Guild ID (
Nonefor global).
- get_signature(guild_id=None)¶
Returns a command signature with the given guild ID.
- get_signatures()¶
Returns all the signatures that this command has.
Command signatures are made up of the command name, command type, and Guild ID (
Nonefor global).
- await invoke_callback(interaction, *args, **kwargs)¶
This function is a coroutine. Invokes the callback, injecting
selfif available.
- await invoke_callback_with_hooks(state, interaction, args=None, kwargs=None)¶
This function is a coroutine. Invokes the callback with all hooks and checks.
- await invoke_error(interaction, error)¶
This function is a coroutine. Invokes the error handler if available.
- property is_guild¶
Returns
Trueif this command is or should be registered to any guilds.- Type:
- is_interaction_valid(interaction)¶
Checks if the interaction given is possibly valid for this command. If the command has more parameters (especially optionals) than the interaction coming in, this may cause a desync between your bot and Discord.
- Parameters:
interaction (
Interaction) – Interaction to validate.- Returns:
TrueIf the interaction could possibly be for this command,Falseotherwise.- Return type:
- is_payload_valid(raw_payload, guild_id=None)¶
Checks if the given raw application command interaction payload from Discord is possibly valid for this command. Note that while this may return
Truefor a given payload, that doesn’t mean that the payload is fully correct for this command. Discord doesn’t send data for parameters that are optional and aren’t supplied by the user.- Parameters:
- Returns:
Trueif the given payload is possibly valid for this command.Falseotherwise.- Return type:
- on_autocomplete(on_kwarg)¶
Decorator that adds an autocomplete callback to the given kwarg.
@bot.slash_command() async def your_favorite_dog(interaction: Interaction, dog: str): await interaction.response.send_message(f"Your favorite dog is {dog}!") @your_favorite_dog.on_autocomplete("dog") async def favorite_dog(interaction: Interaction, dog: str): if not dog: # send the full autocomplete list await interaction.response.send_autocomplete(list_of_dog_breeds) return # send a list of nearest matches from the list of dog breeds get_near_dog = [breed for breed in list_of_dog_breeds if breed.lower().startswith(dog.lower())] await interaction.response.send_autocomplete(get_near_dog)
Note
To use inputs from other options inputted in the command, you can add them as arguments to the autocomplete callback. The order of the arguments does not matter, but the names do.
If you are using
nextcord.Memberornextcord.Usertypehints in your autocompletes then just note that the objects provided can be both None andnextcord.Objectdepending on the data Discord sends.- Parameters:
on_kwarg (
str) – The slash command option to add the autocomplete callback to.
- property options¶
Returns the options of the command.
Changed in version 2.5: This is now a property.
- Type:
Dict[
str,SlashCommandOption]
- parse_discord_response(state, data)¶
Parses the application command creation/update response from Discord.
- Parameters:
state (
ConnectionState) – Connection state to use internally in the command.data (Union[
ApplicationCommandInteractionData,ApplicationCommand]) – Raw dictionary data from Discord.
- property qualified_name¶
Retrieves the fully qualified command name.
Added in version 2.1.
- Type:
- remove_check(func)¶
Removes a check from the ApplicationCommand. Returns the application command for method chaining.
This function is idempotent and will not raise an exception if the function is not in the command’s checks.
- Parameters:
func (
ApplicationCheck) – The function to remove from the checks.
- property required_bot_guild_permissions¶
Returns the permissions the bot needs to have in this guild in order to run this command.
Note
This returns the permissions set with
ext.application_checks.bot_has_guild_permissions().Added in version 2.6.
- property required_bot_permissions¶
Returns the permissions the bot needs to run this command.
Note
This returns the permissions set with
ext.application_checks.bot_has_permissions().Added in version 2.6.
- property required_guild_permissions¶
Returns the guild permissions needed to run this command.
Note
This returns the permissions set with
ext.application_checks.has_guild_permissions().Added in version 2.6.
- property required_permissions¶
Returns the permissions required to run this command.
Note
This returns the permissions set with
ext.application_checks.has_permissions().Added in version 2.6.
- defadd_check
- defafter_invoke
- defbefore_invoke
- asynccall
- asynccall_autocomplete
- asynccall_autocomplete_from_interaction
- asynccan_run
- deferror
- deffrom_autocomplete
- deffrom_callback
- defget_mention
- defhas_error_handler
- asyncinvoke_callback
- asyncinvoke_callback_with_hooks
- asyncinvoke_error
- defon_autocomplete
- defremove_check
- defsubcommand
- class nextcord.SlashApplicationSubcommand(name=None, description=None, *, cmd_type, name_localizations=None, description_localizations=None, callback=None, parent_cmd=None, parent_cog=None, inherit_hooks=False)¶
Class representing a subcommand or subcommand group of a slash command.
- property options¶
Returns the options of the command.
Changed in version 2.5: This is now a property.
- Type:
Dict[
str,SlashCommandOption]
- property qualified_name¶
Retrieve the command name including all parents space separated.
An example of the output would be
parent group subcommand.Added in version 2.1.
- Type:
- await call(state, interaction, option_data)¶
This function is a coroutine. Calls the callback via the given
Interaction, using the givenConnectionStateto get resolved objects if needed and available and the given option data.- Parameters:
state (
ConnectionState) – State object to get resolved objects from.interaction (
Interaction) – Interaction corresponding to the use of the subcommand.option_data (List[
dict]) – List of raw option data from Discord.
- property payload¶
Returns a dict payload made of the attributes of the subcommand (group) to be sent to Discord.
- from_callback(callback=None, option_class=<class 'nextcord.application_command.SlashCommandOption'>, call_children=True)¶
Creates objects of type
option_classwith the parameters of the function, and stores them in the options attribute.- Parameters:
callback (Optional[
Callable]) – Callback to create options from. Must be a coroutine function.option_class (Optional[Type[
BaseCommandOption]]) – Class to create the options using. Should either be or subclassBaseCommandOption. Defaults toBaseCommandOption.
- Returns:
Self for possible chaining.
- Return type:
CallbackMixin
- subcommand(name=None, description=None, *, name_localizations=None, description_localizations=None, inherit_hooks=False)¶
Takes the decorated callback and turns it into a
SlashApplicationSubcommandadded as a subcommand.- Parameters:
name (
str) – Name of the command that users will see. If not set, it defaults to the name of the callback.description (
str) – Description of the command that users will see. If not specified, the docstring will be used. If no docstring is found for the command callback, it defaults to “No description provided”.name_localizations (Dict[Union[
Locale,str],str]) – Name(s) of the command for users of specific locales. The locale code should be the key, with the localized name as the value.description_localizations (Dict[Union[
Locale,str],str]) – Description(s) of the subcommand for users of specific locales. The locale code should be the key, with the localized description as the value.inherit_hooks (
bool) – If the subcommand should inherit the parent subcommandsbefore_invokeandafter_invokecallbacks. Defaults toFalse.
- property command_ids¶
Command IDs the parent command of this subcommand currently has. Schema: {Guild ID (None for global): command ID}
Added in version 2.2.
- add_check(func)¶
Adds a check to the application command. Returns the application command for method chaining.
- Parameters:
func (
ApplicationCheck) – The function that will be used as a check.
- after_invoke(coro)¶
Sets the callback that should be run after the command callback is invoked.
- Parameters:
coro (Callable[[
Interaction], Coroutine]) – Coroutine to set as the after_invoke hook.- Returns:
The coroutine to allow multiple commands to share the function.
- Return type:
Callable[[
Interaction], Coroutine]
- before_invoke(coro)¶
Sets the callback that should be run before the command callback is invoked.
- Parameters:
coro (Callable[[
Interaction], Coroutine]) – Coroutine to set as the before_invoke hook.- Returns:
The coroutine to allow multiple commands to share the function.
- Return type:
Callable[[
Interaction], Coroutine]
- await call_autocomplete(state, interaction, option_data=None)¶
This function is a coroutine. Calls the autocomplete callback with the given interaction and option data.
- await call_autocomplete_from_interaction(interaction)¶
This function is a coroutine. Calls the autocomplete callback with the given interaction.
- await can_run(interaction)¶
This function is a coroutine.
Checks if the command can be executed by checking all the predicates inside the
checksattribute, as well as all global and cog checks.- Parameters:
interaction (
Interaction) – The interaction of the command currently being invoked.- Raises:
ApplicationError – Any application command error that was raised during a check call will be propagated by this function.
- Returns:
A boolean indicating if the command can be invoked.
- Return type:
- property children¶
Returns the sub-commands and sub-command groups of the command.
Changed in version 2.3:
.childrenis now a read-only property.
- property cog_after_invoke¶
Returns the cog_application_command_after_invoke method for the cog that this command is in.
- Returns:
after_invokemethod from the parent cog.Noneif not the method is not found.- Return type:
Optional[
ApplicationHook]
- property cog_before_invoke¶
Returns the cog_application_command_before_invoke method for the cog that this command is in. Returns
Noneif not the method is not found.- Returns:
before_invokemethod from the parent cog.Noneif not the method is not found.- Return type:
Optional[
ApplicationHook]
- error(callback)¶
Decorates a function, setting it as a callback to be called when a
ApplicationErroror any of its subclasses is raised inside theApplicationCommand.- Parameters:
callback (Callable[[
Interaction,ApplicationError],asyncio.Awaitable[Any]]) – The callback to call when an error occurs.
- property error_name¶
Returns a string containing the class name, command name, and the callback to use in raising exceptions.
Examples
>>> print(app_cmd.error_name) SlashApplicationCommand reloadme <function TinyTest.reloadme at 0x7f4b3b563e20>
- Returns:
String containing the class name, command name, and callback object.
- Return type:
- from_autocomplete()¶
Processes the found autocomplete callbacks and associates them to their corresponding options.
- Raises:
ValueError – If a found arg name doesn’t correspond to an autocomplete function.
- get_mention(guild=None)¶
Returns a string that allows you to mention the slash command.
Added in version 2.2.
- Parameters:
guild (Optional[
Snowflake]) – TheGuildof the command to mention. IfNone, then the global command will be mentioned.- Returns:
The string that allows you to mention the slash command.
- Return type:
- Raises:
ValueError – If no guild was provided and the command is not registered globally, or the command is not registered in the guild provided.
- await invoke_callback(interaction, *args, **kwargs)¶
This function is a coroutine. Invokes the callback, injecting
selfif available.
- await invoke_callback_with_hooks(state, interaction, args=None, kwargs=None)¶
This function is a coroutine. Invokes the callback with all hooks and checks.
- await invoke_error(interaction, error)¶
This function is a coroutine. Invokes the error handler if available.
- on_autocomplete(on_kwarg)¶
Decorator that adds an autocomplete callback to the given kwarg.
@bot.slash_command() async def your_favorite_dog(interaction: Interaction, dog: str): await interaction.response.send_message(f"Your favorite dog is {dog}!") @your_favorite_dog.on_autocomplete("dog") async def favorite_dog(interaction: Interaction, dog: str): if not dog: # send the full autocomplete list await interaction.response.send_autocomplete(list_of_dog_breeds) return # send a list of nearest matches from the list of dog breeds get_near_dog = [breed for breed in list_of_dog_breeds if breed.lower().startswith(dog.lower())] await interaction.response.send_autocomplete(get_near_dog)
Note
To use inputs from other options inputted in the command, you can add them as arguments to the autocomplete callback. The order of the arguments does not matter, but the names do.
If you are using
nextcord.Memberornextcord.Usertypehints in your autocompletes then just note that the objects provided can be both None andnextcord.Objectdepending on the data Discord sends.- Parameters:
on_kwarg (
str) – The slash command option to add the autocomplete callback to.
- remove_check(func)¶
Removes a check from the ApplicationCommand. Returns the application command for method chaining.
This function is idempotent and will not raise an exception if the function is not in the command’s checks.
- Parameters:
func (
ApplicationCheck) – The function to remove from the checks.
Slash Options¶
Typehint |
Discord Type |
Notes |
|---|---|---|
<blank> |
String |
When no typehint is given, it defaults to string. |
String |
||
Integer |
Any integer between -2^53 and 2^53 |
|
Number |
Any double between -2^53 and 2^53 |
|
Boolean |
||
User |
||
User |
Identical to typehinting with |
|
Channel |
Includes all channel types + categories. Use |
|
Channel |
Restricts the accepted channel types to Guild Category channels. |
|
Channel |
Restricts the accepted channel types to DM channels. |
|
Channel |
Restricts the accepted channel types to Forum Channels. |
|
Channel |
Restricts the accepted channel types to Group DM channels. |
|
Channel |
Restricts the accepted channel types to Stage Voice channels. |
|
Channel |
Restricts the accepted channel types to Text and News channels. |
|
Channel |
Restricts the accepted channel types to Voice channels. |
|
Channel |
Restricts the accepted “channel” types to News, Public, and Private threads. |
|
Role |
||
Mentionable |
Includes Users and Roles. |
|
Attachment |
Typing Annotation |
Notes |
|---|---|
|
Makes the slash option not required with the type of the given <type>. |
|
Makes the slash option into a choice of the given type. All choices have to be the same data type. |
|
Allows compatible annotations to be typehinted together. Channel types in a union will allow the slash option to be any of them. |
|
Makes your IDE see <type1> as the expected type, but Nextcord will attempt to use <typeN> as the option type. If <typeN> isn’t a valid option type, Nextcord will work backwards towards <type2> until it finds a type that can be used as a valid option type. |
|
Makes a range of values set in |
|
Makes a range of string length set in |
- class nextcord.SlashOption(name=None, description=None, required=None, *, name_localizations=None, description_localizations=None, choices=None, choice_localizations=None, channel_types=None, min_value=None, max_value=None, min_length=None, max_length=None, autocomplete=None, autocomplete_callback=None, default=..., verify=True)¶
Provides Discord with information about an option in a command.
When this class is set as the default argument of a parameter in an Application Command, additional information about the parameter is sent to Discord for the user to see.
- Parameters:
name (
str) – The name of the Option on Discords side. If left as None, it defaults to the parameter name.description (
str) – The description of the Option on Discords side. If left as None, it defaults to “”.required (
bool) – If a user is required to provide this argument before sending the command.name_localizations (Dict[Union[
Locale,str],str]) – Name(s) of the subcommand for users of specific locales. The locale code should be the key, with the localized name as the valuedescription_localizations (Dict[Union[
Locale,str],str]) – Description(s) of the subcommand for users of specific locales. The locale code should be the key, with the localized description as the valuechoices (Union[Dict[
str, Union[str,int,float]],) – Iterable[Union[str,int,float]]] A list of choices that a user must choose. If adictis given, the keys are what the users are able to see, the values are what is sent back to the bot. Otherwise, it is treated as anIterablewhere what the user sees and is sent back to the bot are the same.choice_localizations (Dict[
str, Dict[Union[Locale,str],str]]) – A dictionary of choice display names as the keys, and dictionaries of locale: localized name as the values.channel_types (List[
ChannelType]) – List ofChannelTypeenums, limiting the users choice to only those channel types. The parameter must be typed asGuildChannelfor this to function.min_value (Union[
int,float]) – Minimum integer or floating point value the user is allowed to input. The parameter must be typed as anintorfloatfor this to function.max_value (Union[
int,float]) – Maximum integer or floating point value the user is allowed to input. The parameter must be typed as anintorfloatfor this to function.min_length (
int) –Minimum length for a string value the user is allowed to input. The parameter must be typed as a
strfor this to function.Added in version 2.1.
max_length (
int) –Maximum length for a string value the user is allowed to input. The parameter must be typed as a
strfor this to function.Added in version 2.1.
autocomplete (
bool) – If this parameter has an autocomplete function decorated for it. If unset, it will automatically beTrueif an autocomplete function for it is found.autocomplete_callback (Optional[
Callable]) – The function that will be used to autocomplete this parameter. If not specified, it will be looked for using theon_autocomplete()decorator.default (Any) – When required is not True and the user doesn’t provide a value for this Option, this value is given instead.
verify (
bool) – If True, the given values will be checked to ensure that the payload to Discord is valid.
- class nextcord.SlashCommandOption(parameter, command, parent_cog=None)¶
- channel_mapping = {<class 'nextcord.channel.CategoryChannel'>: (ChannelType.category,), <class 'nextcord.channel.DMChannel'>: (ChannelType.private,), <class 'nextcord.channel.ForumChannel'>: (ChannelType.forum,), <class 'nextcord.channel.GroupChannel'>: (ChannelType.group,), <class 'nextcord.channel.StageChannel'>: (ChannelType.stage_voice,), <class 'nextcord.channel.TextChannel'>: (ChannelType.text, ChannelType.news), <class 'nextcord.channel.VoiceChannel'>: (ChannelType.voice,), <class 'nextcord.threads.Thread'>: (ChannelType.news_thread, ChannelType.public_thread, ChannelType.private_thread)}¶
Maps Python channel annotations/typehints to Discord ChannelType values.
- verify()¶
This should run through
SlashOptionvariables and raise errors when conflicting data is given.
- from_autocomplete_callback(callback)¶
Parses a callback meant to be the autocomplete function.
- await invoke_autocomplete_callback(interaction, option_value, **kwargs)¶
This function is a coroutine. Invokes the autocomplete callback, injecting
selfif available.
- property payload¶
Returns a dict payload made of the attributes of the option to be sent to Discord.
- Type:
- functional_name¶
Name of the kwarg in the function/method
- class nextcord.Range¶
An annotation helper for defining slash command
min_valueandmax_valueparameters.Added in version 2.2.
- Range[x, y]
Creates a range from
xtoy.
- Range[x] | Range[..., x]
Create a range up to
x.
- Range[x, ...]
Create a range from
x.
- class nextcord.String¶
An annotation helper for defining slash command
min_lengthandmax_lengthparameters.Added in version 2.2.
- String[x, y]
Creates a range of string length from
xtoy.
- String[x] | String[..., x]
Create a range of string length up to
x.
- String[x, ...]
Create a range of string length from
x.
User Commands¶
- defadd_check
- defadd_guild_rollout
- defafter_invoke
- defbefore_invoke
- asynccall
- asynccall_from_interaction
- asynccan_run
- deferror
- deffrom_callback
- defget_payload
- defget_rollout_signatures
- defget_signature
- defget_signatures
- defhas_error_handler
- asyncinvoke_callback
- asyncinvoke_callback_with_hooks
- asyncinvoke_error
- defis_interaction_valid
- defis_payload_valid
- defparse_discord_response
- defremove_check
- class nextcord.UserApplicationCommand(name=None, *, name_localizations=None, callback=None, guild_ids=None, default_member_permissions=None, nsfw=False, integration_types=None, contexts=None, parent_cog=None, force_global=False)¶
Class representing a user context menu command.
- add_check(func)¶
Adds a check to the application command. Returns the application command for method chaining.
- Parameters:
func (
ApplicationCheck) – The function that will be used as a check.
- add_guild_rollout(guild)¶
Adds a Guild to the command to be rolled out to when the rollout is run.
- after_invoke(coro)¶
Sets the callback that should be run after the command callback is invoked.
- Parameters:
coro (Callable[[
Interaction], Coroutine]) – Coroutine to set as the after_invoke hook.- Returns:
The coroutine to allow multiple commands to share the function.
- Return type:
Callable[[
Interaction], Coroutine]
- before_invoke(coro)¶
Sets the callback that should be run before the command callback is invoked.
- Parameters:
coro (Callable[[
Interaction], Coroutine]) – Coroutine to set as the before_invoke hook.- Returns:
The coroutine to allow multiple commands to share the function.
- Return type:
Callable[[
Interaction], Coroutine]
- await call_from_interaction(interaction)¶
This function is a coroutine. Calls the callback via the given
Interaction, relying on the locally storedConnectionStateobject.- Parameters:
interaction (
Interaction) – Interaction corresponding to the use of the command.
- await can_run(interaction)¶
This function is a coroutine.
Checks if the command can be executed by checking all the predicates inside the
checksattribute, as well as all global and cog checks.- Parameters:
interaction (
Interaction) – The interaction of the command currently being invoked.- Raises:
ApplicationError – Any application command error that was raised during a check call will be propagated by this function.
- Returns:
A boolean indicating if the command can be invoked.
- Return type:
- property cog_after_invoke¶
Returns the cog_application_command_after_invoke method for the cog that this command is in.
- Returns:
after_invokemethod from the parent cog.Noneif not the method is not found.- Return type:
Optional[
ApplicationHook]
- property cog_before_invoke¶
Returns the cog_application_command_before_invoke method for the cog that this command is in. Returns
Noneif not the method is not found.- Returns:
before_invokemethod from the parent cog.Noneif not the method is not found.- Return type:
Optional[
ApplicationHook]
- error(callback)¶
Decorates a function, setting it as a callback to be called when a
ApplicationErroror any of its subclasses is raised inside theApplicationCommand.- Parameters:
callback (Callable[[
Interaction,ApplicationError],asyncio.Awaitable[Any]]) – The callback to call when an error occurs.
- property error_name¶
Returns a string containing the class name, command name, and the callback to use in raising exceptions.
Examples
>>> print(app_cmd.error_name) SlashApplicationCommand reloadme <function TinyTest.reloadme at 0x7f4b3b563e20>
- Returns:
String containing the class name, command name, and callback object.
- Return type:
- get_payload(guild_id)¶
Makes an Application Command payload for this command to upsert to Discord with the given Guild ID.
- get_rollout_signatures()¶
Returns all signatures that this command wants to roll out to.
Command signatures are made up of the command name, command type, and Guild ID (
Nonefor global).
- get_signature(guild_id=None)¶
Returns a command signature with the given guild ID.
- get_signatures()¶
Returns all the signatures that this command has.
Command signatures are made up of the command name, command type, and Guild ID (
Nonefor global).
- await invoke_callback(interaction, *args, **kwargs)¶
This function is a coroutine. Invokes the callback, injecting
selfif available.
- await invoke_callback_with_hooks(state, interaction, args=None, kwargs=None)¶
This function is a coroutine. Invokes the callback with all hooks and checks.
- await invoke_error(interaction, error)¶
This function is a coroutine. Invokes the error handler if available.
- property is_guild¶
Returns
Trueif this command is or should be registered to any guilds.- Type:
- is_interaction_valid(interaction)¶
Checks if the interaction given is possibly valid for this command. If the command has more parameters (especially optionals) than the interaction coming in, this may cause a desync between your bot and Discord.
- Parameters:
interaction (
Interaction) – Interaction to validate.- Returns:
TrueIf the interaction could possibly be for this command,Falseotherwise.- Return type:
- is_payload_valid(raw_payload, guild_id=None)¶
Checks if the given raw application command interaction payload from Discord is possibly valid for this command. Note that while this may return
Truefor a given payload, that doesn’t mean that the payload is fully correct for this command. Discord doesn’t send data for parameters that are optional and aren’t supplied by the user.- Parameters:
- Returns:
Trueif the given payload is possibly valid for this command.Falseotherwise.- Return type:
- parse_discord_response(state, data)¶
Parses the application command creation/update response from Discord.
- Parameters:
state (
ConnectionState) – Connection state to use internally in the command.data (Union[
ApplicationCommandInteractionData,ApplicationCommand]) – Raw dictionary data from Discord.
- property qualified_name¶
Retrieves the fully qualified command name.
Added in version 2.1.
- Type:
- remove_check(func)¶
Removes a check from the ApplicationCommand. Returns the application command for method chaining.
This function is idempotent and will not raise an exception if the function is not in the command’s checks.
- Parameters:
func (
ApplicationCheck) – The function to remove from the checks.
- property required_bot_guild_permissions¶
Returns the permissions the bot needs to have in this guild in order to run this command.
Note
This returns the permissions set with
ext.application_checks.bot_has_guild_permissions().Added in version 2.6.
- property required_bot_permissions¶
Returns the permissions the bot needs to run this command.
Note
This returns the permissions set with
ext.application_checks.bot_has_permissions().Added in version 2.6.
- property required_guild_permissions¶
Returns the guild permissions needed to run this command.
Note
This returns the permissions set with
ext.application_checks.has_guild_permissions().Added in version 2.6.
- property required_permissions¶
Returns the permissions required to run this command.
Note
This returns the permissions set with
ext.application_checks.has_permissions().Added in version 2.6.
- command_ids¶
Dict[Optional[
int],int]: Command IDs that this application command currently has. Schema: {Guild ID (None for global): command ID}
- property description¶
The description the command should have in Discord. Should be 1-100 characters long.
- await call(state, interaction)¶
This function is a coroutine. Calls the callback via the given
Interaction, using the givenConnectionStateto get resolved objects if needed and available.- Parameters:
state (
ConnectionState) – State object to get resolved objects from.interaction (
Interaction) – Interaction corresponding to the use of the command.
- from_callback(callback=None, option_class=None)¶
Creates objects of type
option_classwith the parameters of the function, and stores them in the options attribute.- Parameters:
callback (Optional[
Callable]) – Callback to create options from. Must be a coroutine function.option_class (Optional[Type[
BaseCommandOption]]) – Class to create the options using. Should either be or subclassBaseCommandOption. Defaults toBaseCommandOption.
- Returns:
Self for possible chaining.
- Return type:
CallbackMixin
Message Commands¶
- defadd_check
- defadd_guild_rollout
- defafter_invoke
- defbefore_invoke
- asynccall
- asynccall_from_interaction
- asynccan_run
- deferror
- deffrom_callback
- defget_payload
- defget_rollout_signatures
- defget_signature
- defget_signatures
- defhas_error_handler
- asyncinvoke_callback
- asyncinvoke_callback_with_hooks
- asyncinvoke_error
- defis_interaction_valid
- defis_payload_valid
- defparse_discord_response
- defremove_check
- class nextcord.MessageApplicationCommand(name=None, *, name_localizations=None, callback=None, guild_ids=None, default_member_permissions=None, nsfw=False, integration_types=None, contexts=None, parent_cog=None, force_global=False)¶
Class representing a message context menu command.
- add_check(func)¶
Adds a check to the application command. Returns the application command for method chaining.
- Parameters:
func (
ApplicationCheck) – The function that will be used as a check.
- add_guild_rollout(guild)¶
Adds a Guild to the command to be rolled out to when the rollout is run.
- after_invoke(coro)¶
Sets the callback that should be run after the command callback is invoked.
- Parameters:
coro (Callable[[
Interaction], Coroutine]) – Coroutine to set as the after_invoke hook.- Returns:
The coroutine to allow multiple commands to share the function.
- Return type:
Callable[[
Interaction], Coroutine]
- before_invoke(coro)¶
Sets the callback that should be run before the command callback is invoked.
- Parameters:
coro (Callable[[
Interaction], Coroutine]) – Coroutine to set as the before_invoke hook.- Returns:
The coroutine to allow multiple commands to share the function.
- Return type:
Callable[[
Interaction], Coroutine]
- await call_from_interaction(interaction)¶
This function is a coroutine. Calls the callback via the given
Interaction, relying on the locally storedConnectionStateobject.- Parameters:
interaction (
Interaction) – Interaction corresponding to the use of the command.
- await can_run(interaction)¶
This function is a coroutine.
Checks if the command can be executed by checking all the predicates inside the
checksattribute, as well as all global and cog checks.- Parameters:
interaction (
Interaction) – The interaction of the command currently being invoked.- Raises:
ApplicationError – Any application command error that was raised during a check call will be propagated by this function.
- Returns:
A boolean indicating if the command can be invoked.
- Return type:
- property cog_after_invoke¶
Returns the cog_application_command_after_invoke method for the cog that this command is in.
- Returns:
after_invokemethod from the parent cog.Noneif not the method is not found.- Return type:
Optional[
ApplicationHook]
- property cog_before_invoke¶
Returns the cog_application_command_before_invoke method for the cog that this command is in. Returns
Noneif not the method is not found.- Returns:
before_invokemethod from the parent cog.Noneif not the method is not found.- Return type:
Optional[
ApplicationHook]
- error(callback)¶
Decorates a function, setting it as a callback to be called when a
ApplicationErroror any of its subclasses is raised inside theApplicationCommand.- Parameters:
callback (Callable[[
Interaction,ApplicationError],asyncio.Awaitable[Any]]) – The callback to call when an error occurs.
- property error_name¶
Returns a string containing the class name, command name, and the callback to use in raising exceptions.
Examples
>>> print(app_cmd.error_name) SlashApplicationCommand reloadme <function TinyTest.reloadme at 0x7f4b3b563e20>
- Returns:
String containing the class name, command name, and callback object.
- Return type:
- get_payload(guild_id)¶
Makes an Application Command payload for this command to upsert to Discord with the given Guild ID.
- get_rollout_signatures()¶
Returns all signatures that this command wants to roll out to.
Command signatures are made up of the command name, command type, and Guild ID (
Nonefor global).
- get_signature(guild_id=None)¶
Returns a command signature with the given guild ID.
- get_signatures()¶
Returns all the signatures that this command has.
Command signatures are made up of the command name, command type, and Guild ID (
Nonefor global).
- await invoke_callback(interaction, *args, **kwargs)¶
This function is a coroutine. Invokes the callback, injecting
selfif available.
- await invoke_callback_with_hooks(state, interaction, args=None, kwargs=None)¶
This function is a coroutine. Invokes the callback with all hooks and checks.
- await invoke_error(interaction, error)¶
This function is a coroutine. Invokes the error handler if available.
- property is_guild¶
Returns
Trueif this command is or should be registered to any guilds.- Type:
- is_interaction_valid(interaction)¶
Checks if the interaction given is possibly valid for this command. If the command has more parameters (especially optionals) than the interaction coming in, this may cause a desync between your bot and Discord.
- Parameters:
interaction (
Interaction) – Interaction to validate.- Returns:
TrueIf the interaction could possibly be for this command,Falseotherwise.- Return type:
- is_payload_valid(raw_payload, guild_id=None)¶
Checks if the given raw application command interaction payload from Discord is possibly valid for this command. Note that while this may return
Truefor a given payload, that doesn’t mean that the payload is fully correct for this command. Discord doesn’t send data for parameters that are optional and aren’t supplied by the user.- Parameters:
- Returns:
Trueif the given payload is possibly valid for this command.Falseotherwise.- Return type:
- parse_discord_response(state, data)¶
Parses the application command creation/update response from Discord.
- Parameters:
state (
ConnectionState) – Connection state to use internally in the command.data (Union[
ApplicationCommandInteractionData,ApplicationCommand]) – Raw dictionary data from Discord.
- property qualified_name¶
Retrieves the fully qualified command name.
Added in version 2.1.
- Type:
- remove_check(func)¶
Removes a check from the ApplicationCommand. Returns the application command for method chaining.
This function is idempotent and will not raise an exception if the function is not in the command’s checks.
- Parameters:
func (
ApplicationCheck) – The function to remove from the checks.
- property required_bot_guild_permissions¶
Returns the permissions the bot needs to have in this guild in order to run this command.
Note
This returns the permissions set with
ext.application_checks.bot_has_guild_permissions().Added in version 2.6.
- property required_bot_permissions¶
Returns the permissions the bot needs to run this command.
Note
This returns the permissions set with
ext.application_checks.bot_has_permissions().Added in version 2.6.
- property required_guild_permissions¶
Returns the guild permissions needed to run this command.
Note
This returns the permissions set with
ext.application_checks.has_guild_permissions().Added in version 2.6.
- property required_permissions¶
Returns the permissions required to run this command.
Note
This returns the permissions set with
ext.application_checks.has_permissions().Added in version 2.6.
- command_ids¶
Dict[Optional[
int],int]: Command IDs that this application command currently has. Schema: {Guild ID (None for global): command ID}
- property description¶
The description the command should have in Discord. Should be 1-100 characters long.
- await call(state, interaction)¶
This function is a coroutine. Calls the callback via the given
Interaction, using the givenConnectionStateto get resolved objects if needed and available.- Parameters:
state (
ConnectionState) – State object to get resolved objects from.interaction (
Interaction) – Interaction corresponding to the use of the command.
- from_callback(callback=None, option_class=None)¶
Creates objects of type
option_classwith the parameters of the function, and stores them in the options attribute.- Parameters:
callback (Optional[
Callable]) – Callback to create options from. Must be a coroutine function.option_class (Optional[Type[
BaseCommandOption]]) – Class to create the options using. Should either be or subclassBaseCommandOption. Defaults toBaseCommandOption.
- Returns:
Self for possible chaining.
- Return type:
CallbackMixin
Command Helpers¶
- class nextcord.CallbackWrapper(callback, *args, **kwargs)¶
A class used to wrap a callback in a sane way to modify aspects of application commands.
By creating a decorator that makes this class wrap a function or an application command, you can easily modify attributes of the command regardless if this wraps the callback or the application command, and without needing to make the application command object interpret arbitrarily set function attributes.
The
modifymethod must be overridden.This handles both multiple layers of wrappers, or if it wraps around a
BaseApplicationCommand- Parameters:
callback (Union[Callable,
CallbackWrapper,BaseApplicationCommand]) – Callback, other callback wrapper, or application command to wrap and/or modify.
Examples
Creating a decorator that makes the description of the command uppercase, and offers an “override” argument:
def upper_description(description_override: str = None): class UpperDescription(CallbackWrapper): def modify(self, app_cmd): if description_override is not None: app_cmd.description = description_override.upper() elif app_cmd.description: app_cmd.description = app_cmd.description.upper() def wrapper(func): return UpperDescription(func) return wrapper @client.slash_command(description="This will be made uppercase.") @upper_description() async def test(interaction): await interaction.send("The description of this command should be in all uppercase!")
- class nextcord.OptionConverter(option_type=<class 'str'>)¶
Based on, in basic functionality, the
ext.commandsConverter. Users subclass this and use convert to provide custom “typings” for slash commands.The
convertmethod MUST be overridden to convert the value from Discord to the desired value. Themodifymethod MAY be overridden to modify theBaseCommandOption.- await convert(interaction, value)¶
This function is a coroutine. Called to convert a value received from Discord to the desired value.
If you do not wish to do any conversion, simply
returnthevalue- Parameters:
interaction (
Interaction) – Interaction associated with the usage of the application command.value (Any) – Value received from Discord.
- Returns:
Converted value to forward to the callback.
- Return type:
Any
- modify(option)¶
Called when the command is being parsed to allow for option modification.
- Parameters:
option (
BaseCommandOption) – Command option that’s being created.
- asyncconvert
- class nextcord.Mentionable¶
When a parameter is typehinted with this, it allows users to select both roles and members.
- await convert(interaction, value)¶
This function is a coroutine. Called to convert a value received from Discord to the desired value.
If you do not wish to do any conversion, simply
returnthevalue- Parameters:
interaction (
Interaction) – Interaction associated with the usage of the application command.value (Any) – Value received from Discord.
- Returns:
Converted value to forward to the callback.
- Return type:
Any
Decorators¶
- class nextcord.message_command(name=None, *, name_localizations=None, guild_ids=..., default_member_permissions=None, nsfw=False, integration_types=None, contexts=None, force_global=False)¶
Creates a Message context command from the decorated function. Used inside
ClientCog’s or something that subclasses it.- Parameters:
name (
str) – Name of the command that users will see. If not set, it defaults to the name of the callback.name_localizations (Dict[Union[
Locale,str],str]) – Name(s) of the command for users of specific locales. The locale code should be the key, with the localized name as the valueguild_ids (Optional[Iterable[
int]]) – IDs ofGuild’s to add this command to. If not passed andClient.default_guild_idsis set, then those default guild ids will be used instead. If both of those are unset, then the command will be a global command.default_member_permissions (Optional[Union[
Permissions,int]]) – Permission(s) required to use the command. Inputting8orPermissions(administrator=True)for example will only allow Administrators to use the command. If set to 0, nobody will be able to use it by default. Server owners CAN override the permission requirements.nsfw (
bool) –Whether the command can only be used in age-restricted channels. Defaults to
False.Added in version 2.4.
integration_types (Optional[Iterable[Union[
IntegrationType,int]]]) –Where the command is available, only for globally-scoped commands. Defaults to
guild_install.Added in version 3.0.
contexts (Optional[Iterable[Union[
InteractionContextType,int]]]) –Where the command can be used, only for globally-scoped commands. By default, all interaction context types included for new commands.
Added in version 3.0.
force_global (
bool) – If True, will force this command to register as a global command, even ifguild_idsis set. Will still register to guilds. Has no effect ifguild_idsare never set or added to.
- class nextcord.slash_command(name=None, description=None, *, name_localizations=None, description_localizations=None, guild_ids=..., default_member_permissions=None, nsfw=False, integration_types=None, contexts=None, force_global=False)¶
Creates a Slash application command from the decorated function. Used inside
ClientCog’s or something that subclasses it.- Parameters:
name (
str) – Name of the command that users will see. If not set, it defaults to the name of the callback.description (
str) – Description of the command that users will see. If not specified, the docstring will be used. If no docstring is found for the command callback, it defaults to “No description provided”.name_localizations (Dict[Union[
Locale,str],str]) – Name(s) of the command for users of specific locales. The locale code should be the key, with the localized name as the value.description_localizations (Dict[Union[
Locale,str],str]) – Description(s) of the subcommand for users of specific locales. The locale code should be the key, with the localized description as the value.guild_ids (Optional[Iterable[
int]]) – IDs ofGuild’s to add this command to. If not passed andClient.default_guild_idsis set, then those default guild ids will be used instead. If both of those are unset, then the command will be a global command.default_member_permissions (Optional[Union[
Permissions,int]]) – Permission(s) required to use the command. Inputting8orPermissions(administrator=True)for example will only allow Administrators to use the command. If set to 0, nobody will be able to use it by default. Server owners CAN override the permission requirements.nsfw (
bool) –Whether the command can only be used in age-restricted channels. Defaults to
False.Note
Due to a discord limitation, this can only be set for the parent command in case of a subcommand.
Added in version 2.4.
integration_types (Optional[Iterable[Union[
IntegrationType,int]]]) –Where the command is available, only for globally-scoped commands. Defaults to
guild_install.Added in version 3.0.
contexts (Optional[Iterable[Union[
InteractionContextType,int]]]) –Where the command can be used, only for globally-scoped commands. By default, all interaction context types included for new commands.
Added in version 3.0.
force_global (
bool) – If True, will force this command to register as a global command, even ifguild_idsis set. Will still register to guilds. Has no effect ifguild_idsare never set or added to.
- class nextcord.user_command(name=None, *, name_localizations=None, guild_ids=..., default_member_permissions=None, nsfw=False, integration_types=None, contexts=None, force_global=False)¶
Creates a User context command from the decorated function. Used inside
ClientCog’s or something that subclasses it.- Parameters:
name (
str) – Name of the command that users will see. If not set, it defaults to the name of the callback.name_localizations (Dict[Union[
Locale,str],str]) – Name(s) of the command for users of specific locales. The locale code should be the key, with the localized name as the valueguild_ids (Optional[Iterable[
int]]) – IDs ofGuild’s to add this command to. If not passed andClient.default_guild_idsis set, then those default guild ids will be used instead. If both of those are unset, then the command will be a global command.default_member_permissions (Optional[Union[
Permissions,int]]) – Permission(s) required to use the command. Inputting8orPermissions(administrator=True)for example will only allow Administrators to use the command. If set to 0, nobody will be able to use it by default. Server owners CAN override the permission requirements.nsfw (
bool) –Whether the command can only be used in age-restricted channels. Defaults to
False.Added in version 2.4.
integration_types (Optional[Iterable[Union[
IntegrationType,int]]]) –Where the command is available, only for globally-scoped commands. Defaults to
guild_install.Added in version 3.0.
contexts (Optional[Iterable[Union[
InteractionContextType,int]]]) –Where the command can be used, only for globally-scoped commands. By default, all interaction context types included for new commands.
Added in version 3.0.
force_global (
bool) – If True, will force this command to register as a global command, even ifguild_idsis set. Will still register to guilds. Has no effect ifguild_idsare never set or added to.
Cogs¶
- class nextcord.ClientCog(*_args, **_kwargs)¶
- has_application_command_error_handler()¶
bool: Checks whether the cog has an error handler for application commands.Added in version 3.0.
- property application_commands¶
Provides the list of application commands in this cog. Subcommands are not included.
- process_app_cmds()¶
Formats all added application commands with their callback.
- cog_application_command_check(interaction)¶
A special method that registers as a
ext.application_checks.check()for every application command and subcommand in this cog.This function can be a coroutine and must take a sole parameter,
interaction, to represent theInteraction.
- await cog_application_command_error(interaction, error)¶
A special method that is called whenever an error is dispatched inside this cog.
This is similar to
on_application_command_error()except only applying to the commands inside this cog.This must be a coroutine.
Added in version 3.0.
- Parameters:
interaction (
Interaction) – The Interaction where the error happened.error (
ApplicationError) – The error that happened.
- await cog_application_command_before_invoke(interaction)¶
A special method that acts as a cog local pre-invoke hook.
This is similar to
ApplicationCommand.before_invoke().This must be a coroutine.
- Parameters:
interaction (
Interaction) – The invocation interaction.
- await cog_application_command_after_invoke(interaction)¶
A special method that acts as a cog local post-invoke hook.
This is similar to
Command.after_invoke().This must be a coroutine.
- Parameters:
interaction (
Interaction) – The invocation interaction.
Warnings¶
- class nextcord.MissingApplicationCommandParametersWarning¶
Warning category raised when creating a slash command from a callback when it appears the self and/or interaction parameter is missing based on the given type annotations.
This warning can be silenced using
warnings.simplefilter().import warnings from nextcord import MissingApplicationCommandParametersWarning warnings.simplefilter("ignore", MissingApplicationCommandParametersWarning)
Exceptions¶
The following exceptions are thrown by the library.
- exception nextcord.DiscordException¶
Base exception class for nextcord
Ideally speaking, this could be caught to handle any exceptions raised from this library.
- exception nextcord.ClientException¶
Exception that’s raised when an operation in the
Clientfails.These are usually for exceptions that happened due to user input.
- exception nextcord.LoginFailure¶
Exception that’s raised when the
Client.login()function fails to log you in from improper credentials or some other misc. failure.
- exception nextcord.NoMoreItems¶
Exception that is raised when an async iteration operation has no more items.
- exception nextcord.HTTPException(response, message)¶
Exception that’s raised 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 nextcord.Forbidden(response, message)¶
Exception that’s raised for when status code 403 occurs.
Subclass of
HTTPException
- exception nextcord.NotFound(response, message)¶
Exception that’s raised for when status code 404 occurs.
Subclass of
HTTPException
- exception nextcord.DiscordServerError(response, message)¶
Exception that’s raised for when a 500 range status code occurs.
Subclass of
HTTPException.Added in version 1.5.
- exception nextcord.InvalidData¶
Exception that’s raised when the library encounters unknown or invalid data from Discord.
- exception nextcord.InvalidArgument¶
Exception that’s raised when an argument to a function is invalid some way (e.g. wrong value or wrong type).
This could be considered the analogous of
ValueErrorandTypeErrorexcept inherited fromClientExceptionand thusDiscordException.
- exception nextcord.GatewayNotFound¶
An exception that is raised when the gateway for Discord could not be found
- exception nextcord.ConnectionClosed(socket, *, shard_id, code=None)¶
Exception that’s raised when the gateway connection is closed for reasons that could not be handled internally.
- exception nextcord.PrivilegedIntentsRequired(shard_id)¶
Exception that’s raised 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:
- exception nextcord.InteractionResponded(interaction)¶
Exception that’s raised when sending another interaction response using
InteractionResponsewhen one has already been done before.An interaction can only respond once.
Added in version 2.0.
- interaction¶
The interaction that’s already been responded to.
- Type:
- exception nextcord.opus.OpusError(code)¶
An exception that is thrown for libopus related errors.
- exception nextcord.opus.OpusNotLoaded¶
An exception that is thrown for when libopus is not loaded.
- exception nextcord.HTTPInternalCancelled¶
Exception that’s raised when an HTTP request is internally cancelled before the actual request is made.
- exception nextcord.HTTPInternalRatelimitLocked¶
Exception that’s raised when an internally tracked ratelimit, global or route, would be exceeded by the request.
Subclass of
HTTPInternalCancelled
- exception nextcord.ApplicationError(message=None, *args)¶
The base exception type for all command related errors.
This inherits from
nextcord.DiscordException.This exception and exceptions inherited from it are handled in a special way as they are caught and passed into a special event from
Bot,on_command_error().
- exception nextcord.ApplicationInvokeError(e)¶
Exception raised when the command being invoked raised an exception.
This inherits from
ApplicationError
- exception nextcord.ApplicationCheckFailure(message=None, *args)¶
Exception raised when the predicates in
BaseApplicationCommand.checkshave failed.This inherits from
ApplicationError
- exception nextcord.ApplicationCommandOptionMissing(message=None, *args)¶
Raised when an option that’s supposed to be part of an application command is missing on our end.