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

Methods
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 in None disables the message cache.

    Changed in version 1.3: Allow disabling the message cache and change the default size to 1000.

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

  • connector (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 at 0 and less than shard_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 Intents class.

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

    New 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 is True if Intents.members is True.

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

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

    New 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 is False then your system clock is used to calculate how long to sleep for. If this is set to False it is recommended to sync your system clock to Google’s NTP server.

    New 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() and on_socket_raw_send(). If this is False then those events will not be dispatched (due to performance considerations). To enable these events, this must be set to True. Defaults to False.

    New 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 to True.

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

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

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

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

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

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

Type:

asyncio.AbstractEventLoop

@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, TypeError is 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=..., dm_permission=None, nsfw=False, default_member_permissions=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 of Guild’s to add this command to. If not passed and Client.default_guild_ids is set, then those default guild ids will be used instead. If both of those are unset, then the command will be a global command.

  • dm_permission (bool) – If the command should be usable in DMs or not. Setting to False will disable the command from being usable in DMs. Only for global commands, but will not error on guild.

  • default_member_permissions (Optional[Union[Permissions, int]]) – Permission(s) required to use the command. Inputting 8 or Permissions(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.

    New in version 2.4.

  • force_global (bool) – If True, will force this command to register as a global command, even if guild_ids is set. Will still register to guilds. Has no effect if guild_ids are never set or added to.

@user_command(name=None, *, name_localizations=None, guild_ids=..., dm_permission=None, default_member_permissions=None, nsfw=False, 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 value

  • guild_ids (Optional[Iterable[int]]) – IDs of Guild’s to add this command to. If not passed and Client.default_guild_ids is set, then those default guild ids will be used instead. If both of those are unset, then the command will be a global command.

  • dm_permission (bool) – If the command should be usable in DMs or not. Setting to False will disable the command from being usable in DMs. Only for global commands, but will not error on guild.

  • default_member_permissions (Optional[Union[Permissions, int]]) – Permission(s) required to use the command. Inputting 8 or Permissions(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.

    New in version 2.4.

  • force_global (bool) – If True, will force this command to register as a global command, even if guild_ids is set. Will still register to guilds. Has no effect if guild_ids are never set or added to.

@message_command(name=None, *, name_localizations=None, guild_ids=..., dm_permission=None, default_member_permissions=None, nsfw=False, 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 value

  • guild_ids (Optional[Iterable[int]]) – IDs of Guild’s to add this command to. If not passed and Client.default_guild_ids is set, then those default guild ids will be used instead. If both of those are unset, then the command will be a global command.

  • dm_permission (bool) – If the command should be usable in DMs or not. Setting to False will disable the command from being usable in DMs. Only for global commands, but will not error on guild.

  • default_member_permissions (Optional[Union[Permissions, int]]) – Permission(s) required to use the command. Inputting 8 or Permissions(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.

    New in version 2.4.

  • force_global (bool) – If True, will force this command to register as a global command, even if guild_ids is set. Will still register to guilds. Has no effect if guild_ids are never set or added to.

async for ... in fetch_guilds(*, limit=200, with_counts=False, before=None, after=None)

Retrieves an AsyncIterator that enables receiving your guilds.

Note

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

Note

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

Examples

Usage

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

Flattening into a list

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

All parameters are optional.

Parameters:
  • limit (Optional[int]) –

    The number of guilds to retrieve. If None, it retrieves every guild you have access to. Note, however, that this would make it a slow operation. Defaults to 200.

    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.

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

float

is_ws_ratelimited()

bool: Whether the websocket is currently rate limited.

This can be useful to know when deciding whether you should query members using HTTP or via the gateway.

New in version 1.6.

property user

Represents the connected client. None if not logged in.

Type:

Optional[ClientUser]

property guilds

The guilds that the connected client is a member of.

Type:

List[Guild]

property emojis

The emojis that the connected client has.

Type:

List[Emoji]

property stickers

The stickers that the connected client has.

New in version 2.0.

Type:

List[GuildSticker]

property cached_messages

Read-only list of messages the connected client has cached.

New in version 1.1.

Type:

Sequence[Message]

property private_channels

The private channels that the connected client is participating on.

Note

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

Type:

List[abc.PrivateChannel]

property voice_clients

Represents a list of voice connections.

These are usually VoiceClient instances.

Type:

List[VoiceProtocol]

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 after on_connect() is called.

New in version 2.0.

Type:

Optional[int]

property application_flags

The client’s application flags.

New in version 2.0.

Type:

ApplicationFlags

property default_guild_ids

List[int] The default guild ids for all application commands.

New in version 2.3.

is_ready()

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

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

This function is a coroutine.

The default error handler provided by the client.

By default this prints to stderr however it could be overridden to have a different implementation. Check on_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 stderr however 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.

New in version 1.4.

Parameters:
  • shard_id (int) – The shard ID that requested being IDENTIFY’d

  • initial (bool) – Whether this IDENTIFY is the first initial IDENTIFY.

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

This function is a coroutine.

Closes the connection to Discord.

clear()

Clears the internal state of the bot.

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

await start(token, *, reconnect=True)

This function is a coroutine.

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

Raises:

TypeError – An unexpected keyword argument was received.

run(*args, **kwargs)

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

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

Roughly Equivalent to:

try:
    loop.run_until_complete(start(*args, **kwargs))
except KeyboardInterrupt:
    loop.run_until_complete(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.

is_closed()

bool: Indicates if the websocket connection is closed.

property activity

The activity being used upon logging in.

Type:

Optional[BaseActivity]

property status

Status: The status being used upon logging on to Discord.

property allowed_mentions

The allowed mention configuration.

New in version 1.4.

Type:

Optional[AllowedMentions]

property intents

The intents configured for this connection.

New in version 1.5.

Type:

Intents

property users

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

Type:

List[User]

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

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

PartialMessageable

get_stage_instance(id, /)

Returns a stage instance with the given stage channel ID.

New in version 2.0.

Parameters:

id (int) – The ID to search for.

Returns:

The returns stage instance of None if not found.

Return type:

Optional[StageInstance]

get_guild(id, /)

Returns a guild with the given ID.

Parameters:

id (int) – The ID to search for.

Returns:

The guild or None if not found.

Return type:

Optional[Guild]

get_user(id, /)

Returns a user with the given ID.

Parameters:

id (int) – The ID to search for.

Returns:

The user or None if not found.

Return type:

Optional[User]

get_emoji(id, /)

Returns an emoji with the given ID.

Parameters:

id (int) – The ID to search for.

Returns:

The custom emoji or None if not found.

Return type:

Optional[Emoji]

get_sticker(id, /)

Returns a guild sticker with the given ID.

New in version 2.0.

Note

To retrieve standard stickers, use fetch_sticker(). or fetch_premium_sticker_packs().

Returns:

The sticker or None if not found.

Return type:

Optional[GuildSticker]

get_scheduled_event(id, /)

Returns a scheduled event with the given ID.

New in version 2.0.

Parameters:

id (int) – The scheduled event’s ID to search for.

Returns:

The scheduled event or None if not found.

Return type:

Optional[ScheduledEvent]

for ... in get_all_channels()

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

This is equivalent to:

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

Note

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

Yields:

abc.GuildChannel – A channel the client can ‘access’.

for ... in get_all_members()

Returns a generator with every Member the client can see.

This is equivalent to:

for guild in client.guilds:
    for member in guild.members:
        yield member
Yields:

Member – A member the client can see.

await wait_until_ready()

This function is a coroutine.

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

wait_for(event, *, check=None, timeout=None)

This function is a coroutine.

Waits for a WebSocket event to be dispatched.

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

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

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

This function returns the first event that meets the requirements.

Examples

Waiting for a user reply:

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

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

        msg = await client.wait_for('message', check=check)
        await channel.send(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 the on_ 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 raising asyncio.TimeoutError.

Raises:

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

Returns:

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

Return type:

Any

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 afk keyword-only parameter.

Parameters:
  • activity (Optional[BaseActivity]) – The activity being done. None if no currently active activity is done.

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

Raises:

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

await fetch_template(code)

This function is a coroutine.

Gets a Template from a discord.new URL or code.

Parameters:

code (Union[Template, str]) – The Discord Template Code or URL (must be a discord.new URL).

Raises:
  • .NotFound – The template is invalid.

  • .HTTPException – Getting the template failed.

Returns:

The template from the URL/code.

Return type:

Template

await fetch_guild(guild_id, /, *, with_counts=True)

This function is a coroutine.

Retrieves a Guild from an ID.

Note

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

Note

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

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

  • .HTTPException – Getting the guild failed.

Returns:

The guild from the ID.

Return type:

Guild

await fetch_guild_preview(guild_id, /)

This function is a coroutine.

Fetches a GuildPreview from an ID.

Note

This will only fetch guilds that the bot is in or that are discoverable.

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

GuildPreview

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 icon parameter now accepts File, Attachment, and Asset.

Parameters:
Raises:
  • .HTTPException – Guild creation failed.

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

Returns:

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

Return type:

Guild

await fetch_stage_instance(channel_id, /)

This function is a coroutine.

Gets a StageInstance for a stage channel id.

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

StageInstance

await fetch_invite(url, *, with_counts=True, with_expiration=True)

This function is a coroutine.

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

Note

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

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

  • .HTTPException – Getting the invite failed.

Returns:

The invite from the URL/ID.

Return type:

Invite

await delete_invite(invite)

This function is a coroutine.

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

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

Parameters:

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

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

  • .NotFound – The invite is invalid or expired.

  • .HTTPException – Revoking the invite failed.

await fetch_widget(guild_id, /)

This function is a coroutine.

Gets a Widget from a guild ID.

Note

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

Parameters:

guild_id (int) – The ID of the guild.

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

  • .HTTPException – Retrieving the widget failed.

Returns:

The guild’s widget.

Return type:

Widget

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:

AppInfo

await fetch_user(user_id, /)

This function is a coroutine.

Retrieves a User based 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.members and member cache enabled, consider get_user() instead.

Parameters:

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

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

  • .HTTPException – Fetching the user failed.

Returns:

The user you requested.

Return type:

User

await fetch_channel(channel_id, /)

This function is a coroutine.

Retrieves a abc.GuildChannel, abc.PrivateChannel, or Thread with the specified ID.

Note

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

New in version 1.2.

Raises:
  • .InvalidData – An unknown channel type was received from Discord.

  • .HTTPException – Retrieving the channel failed.

  • .NotFound – Invalid Channel ID.

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

Returns:

The channel from the ID.

Return type:

Union[abc.GuildChannel, abc.PrivateChannel, Thread]

await fetch_webhook(webhook_id, /)

This function is a coroutine.

Retrieves a Webhook with the specified ID.

Raises:
  • .HTTPException – Retrieving the webhook failed.

  • .NotFound – Invalid webhook ID.

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

Returns:

The webhook you requested.

Return type:

Webhook

await fetch_sticker(sticker_id, /)

This function is a coroutine.

Retrieves a Sticker with the specified ID.

New in version 2.0.

Raises:
  • .HTTPException – Retrieving the sticker failed.

  • .NotFound – Invalid sticker ID.

Returns:

The sticker you requested.

Return type:

Union[StandardSticker, GuildSticker]

await fetch_premium_sticker_packs()

This function is a coroutine.

Retrieves all available premium sticker packs.

New 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 DMChannel with this user.

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

New in version 2.0.

Parameters:

user (Snowflake) – The user to create a DM with.

Returns:

The channel that was created.

Return type:

DMChannel

add_view(view, *, message_id=None)

Registers a View for 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.

New 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 View from 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.

New 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 Modal for 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 Modal from 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.

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

property all_views

List[View] A sequence of all views added to the client.

New in version 2.6.

property persistent_views

A sequence of persistent views added to the client.

New in version 2.0.

Type:

List[View]

views(*, persistent=True)

Returns all persistent or non-persistent views.

New in version 2.6.

Parameters:

persistent (bool) – Whether or not we should grab persistent views. Defaults to True.

Returns:

The views requested.

Return type:

List[ui.View]

property scheduled_events

A list of scheduled events

New 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, None is returned instead.

Return type:

Optional[BaseApplicationCommand]

get_application_command_from_signature(name, cmd_type, guild_id)

Gets a locally stored application command object that matches the given signature.

Parameters:
  • name (str) – Name of the application command. Capital sensitive.

  • cmd_type (Union[int, ApplicationCommandType]) – Type of application command.

  • guild_id (Optional[int]) – Guild ID of the signature. If set to None, it will attempt to get the global signature.

Returns:

command – Application Command with the given signature. If no command with that signature is found, returns None instead.

Return type:

Optional[BaseApplicationCommand]

get_all_application_commands()

Returns a copied set of all added BaseApplicationCommand objects.

get_application_commands(rollout=False)

Gets registered global commands.

Parameters:

rollout (bool) – Whether unregistered/unassociated commands should be returned as well. Defaults to False

Returns:

List of BaseApplicationCommand objects 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 to False

  • use_rollout (bool) – If to apply the rollout signatures instead of existing ones. Defaults to False

  • pre_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 the int guild 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 to None

  • use_rollout (bool) – If the rollout guild IDs of commands should be used. Defaults to True

  • associate_known (bool) – If local commands that match a command already on Discord should be associated with each other. Defaults to True

  • delete_unknown (bool) – If commands on Discord that don’t match a local command should be deleted. Defaults to True

  • update_known (bool) – If commands on Discord have a basic match with a local command, but don’t fully match, should be updated. Defaults to True

  • register_new (bool) – If a local command that doesn’t have a basic match on Discord should be added to Discord. Defaults to True

  • ignore_forbidden (bool) – If this command should suppress a errors.Forbidden exception when the bot encounters a guild where it doesn’t have permissions to view application commands. Defaults to True

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.

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 as None, it will be fetched if needed. Defaults to None.

  • guild_id (Optional[int]) – ID of the guild to sync application commands with. If set to None, global commands will be synced instead. Defaults to None.

  • associate_known (bool) – If local commands that match a command already on Discord should be associated with each other. Defaults to True.

  • delete_unknown (bool) – If commands on Discord that don’t match a local command should be deleted. Defaults to True.

  • update_known (bool) – If commands on Discord have a basic match with a local command, but don’t fully match, should be updated. Defaults to True.

  • register_new (bool) – If a local command that doesn’t have a basic match on Discord should be added to Discord. Defaults to True.

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.

Parameters:
  • data (Optional[List[dict]]) – Payload from HTTPClient.get_guild_commands or HTTPClient.get_global_commands to deploy with. If None, the payload will be retrieved from Discord.

  • guild_id (Optional[int]) – Guild ID to deploy application commands to. If None, 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) – If True, commands on Discord that fail a signature check will be removed. If update_known is False, commands that pass the signature check but fail the deep check will also be removed.

  • update_known (bool) – If True, commands on Discord that pass a signature check but fail the deep check will be updated.

await delete_unknown_application_commands(data=None)

Deletes unknown global commands.

await associate_application_commands(data=None)

Associates global commands registered with Discord with locally added commands.

await update_application_commands(data=None)

Updates global commands that have slightly changed with Discord.

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 as None, it will be fetched if needed. Defaults to None

  • guild_id (Optional[int]) – ID of the guild to sync application commands with. If set to None, global commands will be synced instead. Defaults to None.

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 to None, the commands will be registered as global commands instead. Defaults to None.

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 to None, the commands will be deleted from global commands instead. Defaults to None.

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.

await rollout_application_commands()

This function is a coroutine. Deploys global application commands and registers new ones if enabled.

add_all_cog_commands()

Adds all ApplicationCommand objects inside added cogs to the application command list.

parse_mentions(text)

Parses user mentions in a string and returns a list of User objects.

Note

This does not include role or channel mentions. See Guild.parse_mentions for Member objects, Guild.parse_role_mentions for Role objects, and Guild.parse_channel_mentions for GuildChannel objects.

Note

Only cached users will be returned. To get the IDs of all users mentioned, use parse_raw_mentions() instead.

New in version 2.2.

Parameters:

text (str) – String to parse mentions in.

Returns:

List of User objects that were mentioned in the string.

Return type:

List[User]

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

Returns:

  • Interaction – An instance Interaction or 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 type Interaction and can only raise exceptions inherited from ApplicationError.

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() and application_command_after_invoke() hooks are only called if all checks pass without error. If any check fails, then the hooks are not called.

Parameters:

coro (coroutine) – The coroutine to register as the pre-invoke hook.

Raises:

TypeError – The coroutine passed is not actually a coroutine.

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.

Parameters:

coro (coroutine) – The coroutine to register as the post-invoke hook.

Raises:

TypeError – The coroutine passed is not actually a coroutine.

AutoShardedClient

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 Client except it handles the complications of sharding for the user into a more manageable and transparent single process bot.

When using this client, you will be able to use it as-if it was a regular Client with a single shard when implementation wise internally it is split up into multiple shards. This allows you to not have to deal with IPC or other complicated infrastructure.

It is recommended to use this client only if you have surpassed at least 1000 guilds.

If no shard_count is provided, then the library will use the Bot Gateway endpoint call to figure out how many shards to use.

If a shard_ids parameter is given, then those shard IDs will be used to launch the internal shards. Note that shard_count must be provided if this is used. By default, when omitted, the client will launch shards from 0 to shard_count - 1.

shard_ids

An optional list of shard_ids to launch the shards with.

Type:

Optional[List[int]]

property latency

Measures latency between a HEARTBEAT and a HEARTBEAT_ACK in seconds.

This operates similarly to Client.latency() except it uses the average latency of every shard’s latency. To get a list of shard latency, check the latencies property. Returns nan if there are no shards ready.

Type:

float

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

Type:

List[Tuple[int, float]]

get_shard(shard_id)

Optional[ShardInfo]: Gets the shard information at a given shard ID or None if 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 close()

This function is a coroutine.

Closes the connection to Discord.

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 afk keyword-only parameter.

Parameters:
  • activity (Optional[BaseActivity]) – The activity being done. None if no currently active activity is done.

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

  • shard_id (Optional[int]) – The shard_id to change the presence to. If not specified or None, then it will change the presence of every shard the bot can see.

Raises:

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

is_ws_ratelimited()

bool: Whether the websocket is currently rate limited.

This can be useful to know when deciding whether you should query members using HTTP or via the gateway.

This implementation checks if any of the shards are rate limited. For more granular control, consider ShardInfo.is_ws_ratelimited().

New in version 1.6.

Application Info

AppInfo

class nextcord.AppInfo

Represents the application info for the bot provided by Discord.

id

The application ID.

Type:

int

name

The application name.

Type:

str

owner

The application owner.

Type:

User

team

The application’s team.

New in version 1.3.

Type:

Optional[Team]

description

The application description.

Type:

str

bot_public

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

Type:

bool

bot_require_code_grant

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

Type:

bool

rpc_origins

A list of RPC origin URLs, if RPC is enabled.

Type:

Optional[List[str]]

verify_key

The hex encoded key for verification in interactions and the GameSDK’s GetTicket.

New in version 1.3.

Type:

str

terms_of_service_url

The application’s terms of service URL, if set.

New in version 2.0.

Type:

Optional[str]

privacy_policy_url

The application’s privacy policy URL, if set.

New in version 2.0.

Type:

Optional[str]

property icon

Retrieves the application’s icon asset, if any.

Type:

Optional[Asset]

PartialAppInfo

class nextcord.PartialAppInfo

Represents a partial AppInfo given by create_invite()

New in version 2.0.

id

The application ID.

Type:

int

name

The application name.

Type:

str

description

The application description.

Type:

str

rpc_origins

A list of RPC origin URLs, if RPC is enabled.

Type:

Optional[List[str]]

verify_key

The hex encoded key for verification in interactions and the GameSDK’s GetTicket.

Type:

str

terms_of_service_url

The application’s terms of service URL, if set.

Type:

Optional[str]

privacy_policy_url

The application’s privacy policy URL, if set.

Type:

Optional[str]

property icon

Retrieves the application’s icon asset, if any.

Type:

Optional[Asset]

Team

class nextcord.Team

Represents an application team for a bot provided by Discord.

id

The team ID.

Type:

int

name

The team name

Type:

str

owner_id

The team’s owner ID.

Type:

int

members

A list of the members in the team

New in version 1.3.

Type:

List[TeamMember]

property icon

Retrieves the team’s icon asset, if any.

Type:

Optional[Asset]

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.

New in version 1.3.

name

The team member’s username.

Type:

str

id

The team member’s unique ID.

Type:

int

discriminator

The team member’s discriminator. This is given when the username has conflicts.

Type:

str

avatar

The avatar hash the team member has. Could be None.

Type:

Optional[str]

bot

Specifies if the user is a bot account.

Type:

bool

team

The team that the member is from.

Type:

Team

membership_state

The membership state of the member (e.g. invited or accepted)

Type:

TeamMembershipState

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 by AutoShardedClient to denote when a particular shard ID has connected to Discord.

New in version 1.4.

Parameters:

shard_id (int) – The shard ID that has connected.

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 by AutoShardedClient to denote when a particular shard ID has disconnected from Discord.

New in version 1.4.

Parameters:

shard_id (int) – The shard ID that has disconnected.

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.

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

New 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.guilds and co. are filled up.

Warning

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

nextcord.on_shard_ready(shard_id)

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

Parameters:

shard_id (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 by AutoShardedClient to denote when a particular shard ID has resumed a session.

New in version 1.4.

Parameters:

shard_id (int) – The shard ID that has resumed.

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 Client class you can define an on_error handler consisting of a single empty raise statement. Exceptions raised by on_error will not be handled in any way by Client.

Note

on_error will only be dispatched to Client.event().

It will not be received by Client.wait_for(), or, if used, Bots listeners such as listen() or listener().

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.

New 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_events setting in the Client.

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_events setting in the Client.

Note

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

Parameters:

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

nextcord.on_typing(channel, user, when)

Called when someone begins typing a message.

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

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

This requires Intents.typing to be enabled.

Parameters:
  • channel (abc.Messageable) – The location where the typing originated from.

  • user (Union[User, Member]) – The user that started typing.

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

This requires Intents.typing to be enabled.

Parameters:

payload (RawTypingEvent) – The raw typing payload.

nextcord.on_message(message)

Called when a Message is created and sent.

This requires Intents.messages to be enabled.

Warning

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

Parameters:

message (Message) – The current message.

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_messages parameter or use the on_raw_message_delete() event instead.

This requires Intents.messages to 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_messages parameter or use the on_raw_bulk_message_delete() event instead.

This requires Intents.messages to 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_message

This requires Intents.messages to 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_messages

This requires Intents.messages to be enabled.

Parameters:

payload (RawBulkMessageDeleteEvent) – The raw event payload data.

nextcord.on_message_edit(before, after)

Called when a Message receives an update event. If the message is not found in the internal message cache, then these events will not be called. Messages might not be in cache if the message is too old or the client is participating in high traffic guilds.

If this occurs increase the max_messages parameter or use the on_raw_message_edit() event instead.

The following non-exhaustive cases trigger this event:

  • A message has been pinned or unpinned.

  • The message content has been changed.

  • The message has received an embed.

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

  • The message’s embeds were suppressed or unsuppressed.

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

This requires Intents.messages to be enabled.

Parameters:
  • before (Message) – The previous version of the message.

  • after (Message) – The current version of the message.

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 the on_raw_message_edit() coroutine, the RawMessageUpdateEvent.cached_message will return a Message object that represents the message before the content was modified.

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

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

This requires Intents.messages to be enabled.

Parameters:

payload (RawMessageUpdateEvent) – The raw event payload data.

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 using on_raw_reaction_add() instead.

Note

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

This requires Intents.reactions to be enabled.

Note

This doesn’t require Intents.members within a guild context, but due to Discord not providing updated user information in a direct message it’s required for direct messages to receive this event. Consider using on_raw_reaction_add() if you need this and do not otherwise want to enable the members intent.

Parameters:
  • reaction (Reaction) – The current state of the reaction.

  • user (Union[Member, User]) – The user who added the reaction.

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.reactions to 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.reactions and Intents.members to be enabled.

Note

Consider using on_raw_reaction_remove() if you need this and do not want to enable the members intent.

Parameters:
  • reaction (Reaction) – The current state of the reaction.

  • user (Union[Member, User]) – The user who added the reaction.

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.reactions to 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 using on_raw_reaction_clear() instead.

This requires Intents.reactions to be enabled.

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

  • reactions (List[Reaction]) – The reactions that were removed.

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.reactions to 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 using on_raw_reaction_clear_emoji() instead.

This requires Intents.reactions to be enabled.

New in version 1.3.

Parameters:

reaction (Reaction) – The reaction that got cleared.

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.reactions to be enabled.

New 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 View instead as it provides a nicer user experience.

New 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.messages to 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 be None.

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.guilds to 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.guilds to be enabled.

Parameters:
nextcord.on_guild_channel_pins_update(channel, last_pin)

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

This requires Intents.guilds to be enabled.

Parameters:
  • channel (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 be None.

nextcord.on_thread_create(thread)

Called when a thread is created.

New 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.guilds to 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.

New 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.guilds to 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.

New 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.guilds to be enabled.

New 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 ThreadMember leaves or joins a Thread.

You can get the thread a member belongs in by accessing ThreadMember.thread.

This requires Intents.members to be enabled.

New 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.guilds to be enabled.

New in version 2.0.

Parameters:
  • before (Thread) – The updated thread’s old info.

  • after (Thread) – The updated thread’s new info.

nextcord.on_guild_integrations_update(guild)

Called whenever an integration is created, modified, or removed from a guild.

This requires Intents.integrations to be enabled.

New 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.integrations to be enabled.

New 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.integrations to be enabled.

New 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.integrations to be enabled.

New 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.webhooks to 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 Member leaves or joins a Guild.

This requires Intents.members to be enabled.

Parameters:

member (Member) – The member who joined or left.

nextcord.on_raw_member_remove(payload)

Called when a Member leaves a Guild. Unlike on_member_remove() this is called regardless of the state of the internal message cache.

This requires Intents.members to be enabled.

New in version 2.0.

Parameters:

payload (RawMemberRemoveEvent) – The raw event payload data.

nextcord.on_member_update(before, after)

Called when a Member updates their profile.

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

  • nickname

  • roles

  • pending

  • flags

This requires Intents.members to be enabled.

Parameters:
  • before (Member) – The updated member’s old info.

  • after (Member) – The updated member’s updated info.

nextcord.on_presence_update(before, after)

Called when a Member updates their presence.

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

  • status

  • activity

This requires Intents.presences and Intents.members to be enabled.

New in version 2.0.

Parameters:
  • before (Member) – The updated member’s old info.

  • after (Member) – The updated member’s updated info.

nextcord.on_user_update(before, after)

Called when a User updates their profile.

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

  • avatar

  • username

  • discriminator

This requires Intents.members to be enabled.

Parameters:
  • before (User) – The updated user’s old info.

  • after (User) – The updated user’s updated info.

nextcord.on_guild_join(guild)

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

This requires Intents.guilds to be enabled.

Parameters:

guild (Guild) – The guild that was joined.

nextcord.on_guild_remove(guild)

Called when a Guild is removed from the Client.

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

  • The client got banned.

  • The client got kicked.

  • The client left the guild.

  • The client or the guild owner deleted the guild.

For this event to be invoked, the Client must have been part of the guild to begin with. (i.e. it is part of Client.guilds)

This requires Intents.guilds to be enabled.

Parameters:

guild (Guild) – The guild that got removed.

nextcord.on_guild_update(before, after)

Called when a Guild updates, for example:

  • Changed name

  • Changed AFK channel

  • Changed AFK timeout

  • etc

This requires Intents.guilds to be enabled.

Parameters:
  • before (Guild) – The guild prior to being updated.

  • after (Guild) – The guild after being updated.

nextcord.on_guild_role_create(role)
nextcord.on_guild_role_delete(role)

Called when a Guild creates or deletes a new Role.

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

This requires Intents.guilds to be enabled.

Parameters:

role (Role) – The role that was created or deleted.

nextcord.on_guild_role_update(before, after)

Called when a Role is changed guild-wide.

This requires Intents.guilds to be enabled.

Parameters:
  • before (Role) – The updated role’s old info.

  • after (Role) – The updated role’s updated info.

nextcord.on_guild_emojis_update(guild, before, after)

Called when a Guild adds or removes Emoji.

This requires Intents.emojis_and_stickers to be enabled.

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

  • before (Sequence[Emoji]) – A list of emojis before the update.

  • after (Sequence[Emoji]) – A list of emojis after the update.

nextcord.on_guild_stickers_update(guild, before, after)

Called when a Guild updates its stickers.

This requires Intents.emojis_and_stickers to be enabled.

New 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)
nextcord.on_guild_unavailable(guild)

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

This requires Intents.guilds to be enabled.

Parameters:

guild – The Guild that has changed availability.

nextcord.on_voice_state_update(member, before, after)

Called when a Member changes their VoiceState.

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

  • A member joins a voice 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_states to be enabled.

Parameters:
  • member (Member) – The member whose voice states changed.

  • before (VoiceState) – The voice state prior to the changes.

  • after (VoiceState) – The voice state after the changes.

nextcord.on_stage_instance_create(stage_instance)
nextcord.on_stage_instance_delete(stage_instance)

Called when a StageInstance is created or deleted for a StageChannel.

New 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 StageInstance is updated.

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

  • The topic is changed.

  • The privacy level is changed.

New in version 2.0.

Parameters:
nextcord.on_member_ban(guild, user)

Called when user gets banned from a Guild.

This requires Intents.bans to be enabled.

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

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

nextcord.on_member_unban(guild, user)

Called when a User gets unbanned from a Guild.

This requires Intents.bans to be enabled.

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

  • user (User) – The user that got unbanned.

nextcord.on_invite_create(invite)

Called when an Invite is created. You must have the manage_channels permission to receive this.

New in version 1.3.

Note

There is a rare possibility that the Invite.guild and Invite.channel attributes will be of Object rather than the respective models.

This requires Intents.invites to be enabled.

Parameters:

invite (Invite) – The invite that was created.

nextcord.on_invite_delete(invite)

Called when an Invite is deleted. You must have the manage_channels permission to receive this.

New in version 1.3.

Note

There is a rare possibility that the Invite.guild and Invite.channel attributes will be of Object rather than the respective models.

Outside of those two attributes, the only other attribute guaranteed to be filled by the Discord gateway for this event is Invite.code.

This requires Intents.invites to be enabled.

Parameters:

invite (Invite) – The invite that was deleted.

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 ScheduledEvent is created.

Parameters:

event (ScheduledEvent) – The event that was created.

nextcord.on_guild_scheduled_event_update(before, after)

Called when a ScheduledEvent is updated.

Parameters:
nextcord.on_guild_scheduled_event_delete(event)

Called when a ScheduledEvent is 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 ScheduledEventUser is interested in a ScheduledEvent.

Parameters:
nextcord.on_auto_moderation_rule_create(rule)

Called when an AutoModerationRule is created.

New in version 2.1.

Parameters:

rule (AutoModerationRule) – The rule that was created.

nextcord.on_auto_moderation_rule_update(rule)

Called when an AutoModerationRule is edited.

New in version 2.1.

Parameters:

rule (AutoModerationRule) – The newly edited rule.

nextcord.on_auto_moderation_rule_delete(rule)

Called when a AutoModerationRule is deleted.

New in version 2.1.

Parameters:

rule (AutoModerationRule) – The deleted rule.

nextcord.on_auto_moderation_action_execution(execution)

Called when an AutoModerationAction is executed.

New in version 2.1.

Parameters:

execution (AutoModerationActionExecution) – The object containing the execution information.

nextcord.on_guild_audit_log_entry_create(entry)

Called when an AuditLogEntry is created.

New 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 Member whose name is ‘Mighty’ and return it. If an entry is not found, then None is returned.

This is different from filter() due to the fact it stops the moment it finds a valid entry.

Parameters:
  • predicate – A function that returns a boolean-like result.

  • seq (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 for find().

When multiple attributes are specified, they are checked using logical AND, not logical OR. Meaning they have to meet every attribute passed in and not one of them.

To have a nested attribute search (i.e. search by x.y) then pass in x__y as the keyword argument.

If nothing is found that matches the attributes passed, then None is returned.

Examples

Basic usage:

member = 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:

datetime.datetime

nextcord.utils.oauth_url(client_id, *, permissions=..., guild=..., redirect_uri=..., scopes=..., disable_guild_select=False)

A helper function that returns the OAuth2 URL for inviting the bot into guilds.

Parameters:
  • client_id (Union[int, str]) – The client ID for your bot.

  • permissions (Permissions) – The permissions you’re requesting. If not given then you won’t be requesting any permissions.

  • guild (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',).

    New in version 1.7.

  • disable_guild_select (bool) –

    Whether to disallow the user from changing the guild dropdown.

    New in version 2.0.

Returns:

The OAuth2 URL for inviting the bot into guilds.

Return type:

str

nextcord.utils.remove_markdown(text, *, ignore_links=True)

A helper function that removes markdown characters.

New in version 1.7.

Note

This function is not markdown aware and may remove meaning from the original text. For example, if the input contains 10 * 5 then it will be converted into 10  5.

Parameters:
  • text (str) – The text to remove markdown from.

  • ignore_links (bool) – Whether to leave links alone when removing markdown. For example, if a URL in the text contains characters such as _ then it will be left alone. Defaults to True.

Returns:

The text with the markdown special characters removed.

Return type:

str

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

  • ignore_links (bool) – Whether to leave links alone when escaping markdown. For example, if a URL in the text contains characters such as _ then it will be left alone. This option is not supported with as_needed. Defaults to True.

Returns:

The text with the markdown special characters escaped with a slash.

Return type:

str

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

Parameters:

text (str) – The text to escape mentions from.

Returns:

The text with the mentions removed.

Return type:

str

nextcord.utils.parse_raw_mentions(text)

A helper function that parses mentions from a string as an array of User IDs matched with the syntax of <@user_id> or <@!user_id>.

Note

This does not include role or channel mentions. See parse_raw_role_mentions() and parse_raw_channel_mentions() for those.

New in version 2.2.

Parameters:

text (str) – The text to parse mentions from.

Returns:

A list of user IDs that were mentioned.

Return type:

List[int]

nextcord.utils.parse_raw_role_mentions(text)

A helper function that parses mentions from a string as an array of Role IDs matched with the syntax of <@&role_id>.

New in version 2.2.

Parameters:

text (str) – The text to parse mentions from.

Returns:

A list of role IDs that were mentioned.

Return type:

List[int]

nextcord.utils.parse_raw_channel_mentions(text)

A helper function that parses mentions from a string as an array of GuildChannel IDs matched with the syntax of <#channel_id>.

New in version 2.2.

Parameters:

text (str) – The text to parse mentions from.

Returns:

A list of channel IDs that were mentioned.

Return type:

List[int]

nextcord.utils.resolve_invite(invite)

Resolves an invite from a Invite, URL or code.

Parameters:

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

Returns:

The invite code.

Return type:

str

nextcord.utils.resolve_template(code)

Resolves a template code from a Template, URL or code.

New in version 1.4.

Parameters:

code (Union[Template, str]) – The code.

Returns:

The template code.

Return type:

str

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.

New in version 1.3.

Parameters:
  • when (datetime.datetime) – The timestamp in which to sleep until. If the datetime is naive then it is assumed to be 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.

New in version 2.0.

Returns:

The current aware datetime in UTC.

Return type:

datetime.datetime

nextcord.utils.format_dt(dt, /, style=None)

A helper function to format a datetime.datetime for 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-GB locale.

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

str

nextcord.utils.as_chunks(iterator, max_size)

A helper function that collects an iterator into chunks of a given size.

New in version 2.0.

Parameters:

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

A text channel.

voice

A voice channel.

private

A private text channel. Also called a direct message.

group

A private group text channel.

category

A category channel.

news

A guild news channel.

stage_voice

A guild stage voice channel.

New in version 1.7.

news_thread

A news thread

New in version 2.0.

public_thread

A public thread

New in version 2.0.

private_thread

A private thread

New in version 2.0.

guild_directory

A channel containing the guilds in a Student Hub

New in version 2.2.

forum

A forum channel.

New in version 2.1.

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

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

recipient_add

The system message when a user is added to a group private message or a thread.

recipient_remove

The system message when a user is removed from a group private message or a thread.

call

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

channel_name_change

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

channel_icon_change

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

pins_add

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

new_member

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

premium_guild_subscription

The system message denoting that a member has “nitro boosted” a guild.

premium_guild_tier_1

The system message denoting that a member has “nitro boosted” a guild and it achieved level 1.

premium_guild_tier_2

The system message denoting that a member has “nitro boosted” a guild and it achieved level 2.

premium_guild_tier_3

The system message denoting that a member has “nitro boosted” a guild and it achieved level 3.

channel_follow_add

The system message denoting that an announcement channel has been followed.

New in version 1.3.

guild_stream

The system message denoting that a member is streaming in the guild.

New in version 1.7.

guild_discovery_disqualified

The system message denoting that the guild is no longer eligible for Server Discovery.

New in version 1.7.

guild_discovery_requalified

The system message denoting that the guild has become eligible again for Server Discovery.

New in version 1.7.

guild_discovery_grace_period_initial_warning

The system message denoting that the guild has failed to meet the Server Discovery requirements for one week.

New in version 1.7.

guild_discovery_grace_period_final_warning

The system message denoting that the guild has failed to meet the Server Discovery requirements for 3 weeks in a row.

New in version 1.7.

thread_created

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.

New in version 2.0.

reply

The system message denoting that the author is replying to a message.

New in version 2.0.

chat_input_command

The system message denoting that a slash command was executed.

New in version 2.0.

thread_starter_message

The system message denoting the message in the thread that is the one that started the thread’s conversation topic.

New in version 2.0.

guild_invite_reminder

The system message sent as a reminder to invite people to the guild.

New in version 2.0.

context_menu_command

The system message denoting that a context menu command was executed.

New in version 2.0.

auto_moderation_action

The system message denoting that an auto moderation action was executed

New in version 2.1.

stage_start

The system message denoting that a stage channel has started.

New in version 2.6.

stage_end

The system message denoting that a stage channel has ended.

New in version 2.6.

stage_speaker

The system message denoting that a stage channel has a new speaker.

New in version 2.6.

stage_topic

The system message denoting that a stage channel has a new topic.

New in version 2.6.

class nextcord.UserFlags

Represents Discord User flags.

staff

The user is a Discord Employee.

partner

The user is a Discord Partner.

hypesquad

The user is a HypeSquad Events member.

bug_hunter

The user is a Bug Hunter.

mfa_sms

The user has SMS recovery for Multi Factor Authentication enabled.

premium_promo_dismissed

The user has dismissed the Discord Nitro promotion.

hypesquad_bravery

The user is a HypeSquad Bravery member.

hypesquad_brilliance

The user is a HypeSquad Brilliance member.

hypesquad_balance

The user is a HypeSquad Balance member.

early_supporter

The user is an Early Supporter.

team_user

The user is a Team User.

system

The user is a system user (i.e. represents Discord officially).

has_unread_urgent_messages

The user has an unread system message.

bug_hunter_level_2

The user is a Bug Hunter Level 2.

verified_bot

The user is a Verified Bot.

verified_bot_developer

The user is an Early Verified Bot Developer.

discord_certified_moderator

The user is a Discord Certified Moderator.

bot_http_interactions

The user is a bot that uses only HTTP interactions and is shown in the online member list.

New in version 2.4.

known_spammer

The user is a Known Spammer.

active_developer

The user is an Active Developer.

New in version 2.4.

class nextcord.ActivityType

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

unknown

An unknown activity type. This should generally not happen.

playing

A “Playing” activity type.

streaming

A “Streaming” activity type.

listening

A “Listening” activity type.

watching

A “Watching” activity type.

custom

A custom activity type.

competing

A competing activity type.

New in version 1.5.

class nextcord.InteractionType

Specifies the type of Interaction.

New in version 2.0.

ping

Represents Discord pinging to see if the interaction response server is alive.

application_command

Represents a slash command or context menu interaction.

component

Represents a component based interaction, i.e. using the Discord Bot UI Kit.

application_command_autocomplete

Represents a slash command autocomplete interaction.

modal_submit

Represents a modal submit interaction.

class nextcord.InteractionResponseType

Specifies the response type for the interaction.

New in version 2.0.

pong

Pongs the interaction when given a ping.

See also InteractionResponse.pong()

channel_message

Respond to the interaction with a message.

See also InteractionResponse.send_message()

deferred_channel_message

Responds to the interaction with a message at a later time.

See also InteractionResponse.defer()

deferred_message_update

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

Responds to the interaction by editing the message.

See also InteractionResponse.edit_message()

class nextcord.ComponentType

Represents the component type of a component.

New in version 2.0.

action_row

Represents the group component which holds different components in a row.

button

Represents a button component.

select

Represents a string select component.

text_input

Represents a text input component.

user_select

Represents a user select component.

New in version 2.3.

role_select

Represents a role select component.

New in version 2.3.

mentionable_select

Represents a mentionable select component.

New in version 2.3.

channel_select

Represents a channel select component.

New in version 2.3.

class nextcord.ButtonStyle

Represents the style of the button component.

New in version 2.0.

primary

Represents a blurple button for the primary action.

secondary

Represents a grey button for the secondary action.

success

Represents a green button for a successful action.

danger

Represents a red button for a dangerous action.

Represents a link button.

blurple

An alias for primary.

grey

An alias for secondary.

gray

An alias for secondary.

green

An alias for success.

red

An alias for danger.

url

An alias for link.

class nextcord.TextInputStyle

Represent the style of a text input component.

short

Represent a single line input

paragraph

Represent a multi line input

class nextcord.VoiceRegion

Specifies the region a voice server belongs to.

amsterdam

The Amsterdam region.

brazil

The Brazil region.

dubai

The Dubai region.

New in version 1.3.

eu_central

The EU Central region.

eu_west

The EU West region.

europe

The Europe region.

New in version 1.3.

frankfurt

The Frankfurt region.

hongkong

The Hong Kong region.

india

The India region.

New in version 1.2.

japan

The Japan region.

london

The London region.

russia

The Russia region.

singapore

The Singapore region.

southafrica

The South Africa region.

south_korea

The South Korea region.

sydney

The Sydney region.

us_central

The US Central region.

us_east

The US East region.

us_south

The US South region.

us_west

The US West region.

vip_amsterdam

The Amsterdam region for VIP guilds.

vip_us_east

The US East region for VIP guilds.

vip_us_west

The US West region for VIP guilds.

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

New 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

No criteria set.

low

Member must have a verified email on their Discord account.

medium

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

high

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

highest

Member must have a verified phone on their Discord account.

class nextcord.NotificationLevel

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

New 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

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

only_mentions

Members receive notifications for messages they are mentioned in.

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.

New 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

The guild does not have the content filter enabled.

no_role

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

all_members

The guild has the content filter enabled for every member.

class nextcord.Status

Specifies a Member ‘s status.

online

The member is online.

offline

The member is offline.

idle

The member is idle.

dnd

The member is “Do Not Disturb”.

do_not_disturb

An alias for dnd.

invisible

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

class nextcord.AuditLogAction

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

guild_update

The guild has updated. Things that trigger this include:

  • Changing the guild vanity URL

  • Changing the guild invite splash

  • Changing the guild AFK channel or timeout

  • Changing the guild voice server region

  • Changing the guild icon, banner, or discovery splash

  • Changing the guild moderation settings

  • Changing things related to the guild widget

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

Possible attributes for AuditLogDiff:

channel_create

A new channel was created.

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

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

Possible attributes for AuditLogDiff:

channel_update

A channel was updated. Things that trigger this include:

  • The channel name or topic was changed

  • The channel bitrate was changed

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

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

Possible attributes for AuditLogDiff:

channel_delete

A channel was deleted.

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

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

Possible attributes for AuditLogDiff:

overwrite_create

A channel permission overwrite was created.

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

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

Possible attributes for AuditLogDiff:

overwrite_update

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

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

Possible attributes for AuditLogDiff:

overwrite_delete

A channel permission overwrite was deleted.

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

Possible attributes for AuditLogDiff:

kick

A member was kicked.

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

When this is the action, changes is empty.

member_prune

A member prune was triggered.

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

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

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

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

When this is the action, changes is empty.

ban

A member was banned.

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

When this is the action, changes is empty.

unban

A member was unbanned.

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

When this is the action, changes is empty.

member_update

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

  • A nickname was changed

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

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

Possible attributes for AuditLogDiff:

member_role_update

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

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

Possible attributes for AuditLogDiff:

member_move

A member’s voice channel has been updated. This triggers when a member is moved to a different voice channel.

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

  • channel: A TextChannel or Object with the channel ID where the members were moved.

  • count: An integer specifying how many members were moved.

New in version 1.3.

member_disconnect

A member’s voice state has changed. This triggers when a member is force disconnected from voice.

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

  • count: An integer specifying how many members were disconnected.

New in version 1.3.

bot_add

A bot was added to the guild.

When this is the action, the type of target is the Member or User which was added to the guild.

New in version 1.3.

role_create

A new role was created.

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

Possible attributes for AuditLogDiff:

role_update

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

  • The name has changed

  • The permissions have changed

  • The colour has changed

  • Its hoist/mentionable state has changed

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

Possible attributes for AuditLogDiff:

role_delete

A role was deleted.

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

Possible attributes for AuditLogDiff:

invite_create

An invite was created.

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

Possible attributes for AuditLogDiff:

invite_update

An invite was updated.

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

invite_delete

An invite was deleted.

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

Possible attributes for AuditLogDiff:

webhook_create

A webhook was created.

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

Possible attributes for AuditLogDiff:

webhook_update

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

  • The webhook name changed

  • The webhook channel changed

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

Possible attributes for AuditLogDiff:

webhook_delete

A webhook was deleted.

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

Possible attributes for AuditLogDiff:

emoji_create

An emoji was created.

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

Possible attributes for AuditLogDiff:

emoji_update

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

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

Possible attributes for AuditLogDiff:

emoji_delete

An emoji was deleted.

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

Possible attributes for AuditLogDiff:

message_delete

A message was deleted by a moderator. Note that this only triggers if the message was deleted by someone other than the author.

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

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

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

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

message_bulk_delete

Messages were bulk deleted by a moderator.

When this is the action, the type of target is the TextChannel or Object with the ID of the channel that was purged.

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

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

New in version 1.3.

message_pin

A message was pinned in a channel.

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

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

  • channel: A TextChannel or Object with the channel ID where the message was pinned.

  • message_id: the ID of the message which was pinned.

New in version 1.3.

message_unpin

A message was unpinned in a channel.

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

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

  • channel: A TextChannel or Object with the channel ID where the message was unpinned.

  • message_id: the ID of the message which was unpinned.

New in version 1.3.

integration_create

A guild integration was created.

When this is the action, the type of target is the Object with the integration ID of the integration which was created.

New in version 1.3.

integration_update

A guild integration was updated.

When this is the action, the type of target is the Object with the integration ID of the integration which was updated.

New in version 1.3.

integration_delete

A guild integration was deleted.

When this is the action, the type of target is the Object with the integration ID of the integration which was deleted.

New in version 1.3.

stage_instance_create

A stage instance was started.

When this is the action, the type of target is the StageInstance or Object with the ID of the stage instance which was created.

Possible attributes for AuditLogDiff:

New in version 2.0.

stage_instance_update

A stage instance was updated.

When this is the action, the type of target is the StageInstance or Object with the ID of the stage instance which was updated.

Possible attributes for AuditLogDiff:

New in version 2.0.

stage_instance_delete

A stage instance was ended.

New in version 2.0.

sticker_create

A sticker was created.

When this is the action, the type of target is the GuildSticker or Object with the ID of the sticker which was updated.

Possible attributes for AuditLogDiff:

New in version 2.0.

sticker_update

A sticker was updated.

When this is the action, the type of target is the GuildSticker or Object with the ID of the sticker which was updated.

Possible attributes for AuditLogDiff:

New in version 2.0.

sticker_delete

A sticker was deleted.

When this is the action, the type of target is the GuildSticker or Object with the ID of the sticker which was updated.

Possible attributes for AuditLogDiff:

New in version 2.0.

thread_create

A thread was created.

When this is the action, the type of target is the Thread or Object with the ID of the thread which was created.

Possible attributes for AuditLogDiff:

New in version 2.0.

thread_update

A thread was updated.

When this is the action, the type of target is the Thread or Object with the ID of the thread which was updated.

Possible attributes for AuditLogDiff:

New in version 2.0.

thread_delete

A thread was deleted.

When this is the action, the type of target is the Thread or Object with the ID of the thread which was deleted.

Possible attributes for AuditLogDiff:

New in version 2.0.

auto_moderation_rule_create

An auto moderation rule was created.

When this is the action, the type of target is the AutoModerationRule or Object with the ID of the rule which was created.

Possible attributes for AuditLogDiff:

New in version 2.1.

auto_moderation_rule_update

An auto moderation rule was updated.

When this is the action, the type of target is the AutoModerationRule or Object with the ID of the rule which was updated.

Possible attributes for AuditLogDiff:

New in version 2.1.

auto_moderation_rule_delete

An auto moderation rule was deleted.

When this is the action, the type of target is the AutoModerationRule or Object with the ID of the rule which was deleted.

Possible attributes for AuditLogDiff:

New in version 2.1.

auto_moderation_block_message

A message was blocked by an auto moderation rule.

When this is the action, the type of target is the Member or User whose message was blocked.

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

New in version 2.1.

auto_moderation_flag_to_channel

A message was flagged by an auto moderation rule.

When this is the action, the type of target is the Member or User whose message was flagged.

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

New in version 2.3.

auto_moderation_user_communication_disabled

A member was timed out by an auto moderation rule.

When this is the action, the type of target is the Member or User who was timed out.

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

New in version 2.3.

class nextcord.AuditLogActionCategory

Represents the category that the AuditLogAction belongs to.

This can be retrieved via AuditLogEntry.category.

create

The action is the creation of something.

delete

The action is the deletion of something.

update

The action is the update of something.

class nextcord.TeamMembershipState

Represents the membership state of a team member retrieved through Client.application_info().

New in version 1.3.

invited

Represents an invited member.

accepted

Represents a member currently in the team.

class nextcord.WebhookType

Represents the type of webhook that can be received.

New in version 1.3.

incoming

Represents a webhook that can post messages to channels with a token.

channel_follower

Represents a webhook that is internally managed by Discord, used for following channels.

application

Represents a webhook that is used for interactions or applications.

New in version 2.0.

class nextcord.ExpireBehaviour

Represents the behaviour the Integration should perform when a user’s subscription has finished.

There is an alias for this called ExpireBehavior.

New in version 1.4.

remove_role

This will remove the StreamIntegration.role from the user when their subscription is finished.

kick

This will kick the user when their subscription is finished.

class nextcord.DefaultAvatar

Represents the default avatar of a Discord User

blurple

Represents the default avatar with the color blurple. See also Colour.blurple

grey

Represents the default avatar with the color grey. See also Colour.greyple

gray

An alias for grey.

green

Represents the default avatar with the color green. See also Colour.green

orange

Represents the default avatar with the color orange. See also Colour.orange

red

Represents the default avatar with the color red. See also Colour.red

fuchsia

Represents the default avatar with the color fuchsia. See also Colour.fuchsia

New in version 2.6.

pink

An alias for fuchsia

New in version 2.6.

class nextcord.StickerType

Represents the type of sticker.

New in version 2.0.

standard

Represents a standard sticker.

guild

Represents a custom sticker created in a guild.

class nextcord.StickerFormatType

Represents the type of sticker images.

New in version 1.6.

png

Represents a sticker with a png image.

apng

Represents a sticker with an apng image.

lottie

Represents a sticker with a lottie image.

gif

Represents a sticker with a GIF image.

New in version 2.4.

class nextcord.InviteTarget

Represents the invite type for voice channel invites.

New in version 2.0.

unknown

The invite doesn’t target anyone or anything.

stream

A stream invite that targets a user.

embedded_application

A stream invite that targets an embedded application.

class nextcord.VideoQualityMode

Represents the camera video quality mode for voice channel participants.

New in version 2.0.

auto

Represents auto camera video quality.

full

Represents full camera video quality.

class nextcord.StagePrivacyLevel

Represents a stage instance’s privacy level.

New in version 2.0.

public

The stage instance can be joined by external users.

closed

The stage instance can only be joined by members of the guild.

guild_only

Alias for closed

class nextcord.NSFWLevel

Represents the NSFW level of a guild.

New 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

The guild has not been categorised yet.

explicit

The guild contains NSFW content.

safe

The guild does not contain any NSFW content.

age_restricted

The guild may contain NSFW content.

class nextcord.ScheduledEventEntityType

Represents the type of an entity on a scheduled event.

stage_instance

The event is for a stage.

voice

The event is for a voice channel.

external

The event is happening elsewhere.

class nextcord.ScheduledEventPrivacyLevel

Represents the privacy level of scheduled event.

guild_only

The scheduled event is only visible to members of the guild.

class nextcord.ScheduledEventStatus

Represents the status of a scheduled event.

scheduled

The event is scheduled to happen.

active

The event is happening.

completed

The event has finished.

canceled

The event was canceled.

cancelled

An alias for canceled.

class nextcord.Locale(value)

An enumeration.

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

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

Represents what event context an auto moderation rule will be checked.

New in version 2.1.

message_send

A member sends or edits a message in the guild.

class nextcord.AutoModerationTriggerType

Represents the type of content which can trigger an auto moderation rule.

New in version 2.1.

Changed in version 2.2: Removed harmful_link as it is no longer used by Discord.

keyword

This rule checks if content contains words from a user defined list of keywords.

spam

This rule checks if content represents generic spam.

keyword_preset

This rule checks if content contains words from Discord pre-defined wordsets.

mention_spam

This rule checks if the number of mentions in the message is more than the maximum allowed.

New in version 2.3.

class nextcord.KeywordPresetType

Represents the type of a keyword preset auto moderation rule.

New in version 2.1.

profanity

Words that may be considered forms of swearing or cursing.

sexual_content

Words that refer to sexually explicit behaviour or activity.

slurs

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.

New in version 2.1.

block_message

Blocks a message with content matching the rule.

send_alert_message

Logs message content to a specified channel.

timeout

Timeout user for a specified duration.

Note

This action type can only be used with the Permissions.moderate_members permission.

class nextcord.SortOrderType

New in version 2.3.

The default sort order type used to sort posts in a ForumChannel.

latest_activity

Sort forum posts by their activity.

creation_date

Sort forum posts by their creation date.

class nextcord.ForumLayoutType

The default layout type used to display posts in a ForumChannel.

New in version 2.4.

not_set

No default has been set by channel administrators.

list

Display posts as a list, more text focused.

gallery

Display posts as a collection of posts with images, this is more image focused.

class nextcord.RoleConnectionMetadataType

Represents the type of comparison a role connection metadata record will use.

New in version 2.4.

integer_less_than_or_equal
datetime_less_than_or_equal

The metadata value must be less than or equal to the guild’s configured value.

integer_greater_than_or_equal
datetime_greater_than_or_equal

The metadata value must be greater than or equal to the guild’s configured value.

integer_equal
boolean_equal

The metadata value must be equal to the guild’s configured value.

integer_not_equal
boolean_not_equal

The metadata value must be not equal to the guild’s configured value.

Async Iterator

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

These async iterators can be used as follows:

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

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

class nextcord.AsyncIterator

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

async for x in y

Iterates over the contents of the async iterator.

await next()

This function is a coroutine.

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

await get(**attrs)

This function is a coroutine.

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

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

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

This function is a coroutine.

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

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

Getting the last audit log with a reason or None:

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

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

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

Returns:

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

await flatten()

This function is a coroutine.

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

Returns:

A list of every element in the async iterator.

Return type:

list

chunk(max_size)

Collects items into chunks of up to a given maximum size. Another AsyncIterator is returned which collects items into lists of a given size. The maximum chunk size must be a positive integer.

New in version 1.6.

Collecting groups of users:

async for leader, *users in reaction.users().chunk(3):
    ...

Warning

The last chunk collected may not be as large as max_size.

Parameters:

max_size – The size of individual chunks.

Return type:

AsyncIterator

map(func)

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

Creating a content iterator:

def transform(message):
    return message.content

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

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

Return type:

AsyncIterator

filter(predicate)

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

Getting messages by non-bot accounts:

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

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

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

Return type:

AsyncIterator

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:

AuditLogAction

user

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

Type:

abc.User

id

The entry ID.

Type:

int

target

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

Type:

Any

reason

The reason this action was done.

Type:

Optional[str]

extra

Extra information that this entry has that might be useful. For most actions, this is None. However in some cases it contains extra information. See AuditLogAction for which actions have this field filled out.

Type:

Any

created_at

Returns the entry’s creation time in UTC.

Type:

datetime.datetime

category

The category of the action, if applicable.

Type:

Optional[AuditLogActionCategory]

changes

The list of changes this entry has.

Type:

AuditLogChanges

before

The target’s prior state.

Type:

AuditLogDiff

after

The target’s subsequent state.

Type:

AuditLogDiff

AuditLogChanges

Attributes
class nextcord.AuditLogChanges

An audit log change set.

before

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

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

Category

Description

create

All attributes are set to None.

delete

All attributes are set the value before deletion.

update

All attributes are set the value before updating.

None

No attributes are set.

after

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

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

Category

Description

create

All attributes are set to the created value

delete

All attributes are set to None

update

All attributes are set the value after updating.

None

No attributes are set.

AuditLogDiff

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.

name

A name of something.

Type:

str

icon

A guild’s icon. See also Guild.icon.

Type:

Asset

splash

The guild’s invite splash. See also Guild.splash.

Type:

Asset

discovery_splash

The guild’s discovery splash. See also Guild.discovery_splash.

Type:

Asset

banner

The guild’s banner. See also Guild.banner.

Type:

Asset

owner

The guild’s owner. See also Guild.owner

Type:

Union[Member, User]

region

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

Type:

VoiceRegion

afk_channel

The guild’s AFK channel.

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

See Guild.afk_channel.

Type:

Union[VoiceChannel, Object]

system_channel

The guild’s system channel.

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

See Guild.system_channel.

Type:

Union[TextChannel, Object]

rules_channel

The guild’s rules channel.

If this could not be found then it falls back to a Object with 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 Object with 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:

int

mfa_level

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

Type:

int

widget_enabled

The guild’s widget has been enabled or disabled.

Type:

bool

widget_channel

The widget’s channel.

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

Type:

Union[TextChannel, Object]

verification_level

The guild’s verification level.

See also Guild.verification_level.

Type:

VerificationLevel

default_notifications

The guild’s default notification level.

See also Guild.default_notifications.

Type:

NotificationLevel

explicit_content_filter

The guild’s content filter.

See also Guild.explicit_content_filter.

Type:

ContentFilter

default_message_notifications

The guild’s default message notification setting.

Type:

int

vanity_url_code

The guild’s vanity URL.

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

Type:

str

position

The position of a Role or abc.GuildChannel.

Type:

int

type

The type of channel or sticker.

Type:

Union[ChannelType, StickerType]

topic

The topic of a TextChannel or StageChannel.

See also TextChannel.topic or StageChannel.topic.

Type:

str

bitrate

The bitrate of a VoiceChannel.

See also VoiceChannel.bitrate.

Type:

int

overwrites

A list of permission overwrite tuples that represents a target and a PermissionOverwrite for said target.

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

Type:

List[Tuple[target, PermissionOverwrite]]

privacy_level

The privacy level of the stage instance.

Type:

StagePrivacyLevel

roles

A list of roles being added or removed from a member.

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

Type:

List[Union[Role, Object]]

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:

bool

mute

Whether the member is being server muted.

See also VoiceState.mute.

Type:

bool

permissions

The permissions of a role.

See also Role.permissions.

Type:

Permissions

colour
color

The colour of a role.

See also Role.colour

Type:

Colour

hoist

Whether the role is being hoisted or not.

See also Role.hoist

Type:

bool

mentionable

Whether the role is mentionable or not.

See also Role.mentionable

Type:

bool

code

The invite’s code.

See also Invite.code

Type:

str

channel

A guild channel.

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

Type:

Union[abc.GuildChannel, Object]

inviter

The user who created the invite.

See also Invite.inviter.

Type:

Optional[User]

max_uses

The invite’s max uses.

See also Invite.max_uses.

Type:

int

uses

The invite’s current uses.

See also Invite.uses.

Type:

int

max_age

The invite’s max age in seconds.

See also Invite.max_age.

Type:

int

temporary

If the invite is a temporary invite.

See also Invite.temporary.

Type:

bool

allow
deny

The permissions being allowed or denied.

Type:

Permissions

id

The ID of the object being changed.

Type:

int

avatar

The avatar of a member.

See also User.avatar.

Type:

Asset

slowmode_delay

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

See also TextChannel.slowmode_delay.

Type:

int

rtc_region

The region for the voice channel’s voice communication. A value of None indicates automatic voice region detection.

See also VoiceChannel.rtc_region.

Type:

VoiceRegion

video_quality_mode

The camera video quality for the voice channel’s participants.

See also VoiceChannel.video_quality_mode.

Type:

VideoQualityMode

format_type

The format type of a sticker being changed.

See also GuildSticker.format

Type:

StickerFormatType

emoji

The name of the emoji that represents a sticker being changed.

See also GuildSticker.emoji

Type:

str

description

The description of a sticker being changed.

See also GuildSticker.description

Type:

str

available

The availability of a sticker being changed.

See also GuildSticker.available

Type:

bool

archived

The thread is now archived.

Type:

bool

locked

The thread is being locked or unlocked.

Type:

bool

auto_archive_duration

The thread’s auto archive duration being changed.

See also Thread.auto_archive_duration

Type:

int

default_auto_archive_duration

The default auto archive duration for newly created threads being changed.

Type:

int

enabled

Whether something was enabled or disabled.

Type:

bool

trigger_type

The trigger type of an auto moderation rule being changed.

Type:

AutoModerationTriggerType

event_type

The event type of an auto moderation rule being changed.

Type:

AutoModerationEventType

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 Object with the ID set.

Type:

List[Union[Role, Object]]

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

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() and TextChannel.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() or partial() 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.

id

The webhook’s ID

Type:

int

type

The type of the webhook.

New in version 1.3.

Type:

WebhookType

token

The authentication token of the webhook. If this is None then the webhook cannot be used to make requests.

Type:

Optional[str]

guild_id

The guild ID this webhook is for.

Type:

Optional[int]

channel_id

The channel ID this webhook is for.

Type:

Optional[int]

user

The user this webhook was created by. If the webhook was received without authentication then this will be None.

Type:

Optional[abc.User]

name

The default name of the webhook.

Type:

Optional[str]

source_guild

The guild of the channel that this webhook is following. Only given if type is WebhookType.channel_follower.

New in version 2.0.

Type:

Optional[PartialWebhookGuild]

source_channel

The channel that this webhook is following. Only given if type is WebhookType.channel_follower.

New in version 2.0.

Type:

Optional[PartialWebhookChannel]

property url

Returns the webhook’s url.

Type:

str

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.

    New in version 2.0.

  • bot_token (Optional[str]) –

    The bot authentication token for authenticated requests involving the webhook.

    New in version 2.0.

Returns:

A partial Webhook. A partial webhook is just a webhook object with an ID and a token.

Return type:

Webhook

classmethod from_url(url, *, session, bot_token=None)

Creates a partial Webhook from 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.

    New in version 2.0.

  • bot_token (Optional[str]) –

    The bot authentication token for authenticated requests involving the webhook.

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

Webhook

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.

New in version 2.0.

Note

When fetching with an unauthenticated webhook, i.e. is_authenticated() returns False, 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 to True.

Raises:
Returns:

The fetched webhook.

Return type:

Webhook

await delete(*, reason=None, prefer_auth=True)

This function is a coroutine.

Deletes this Webhook.

Parameters:
  • reason (Optional[str]) –

    The reason for deleting this webhook. Shows up on the audit log.

    New in version 1.4.

  • prefer_auth (bool) –

    Whether to use the bot token over the webhook token if available. Defaults to True.

    New in version 2.0.

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 avatar parameter now accepts File, Attachment, and Asset.

Parameters:
  • name (Optional[str]) – The webhook’s new default name.

  • avatar (Optional[Union[bytes, Asset, Attachment, File]]) – A bytes-like object, File, Attachment, or Asset representing the webhook’s new default avatar.

  • channel (Optional[abc.Snowflake]) –

    The webhook’s new channel. This requires an authenticated webhook.

    New in version 2.0.

  • reason (Optional[str]) –

    The reason for editing this webhook. Shows up on the audit log.

    New in version 1.4.

  • prefer_auth (bool) –

    Whether to use the bot token over the webhook token if available. Defaults to True.

    New 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 Asset for the avatar the webhook has.

If the webhook does not have a traditional avatar, an asset for the default avatar is returned instead.

Type:

Asset

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:

datetime.datetime

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.

New in version 2.0.

is_partial()

bool: Whether the webhook is a “partial” webhook.

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

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 file parameter should be used with a single File object.

If the embed parameter is provided, it must be of type Embed and it must be a rich embed type. You cannot mix the embed parameter with the embeds parameter, which must be a list of Embed objects to send.

Changed in version 2.4: ephemeral can now accept None to indicate that flags should 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 from None to a WebhookMessage if set to True. If the type of webhook is WebhookType.application then this is always set to True.

  • username (str) – The username to send with this message. If no username is provided then the default username for the webhook is used.

  • avatar_url (str) – The avatar URL to send with this message. If no avatar URL is provided then the default avatar for the webhook is used. If this is not a string then it is explicitly cast using str.

  • 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 to WebhookType.application webhooks. 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.

    New in version 2.0.

  • file (File) – The file to upload. This cannot be mixed with files parameter.

  • files (List[File]) – A list of files to send with the content. This cannot be mixed with the file parameter.

  • embed (Embed) – The rich embed for the content to send. This cannot be mixed with embeds parameter.

  • embeds (List[Embed]) – A list of embeds to send with the content. Maximum of 10. This cannot be mixed with the embed parameter.

  • allowed_mentions (AllowedMentions) –

    Controls the mentions being processed in this message.

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

    New in version 2.0.

  • thread (Snowflake) –

    The thread to send this webhook to.

    New in version 2.0.

  • flags (Optional[MessageFlags]) –

    The message flags being set for this message. Currently only suppress_embeds is able to be set.

    New in version 2.4.

  • suppress_embeds (Optional[bool]) –

    Whether to suppress embeds on this message.

    New in version 2.4.

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 embed and embeds or file and files.

  • ValueError – The length of embeds was invalid.

  • InvalidArgument – There was no token associated with this webhook or ephemeral was passed with the improper webhook type or there was no state attached with this webhook when giving it a view.

Returns:

If wait is True then the message that was sent, otherwise None.

Return type:

Optional[WebhookMessage]

await fetch_message(id)

This function is a coroutine.

Retrieves a single WebhookMessage owned by this webhook.

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

WebhookMessage

await edit_message(message_id, *, content=..., embeds=..., embed=..., file=..., files=..., attachments=..., view=..., 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.

New 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 or None to clear it.

  • embeds (List[Embed]) – A list of embeds to edit the message with.

  • embed (Optional[Embed]) – The embed to edit the message with. None suppresses the embeds. This should not be mixed with the embeds parameter.

  • file (File) –

    The file to upload. This cannot be mixed with files parameter.

    New in version 2.0.

  • files (List[File]) –

    A list of files to send with the content. This cannot be mixed with the file parameter.

    New in version 2.0.

  • attachments (List[Attachment]) –

    A list of attachments to keep in the message.

    New in version 2.0.

  • allowed_mentions (AllowedMentions) – Controls the mentions being processed in this message. See abc.Messageable.send() for more information.

  • view (Optional[View]) –

    The updated view to update this message with. If None is passed then the view is removed. The webhook must have state attached, similar to send().

    New in version 2.0.

Raises:
  • HTTPException – Editing the message failed.

  • Forbidden – Edited a message that is not yours.

  • InvalidArgument – You specified both embed and embeds or file and files.

  • ValueError – The length of embeds was invalid.

  • InvalidArgument – There was no token associated with this webhook or the webhook had no state.

Returns:

The newly edited webhook message.

Return type:

WebhookMessage

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.

New in version 1.6.

Parameters:

message_id (int) – The message ID to delete.

Raises:

WebhookMessage

Methods
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.Message with changes to edit() and delete() to work.

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

New 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 or None to clear it.

  • embeds (List[Embed]) – A list of embeds to edit the message with.

  • embed (Optional[Embed]) – The embed to edit the message with. None suppresses the embeds. This should not be mixed with the embeds parameter.

  • file (File) –

    The file to upload. This cannot be mixed with files parameter.

    New in version 2.0.

  • files (List[File]) –

    A list of files to send with the content. This cannot be mixed with the file parameter.

    New in version 2.0.

  • attachments (List[Attachment]) –

    A list of attachments to keep in the message. To keep all existing attachments, pass message.attachments.

    New in version 2.0.

  • allowed_mentions (AllowedMentions) – Controls the mentions being processed in this message. See abc.Messageable.send() for more information.

  • view (Optional[View]) –

    The updated view to update this message with. If None is passed then the view is removed.

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

    New in version 2.0.

Raises:
Returns:

The newly edited message.

Return type:

WebhookMessage

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

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.

id

The webhook’s ID

Type:

int

type

The type of the webhook.

New in version 1.3.

Type:

WebhookType

token

The authentication token of the webhook. If this is None then the webhook cannot be used to make requests.

Type:

Optional[str]

guild_id

The guild ID this webhook is for.

Type:

Optional[int]

channel_id

The channel ID this webhook is for.

Type:

Optional[int]

user

The user this webhook was created by. If the webhook was received without authentication then this will be None.

Type:

Optional[abc.User]

name

The default name of the webhook.

Type:

Optional[str]

source_guild

The guild of the channel that this webhook is following. Only given if type is WebhookType.channel_follower.

New in version 2.0.

Type:

Optional[PartialWebhookGuild]

source_channel

The channel that this webhook is following. Only given if type is WebhookType.channel_follower.

New in version 2.0.

Type:

Optional[PartialWebhookChannel]

property url

Returns the webhook’s url.

Type:

str

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, the requests auto 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:

Webhook

classmethod from_url(url, *, session=..., bot_token=None)

Creates a partial Webhook from 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, the requests auto 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:

Webhook

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() returns False, 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 to True.

Raises:
Returns:

The fetched webhook.

Return type:

SyncWebhook

delete(*, reason=None, prefer_auth=True)

Deletes this Webhook.

Parameters:
  • reason (Optional[str