Welcome to disnake

_images/snake.svg_images/snake_dark.svg

disnake is a modern, easy to use, feature-rich, and async-ready API wrapper for Discord.

Features:

  • Modern Pythonic API using async/await syntax

  • Sane rate limit handling that prevents 429 errors

  • Command extension to aid with bot creation

  • Easy to use with an object oriented design

  • Optimised for both speed and memory

Getting started

Is this your first time using the library? This is the place to get started!

Getting help

If you’re having trouble with something, these resources might help.

Extensions

These extensions help you during development when it comes to common tasks.

disnake.ext.commands – Bot commands framework

disnake offers a lower level aspect on interacting with Discord. Often times, the library is used for the creation of bots. However this task can be daunting and confusing to get correctly the first time. Many times there comes a repetition in creating a bot command framework that is extensible, flexible, and powerful. For this reason, disnake comes with an extension library that handles this for you.

Commands

One of the most appealing aspects of the command extension is how easy it is to define commands and how you can arbitrarily nest groups and commands to have a rich sub-command system.

Commands are defined by attaching it to a regular Python function. The command is then invoked by the user using a similar signature to the Python function.

For example, in the given command definition:

@bot.command()
async def foo(ctx, arg):
    await ctx.send(arg)

With the following prefix ($), it would be invoked by the user via:

$foo abc

A command must always have at least one parameter, ctx, which is the Context as the first one.

There are two ways of registering a command. The first one is by using Bot.command() decorator, as seen in the example above. The second is using the command() decorator followed by Bot.add_command() on the instance.

Essentially, these two are equivalent:

from disnake.ext import commands

bot = commands.Bot(command_prefix='$')

@bot.command()
async def test(ctx):
    pass

# or:

@commands.command()
async def test(ctx):
    pass

bot.add_command(test)

Since the Bot.command() decorator is shorter and easier to comprehend, it will be the one used throughout the documentation here.

Any parameter that is accepted by the Command constructor can be passed into the decorator. For example, to change the name to something other than the function would be as simple as doing this:

@bot.command(name='list')
async def _list(ctx, arg):
    pass
Parameters

Since we define commands by making Python functions, we also define the argument passing behaviour by the function parameters.

Certain parameter types do different things in the user side and most forms of parameter types are supported.

Positional

The most basic form of parameter passing is the positional parameter. This is where we pass a parameter as-is:

@bot.command()
async def test(ctx, arg):
    await ctx.send(arg)

On the bot using side, you can provide positional arguments by just passing a regular string:

_images/positional1.png

To make use of a word with spaces in between, you should quote it:

_images/positional2.png

As a note of warning, if you omit the quotes, you will only get the first word:

_images/positional3.png

Since positional arguments are just regular Python arguments, you can have as many as you want:

@bot.command()
async def test(ctx, arg1, arg2):
    await ctx.send(f'You passed {arg1} and {arg2}')
Variable

Sometimes you want users to pass in an undetermined number of parameters. The library supports this similar to how variable list parameters are done in Python:

@bot.command()
async def test(ctx, *args):
    arguments = ', '.join(args)
    await ctx.send(f'{len(args)} arguments: {arguments}')

This allows our user to accept either one or many arguments as they please. This works similar to positional arguments, so multi-word parameters should be quoted.

For example, on the bot side:

_images/variable1.png

If the user wants to input a multi-word argument, they have to quote it like earlier:

_images/variable2.png

Do note that similar to the Python function behaviour, a user can technically pass no arguments at all:

_images/variable3.png

Since the args variable is a tuple, you can do anything you would usually do with one.

Keyword-Only Arguments

When you want to handle parsing of the argument yourself or do not feel like you want to wrap multi-word user input into quotes, you can ask the library to give you the rest as a single argument. We do this by using a keyword-only argument, seen below:

@bot.command()
async def test(ctx, *, arg):
    await ctx.send(arg)

Warning

You can only have one keyword-only argument due to parsing ambiguities.

On the bot side, we do not need to quote input with spaces:

_images/keyword1.png

Do keep in mind that wrapping it in quotes leaves it as-is:

_images/keyword2.png

By default, the keyword-only arguments are stripped of white space to make it easier to work with. This behaviour can be toggled by the Command.rest_is_raw argument in the decorator.

Invocation Context

As seen earlier, every command must take at least a single parameter, called the Context.

This parameter gives you access to something called the “invocation context”. Essentially all the information you need to know how the command was executed. It contains a lot of useful information:

The context implements the abc.Messageable interface, so anything you can do on a abc.Messageable you can do on the Context.

Converters

Adding bot arguments with function parameters is only the first step in defining your bot’s command interface. To actually make use of the arguments, we usually want to convert the data into a target type. We call these Converters.

Converters come in a few flavours:

  • A regular callable object that takes an argument as a sole parameter and returns a different type.

    • These range from your own function, to something like bool or int.

  • A custom class that inherits from Converter.

Basic Converters

At its core, a basic converter is a callable that takes in an argument and turns it into something else.

For example, if we wanted to add two numbers together, we could request that they are turned into integers for us by specifying the converter:

@bot.command()
async def add(ctx, a: int, b: int):
    await ctx.send(a + b)

We specify converters by using something called a function annotation. This is a Python 3 exclusive feature that was introduced in PEP 3107.

This works with any callable, such as a function that would convert a string to all upper-case:

def to_upper(argument):
    return argument.upper()

@bot.command()
async def up(ctx, *, content: to_upper):
    await ctx.send(content)
bool

Unlike the other basic converters, the bool converter is treated slightly different. Instead of casting directly to the bool type, which would result in any non-empty argument returning True, it instead evaluates the argument as True or False based on its given content:

if lowered in ('yes', 'y', 'true', 't', '1', 'enable', 'on'):
    return True
elif lowered in ('no', 'n', 'false', 'f', '0', 'disable', 'off'):
    return False
Advanced Converters

Sometimes a basic converter doesn’t have enough information that we need. For example, sometimes we want to get some information from the Message that called the command or we want to do some asynchronous processing.

For this, the library provides the Converter interface. This allows you to have access to the Context and have the callable be asynchronous. Defining a custom converter using this interface requires overriding a single method, Converter.convert().

An example converter:

import random

class Slapper(commands.Converter):
    async def convert(self, ctx, argument):
        to_slap = random.choice(ctx.guild.members)
        return f'{ctx.author} slapped {to_slap} because *{argument}*'

@bot.command()
async def slap(ctx, *, reason: Slapper):
    await ctx.send(reason)

The converter provided can either be constructed or not. Essentially these two are equivalent:

@bot.command()
async def slap(ctx, *, reason: Slapper):
    await ctx.send(reason)

# is the same as...

@bot.command()
async def slap(ctx, *, reason: Slapper()):
    await ctx.send(reason)

Having the possibility of the converter be constructed allows you to set up some state in the converter’s __init__ for fine tuning the converter. An example of this is actually in the library, clean_content.

@bot.command()
async def clean(ctx, *, content: commands.clean_content):
    await ctx.send(content)

# or for fine-tuning

@bot.command()
async def clean(ctx, *, content: commands.clean_content(use_nicknames=False)):
    await ctx.send(content)

If a converter fails to convert an argument to its designated target type, the BadArgument exception must be raised.

Inline Advanced Converters

If we don’t want to inherit from Converter, we can still provide a converter that has the advanced functionalities of an advanced converter and save us from specifying two types.

For example, a common idiom would be to have a class and a converter for that class:

class JoinDistance:
    def __init__(self, joined, created):
        self.joined = joined
        self.created = created

    @property
    def delta(self):
        return self.joined - self.created

class JoinDistanceConverter(commands.MemberConverter):
    async def convert(self, ctx, argument):
        member = await super().convert(ctx, argument)
        return JoinDistance(member.joined_at, member.created_at)

@bot.command()
async def delta(ctx, *, member: JoinDistanceConverter):
    is_new = member.delta.days < 100
    if is_new:
        await ctx.send("Hey you're pretty new!")
    else:
        await ctx.send("Hm you're not so new.")

This can get tedious, so an inline advanced converter is possible through a classmethod() inside the type:

class JoinDistance:
    def __init__(self, joined, created):
        self.joined = joined
        self.created = created

    @classmethod
    async def convert(cls, ctx, argument):
        member = await commands.MemberConverter().convert(ctx, argument)
        return cls(member.joined_at, member.created_at)

    @property
    def delta(self):
        return self.joined - self.created

@bot.command()
async def delta(ctx, *, member: JoinDistance):
    is_new = member.delta.days < 100
    if is_new:
        await ctx.send("Hey you're pretty new!")
    else:
        await ctx.send("Hm you're not so new.")
Discord Converters

Working with Discord Models is a fairly common thing when defining commands, as a result the library makes working with them easy.

For example, to receive a Member you can just pass it as a converter:

@bot.command()
async def joined(ctx, *, member: disnake.Member):
    await ctx.send(f'{member} joined on {member.joined_at}')

When this command is executed, it attempts to convert the string given into a Member and then passes it as a parameter for the function. This works by checking if the string is a mention, an ID, a nickname, a username + discriminator, or just a regular username. The default set of converters have been written to be as easy to use as possible.

A lot of Discord models work out of the gate as a parameter:

Having any of these set as the converter will intelligently convert the argument to the appropriate target type you specify.

Under the hood, these are implemented by the Advanced Converters interface. A table of the equivalent converter is given below:

By providing the converter it allows us to use them as building blocks for another converter:

class MemberRoles(commands.MemberConverter):
    async def convert(self, ctx, argument):
        member = await super().convert(ctx, argument)
        return [role.name for role in member.roles[1:]] # Remove everyone role!

@bot.command()
async def roles(ctx, *, member: MemberRoles):
    """Tells you a member's roles."""
    await ctx.send('I see the following roles: ' + ', '.join(member))
Special Converters

The command extension also has support for certain converters to allow for more advanced and intricate use cases that go beyond the generic linear parsing. These converters allow you to introduce some more relaxed and dynamic grammar to your commands in an easy to use manner.

typing.Union

A typing.Union is a special type hint that allows for the command to take in any of the specific types instead of a singular type. For example, given the following:

import typing

@bot.command()
async def union(ctx, what: typing.Union[disnake.TextChannel, disnake.Member]):
    await ctx.send(what)

The what parameter would either take a disnake.TextChannel converter or a disnake.Member converter. The way this works is through a left-to-right order. It first attempts to convert the input to a disnake.TextChannel, and if it fails it tries to convert it to a disnake.Member. If all converters fail, then a special error is raised, BadUnionArgument.

Note that any valid converter discussed above can be passed in to the argument list of a typing.Union.

typing.Optional

A typing.Optional is a special type hint that allows for “back-referencing” behaviour. If the converter fails to parse into the specified type, the parser will skip the parameter and then either None or the specified default will be passed into the parameter instead. The parser will then continue on to the next parameters and converters, if any.

Consider the following example:

import typing

@bot.command()
async def bottles(ctx, amount: typing.Optional[int] = 99, *, liquid="beer"):
    await ctx.send(f'{amount} bottles of {liquid} on the wall!')
_images/optional1.png

In this example, since the argument could not be converted into an int, the default of 99 is passed and the parser resumes handling, which in this case would be to pass it into the liquid parameter.

Note

This converter only works in regular positional parameters, not variable parameters or keyword-only parameters.

typing.Literal

A typing.Literal is a special type hint that requires the passed parameter to be equal to one of the listed values after being converted to the same type. For example, given the following:

from typing import Literal

@bot.command()
async def shop(ctx, buy_sell: Literal['buy', 'sell'], amount: Literal[1, 2], *, item: str):
    await ctx.send(f'{buy_sell.capitalize()}ing {amount} {item}(s)!')

The buy_sell parameter must be either the literal string "buy" or "sell" and amount must convert to the int 1 or 2. If buy_sell or amount don’t match any value, then a special error is raised, BadLiteralArgument. Any literal values can be mixed and matched within the same typing.Literal converter.

Note that typing.Literal[True] and typing.Literal[False] still follow the bool converter rules.

Greedy

The Greedy converter is a generalisation of the typing.Optional converter, except applied to a list of arguments. In simple terms, this means that it tries to convert as much as it can until it can’t convert any further.

Consider the following example:

@bot.command()
async def slap(ctx, members: commands.Greedy[disnake.Member], *, reason='no reason'):
    slapped = ", ".join(x.name for x in members)
    await ctx.send(f'{slapped} just got slapped for {reason}')

When invoked, it allows for any number of members to be passed in:

_images/greedy1.png

The type passed when using this converter depends on the parameter type that it is being attached to:

  • Positional parameter types will receive either the default parameter or a list of the converted values.

  • Variable parameter types will be a tuple as usual.

  • Keyword-only parameter types will be the same as if Greedy was not passed at all.

Greedy parameters can also be made optional by specifying an optional value.

When mixed with the typing.Optional converter you can provide simple and expressive command invocation syntaxes:

from datetime import timedelta
from typing import Optional

@bot.command()
async def ban(ctx, members: commands.Greedy[disnake.Member],
                   delete_days: Optional[int] = 0, *,
                   reason: str):
    """Mass bans members with an optional delete_days parameter"""
    for member in members:
        await member.ban(clean_history_duration=timedelta(days=delete_days), reason=reason)

This command can be invoked any of the following ways:

$ban @Member @Member2 spam bot
$ban @Member @Member2 7 spam bot
$ban @Member spam

Warning

The usage of Greedy and typing.Optional are powerful and useful, however as a price, they open you up to some parsing ambiguities that might surprise some people.

For example, a signature expecting a typing.Optional of a disnake.Member followed by a int could catch a member named after a number due to the different ways a MemberConverter decides to fetch members. You should take care to not introduce unintended parsing ambiguities in your code. One technique would be to clamp down the expected syntaxes allowed through custom converters or reordering the parameters to minimise clashes.

To help aid with some parsing ambiguities, str, None, typing.Optional and Greedy are forbidden as parameters for the Greedy converter.

FlagConverter

New in version 2.0.

A FlagConverter allows the user to specify user-friendly “flags” using PEP 526 type annotations or a syntax more reminiscent of the dataclasses module.

For example, the following code:

from disnake.ext import commands
import disnake

class BanFlags(commands.FlagConverter):
    member: disnake.Member
    reason: str
    days: int = 1

@commands.command()
async def ban(ctx, *, flags: BanFlags):
    plural = f'{flags.days} days' if flags.days != 1 else f'{flags.days} day'
    await ctx.send(f'Banned {flags.member} for {flags.reason!r} (deleted {plural} worth of messages)')

Allows the user to invoke the command using a simple flag-like syntax:

_images/flags1.png

Flags use a syntax that allows the user to not require quotes when passing in values to the flag. The goal of the flag syntax is to be as user-friendly as possible. This makes flags a good choice for complicated commands that can have multiple knobs to turn or simulating keyword-only parameters in your external command interface. It is recommended to use keyword-only parameters with the flag converter. This ensures proper parsing and behaviour with quoting.

Internally, the FlagConverter class examines the class to find flags. A flag can either be a class variable with a type annotation or a class variable that’s been assigned the result of the flag() function. These flags are then used to define the interface that your users will use. The annotations correspond to the converters that the flag arguments must adhere to.

For most use cases, no extra work is required to define flags. However, if customisation is needed to control the flag name or the default value then the flag() function can come in handy:

from typing import List

class BanFlags(commands.FlagConverter):
    members: List[disnake.Member] = commands.flag(name='member', default=lambda ctx: [])

This tells the parser that the members attribute is mapped to a flag named member and that the default value is an empty list. For greater customisability, the default can either be a value or a callable that takes the Context as a sole parameter. This callable can either be a function or a coroutine.

In order to customise the flag syntax we also have a few options that can be passed to the class parameter list:

# --hello world syntax
class PosixLikeFlags(commands.FlagConverter, delimiter=' ', prefix='--'):
    hello: str


# /make food
class WindowsLikeFlags(commands.FlagConverter, prefix='/', delimiter=''):
    make: str

# TOPIC: not allowed nsfw: yes Slowmode: 100
class Settings(commands.FlagConverter, case_insensitive=True):
    topic: Optional[str]
    nsfw: Optional[bool]
    slowmode: Optional[int]

Note

Despite the similarities in these examples to command like arguments, the syntax and parser is not a command line parser. The syntax is mainly inspired by Discord’s search bar input and as a result all flags need a corresponding value.

The flag converter is similar to regular commands and allows you to use most types of converters (with the exception of Greedy) as the type annotation. Some extra support is added for specific annotations as described below.

typing.List

If a list is given as a flag annotation it tells the parser that the argument can be passed multiple times.

For example, augmenting the example above:

from datetime import timedelta
from typing import List

class BanFlags(commands.FlagConverter):
    members: List[disnake.Member] = commands.flag(name='member')
    reason: str
    days: int = 1

@bot.command()
async def ban(ctx, *, flags: BanFlags):
    for member in flags.members:
        await member.ban(reason=flags.reason, clean_history_duration=timedelta(days=flags.days))

    members = ', '.join(str(member) for member in flags.members)
    plural = f'{flags.days} days' if flags.days != 1 else f'{flags.days} day'
    await ctx.send(f'Banned {members} for {flags.reason!r} (deleted {plural} worth of messages)')

This is called by repeatedly specifying the flag:

_images/flags2.png
typing.Tuple

Since the above syntax can be a bit repetitive when specifying a flag many times, the tuple type annotation allows for “greedy-like” semantics using a variadic tuple:

from disnake.ext import commands
from typing import Tuple
import disnake

class BanFlags(commands.FlagConverter):
    members: Tuple[disnake.Member, ...]
    reason: str
    days: int = 1

This allows the previous ban command to be called like this:

_images/flags3.png

The tuple annotation also allows for parsing of pairs. For example, given the following code:

# point: 10 11 point: 12 13
class Coordinates(commands.FlagConverter):
    point: Tuple[int, int]

Warning

Due to potential parsing ambiguities, the parser expects tuple arguments to be quoted if they require spaces. So if one of the inner types is str and the argument requires spaces then quotes should be used to disambiguate it from the other element of the tuple.

typing.Dict

A dict annotation is functionally equivalent to List[Tuple[K, V]] except with the return type given as a dict rather than a list.

Error Handling

When our commands fail to parse we will, by default, receive a noisy error in stderr of our console that tells us that an error has happened and has been silently ignored.

In order to handle our errors, we must use something called an error handler. There is a global error handler, called on_command_error() which works like any other event in the Event Reference. This global error handler is called for every error reached.

Most of the time however, we want to handle an error local to the command itself. Luckily, commands come with local error handlers that allow us to do just that. First we decorate an error handler function with Command.error():

@bot.command()
async def info(ctx, *, member: disnake.Member):
    """Tells you some info about the member."""
    msg = f'{member} joined on {member.joined_at} and has {len(member.roles)} roles.'
    await ctx.send(msg)

@info.error
async def info_error(ctx, error):
    if isinstance(error, commands.BadArgument):
        await ctx.send('I could not find that member...')

The first parameter of the error handler is the Context while the second one is an exception that is derived from CommandError. A list of errors is found in the Exceptions page of the documentation.

Checks

There are cases when we don’t want a user to use our commands. They don’t have permissions to do so or maybe we blocked them from using our bot earlier. The commands extension comes with full support for these things in a concept called a Checks.

A check is a basic predicate that can take in a Context as its sole parameter. Within it, you have the following options:

  • Return True to signal that the person can run the command.

  • Return False to signal that the person cannot run the command.

  • Raise a CommandError derived exception to signal the person cannot run the command.

    • This allows you to have custom error messages for you to handle in the error handlers.

To register a check for a command, we would have two ways of doing so. The first is using the check() decorator. For example:

async def is_owner(ctx):
    return ctx.author.id == 316026178463072268

@bot.command(name='eval')
@commands.check(is_owner)
async def _eval(ctx, *, code):
    """A bad example of an eval command"""
    await ctx.send(eval(code))

This would only evaluate the command if the function is_owner returns True. Sometimes we re-use a check often and want to split it into its own decorator. To do that we can just add another level of depth:

def is_owner():
    async def predicate(ctx):
        return ctx.author.id == 316026178463072268
    return commands.check(predicate)

@bot.command(name='eval')
@is_owner()
async def _eval(ctx, *, code):
    """A bad example of an eval command"""
    await ctx.send(eval(code))

Since an owner check is so common, the library provides it for you (is_owner()):

@bot.command(name='eval')
@commands.is_owner()
async def _eval(ctx, *, code):
    """A bad example of an eval command"""
    await ctx.send(eval(code))

When multiple checks are specified, all of them must be True:

def is_in_guild(guild_id):
    async def predicate(ctx):
        return ctx.guild and ctx.guild.id == guild_id
    return commands.check(predicate)

@bot.command()
@commands.is_owner()
@is_in_guild(41771983423143937)
async def secretguilddata(ctx):
    """super secret stuff"""
    await ctx.send('secret stuff')

If any of those checks fail in the example above, then the command will not be run.

When an error happens, the error is propagated to the error handlers. If you do not raise a custom CommandError derived exception, then it will get wrapped up into a CheckFailure exception as so:

@bot.command()
@commands.is_owner()
@is_in_guild(41771983423143937)
async def secretguilddata(ctx):
    """super secret stuff"""
    await ctx.send('secret stuff')

@secretguilddata.error
async def secretguilddata_error(ctx, error):
    if isinstance(error, commands.CheckFailure):
        await ctx.send('nothing to see here comrade.')

If you want a more robust error system, you can derive from the exception and raise it instead of returning False:

class NoPrivateMessages(commands.CheckFailure):
    pass

def guild_only():
    async def predicate(ctx):
        if ctx.guild is None:
            raise NoPrivateMessages('Hey no DMs!')
        return True
    return commands.check(predicate)

@guild_only()
async def test(ctx):
    await ctx.send('Hey this is not a DM! Nice.')

@test.error
async def test_error(ctx, error):
    if isinstance(error, NoPrivateMessages):
        await ctx.send(error)

Note

Since having a guild_only decorator is pretty common, it comes built-in via guild_only().

Global Checks

Sometimes we want to apply a check to every command, not just certain commands. The library supports this as well using the global check concept.

Global checks work similarly to regular checks except they are registered with the Bot.check() decorator.

For example, to block all DMs we could do the following:

@bot.check
async def globally_block_dms(ctx):
    return ctx.guild is not None

Warning

Be careful on how you write your global checks, as it could also lock you out of your own bot.

Slash Commands

Slash commands can significantly simplify the user’s experience with your bot. Once “/” is pressed on the keyboard, the list of slash commands appears. You can fill the options and read the hints at the same time, while types are validated instantly. This library allows to make such commands in several minutes, regardless of their complexity.

Getting started

You have probably noticed that slash commands have really interactive user interface, as if each slash command was built-in. This is because each slash command is registered in Discord before people can see it. This library handles registration for you, but you can still manage it.

By default, the registration is global. This means that your slash commands will be visible everywhere, including bot DMs, though you can disable them in DMs by setting the appropriate permissions. You can also change the registration to be local, so your slash commands will only be visible in several guilds.

This code sample shows how to set the registration to be local:

from disnake.ext import commands

bot = commands.Bot(
    command_prefix='!',
    test_guilds=[123456789],
    # In the list above you can specify the IDs of your test guilds.
    # Why is this kwarg called test_guilds? This is because you're not meant to use
    # local registration in production, since you may exceed the rate limits.
)

For global registration, don’t specify this parameter.

Another useful parameter is sync_commands_debug. If set to True, you receive debug messages related to the app command registration by default, without having to change the log level of any loggers (see Bot.sync_commands_debug for more info). This is useful if you want to figure out some registration details:

from disnake.ext import commands

bot = commands.Bot(
    command_prefix='!',
    test_guilds=[123456789], # Optional
    sync_commands_debug=True
)

If you want to disable the automatic registration, set sync_commands to False:

from disnake.ext import commands

bot = commands.Bot(
    command_prefix='!',
    sync_commands=False
)
Basic Slash Command

Make sure that you’ve read Getting started, it contains important information about command registration.

Here’s an example of a slash command:

@bot.slash_command(description="Responds with 'World'")
async def hello(inter):
    await inter.response.send_message("World")

A slash command must always have at least one parameter, inter, which is the ApplicationCommandInteraction as the first one.

I can’t see my slash command, what do I do? Read Getting started.

Parameters

You may want to define a couple of options for your slash command. In disnake, the definition of options is based on annotations.

Here’s an example of a command with one integer option (without a description):

@bot.slash_command(description="Multiplies the number by 7")
async def multiply(inter, number: int):
    await inter.response.send_message(number * 7)

The result should look like this:

_images/int_option.png

You can of course set a default for your option by giving a default value:

@bot.slash_command(description="Multiplies the number by a multiplier")
async def multiply(inter, number: int, multiplier: int = 7):
    await inter.response.send_message(number * multiplier)

You may have as many options as you want but the order matters, an optional option cannot be followed by a required one.

Option Types

You might already be familiar with discord.py’s converters, slash commands have a very similar equivalent in the form of option types. Discord itself supports only a few built-in types which are guaranteed to be enforced:

All the other types may be converted implicitly, similarly to Basic Converters

@bot.slash_command()
async def multiply(
    interaction,
    string: str,
    integer: int,
    number: float,
    user: disnake.User,
    emoji: disnake.Emoji,
    message: disnake.Message
):
    ...

Note

* All channel subclasses and unions (e.g. Union[TextChannel, StageChannel]) are also supported. See ParamInfo.channel_types for more fine-grained control.

** Some combinations of types are also allowed, including:

Note that a User annotation can also result in a Member being received.

*** Corresponds to any mentionable type, currently equivalent to Union[User, Member, Role].

Number Ranges

int and float parameters support minimum and maximum allowed values using the lt, le, gt, ge parameters on Param. For instance, you could restrict an option to only accept positive integers:

@bot.slash_command()
async def command(
    inter: disnake.ApplicationCommandInteraction,
    amount: int = commands.Param(gt=0),
):
    ...

Instead of using Param, you can also use a Range annotation. The range bounds are both inclusive; using ... as a bound indicates that this end of the range is unbounded. The type of the option is determined by the range bounds, with the option being a float if at least one of the bounds is a float, and int otherwise.

@bot.slash_command()
async def ranges(
    inter: disnake.ApplicationCommandInteraction,
    a: commands.Range[0, 10],       # 0 - 10 int
    b: commands.Range[0, 10.0],     # 0 - 10 float
    c: commands.Range[1, ...],      # positive int
):
    ...

Note

Type checker support for Range and String (see below) is limited. Pylance/Pyright seem to handle it correctly; MyPy currently needs a plugin for it to understand Range and String semantics, which can be added in the configuration file (setup.cfg, mypy.ini):

[mypy]
plugins = disnake.ext.mypy_plugin

For pyproject.toml configs, use this instead:

[tool.mypy]
plugins = "disnake.ext.mypy_plugin"
String Lengths

str parameters support minimum and maximum allowed value lengths using the min_length and max_length parameters on Param. For instance, you could restrict an option to only accept a single character:

@bot.slash_command()
async def charinfo(
    inter: disnake.ApplicationCommandInteraction,
    character: str = commands.Param(max_length=1),
):
    ...

Or restrict a tag command to limit tag names to 20 characters:

@bot.slash_command()
async def tags(
    inter: disnake.ApplicationCommandInteraction,
    tag: str = commands.Param(max_length=20)
):
    ...

Instead of using Param, you can also use a String annotation. The length bounds are both inclusive; using ... as a bound indicates that this end of the string length is unbounded.

@bot.slash_command()
async def strings(
    inter: disnake.ApplicationCommandInteraction,
    a: commands.String[0, 10],       # a str no longer than 10 characters.
    b: commands.String[10, 100],     # a str that's at least 10 characters but not longer than 100.
    c: commands.String[50, ...]      # a str that's at least 50 characters.
):
    ...

Note

There is a max length of 6000 characters, which is enforced by Discord.

Note

For mypy type checking support, please see the above note about the mypy plugin.

Docstrings

If you have a feeling that option descriptions make the parameters of your function look overloaded, use docstrings. This feature allows to describe your command and options in triple quotes inside the function, following the RST markdown.

In order to describe the parameters, list them under the Parameters header, underlined with dashes:

@bot.slash_command()
async def give_cookies(
    inter: disnake.ApplicationCommandInteraction,
    user: disnake.User,
    amount: int = 1
):
    """
    Give several cookies to a user

    Parameters
    ----------
    user: The user to give cookies to
    amount: The amount of cookies to give
    """
    ...

Note

In the above example we’re using a simplified RST markdown.

If you prefer the real RST format, you can still use it:

@bot.slash_command()
async def give_cookies(
    inter: disnake.ApplicationCommandInteraction,
    user: disnake.User,
    amount: int = 1
):
    """
    Give several cookies to a user

    Parameters
    ----------
    user: :class:`disnake.User`
        The user to give cookies to
    amount: :class:`int`
        The amount of cookies to give
    """
    ...
Parameter Descriptors

Python has no truly clean way to provide metadata for parameters, so disnake uses the same approach as fastapi using parameter defaults. At the current time there’s only Param.

With this you may set the name, description, custom converters, Autocompleters, and more.

@bot.slash_command()
async def math(
    interaction: disnake.ApplicationCommandInteraction,
    a: int = commands.Param(le=10),
    b: int = commands.Param(le=10),
    op: str = commands.Param(name="operator", choices=["+", "-", "/", "*"])
):
    """
    Perform an operation on two numbers as long as both of them are less than or equal to 10
    """
    ...
@bot.slash_command()
async def multiply(
    interaction: disnake.ApplicationCommandInteraction,
    clean: str = commands.Param(converter=lambda inter, arg: arg.replace("@", "\\@")
):
    ...

Note

The converter parameter only ever takes in a function, not a Converter class. Converter classes are completely unusable in disnake due to their inconsistent typing.

Choices

Some options can have a list of choices, so the user doesn’t have to manually fill the value. The most elegant way of defining the choices is by using enums. These enums must inherit from the type of their value if you want them to work with linters.

For example:

from enum import Enum

class Animal(str, Enum):
    Dog = 'dog'
    Cat = 'cat'
    Penguin = 'peng'

@bot.slash_command()
async def blep(inter: disnake.ApplicationCommandInteraction, animal: Animal):
    await inter.response.send_message(animal)

Note

The animal arg will receive one of the enum values.

You can define an enum in one line:

Animal = commands.option_enum({"Dog": "dog", "Cat": "cat", "Penguin": "penguin"})

@bot.slash_command()
async def blep(inter: disnake.ApplicationCommandInteraction, animal: Animal):
    await inter.response.send_message(animal)

Or even forget about values and define the enum from list:

Animal = commands.option_enum(["Dog", "Cat", "Penguin"])

@bot.slash_command()
async def blep(inter: disnake.ApplicationCommandInteraction, animal: Animal):
    await inter.response.send_message(animal)

Or you can simply list the choices in commands.Param:

@bot.slash_command()
async def blep(
    inter: disnake.ApplicationCommandInteraction,
    animal: str = commands.Param(choices={"Dog": "dog", "Cat": "cat", "Penguin": "penguin"})
):
    await inter.response.send_message(animal)

# Or define the choices in a list

@bot.slash_command()
async def blep(
    inter: disnake.ApplicationCommandInteraction,
    animal: str = commands.Param(choices=["Dog", "Cat", "Penguin"])
):
    await inter.response.send_message(animal)
Autocompleters

Slash commands support interactive autocompletion. You can define a function that will constantly suggest autocomplete options while the user is typing. So basically autocompletion is roughly equivalent to dynamic choices.

In order to build an option with autocompletion, define a function that takes 2 parameters - ApplicationCommandInteraction instance, representing an autocomp interaction with your command, and a str instance, representing the current user input. The function should return a list of strings or a mapping of choice names to values.

For example:

LANGUAGES = ["python", "javascript", "typescript", "java", "rust", "lisp", "elixir"]

async def autocomp_langs(inter: disnake.ApplicationCommandInteraction, user_input: str):
    return [lang for lang in LANGUAGES if user_input.lower() in lang]

@bot.slash_command()
async def example(
    inter: disnake.ApplicationCommandInteraction,
    language: str = commands.Param(autocomplete=autocomp_langs)
):
    ...

In case you need don’t want to use Param or need to use self in a cog you may create autocomplete options with the autocomplete decorator:

@bot.slash_command()
async def languages(inter: disnake.ApplicationCommandInteraction, language: str):
    pass


@languages.autocomplete("language")
async def language_autocomp(inter: disnake.ApplicationCommandInteraction, string: str):
    string = string.lower()
    return [lang for lang in LANGUAGES if string in lang.lower()]
    ...
Subcommands And Groups

Groups of commands work differently in terms of slash commands. Instead of defining a group, you should still define a slash command and then nest some sub-commands or sub-command-groups there via special decorators.

For example, here’s how you make a /show user command:

@bot.slash_command()
async def show(inter):
    # Here you can paste some code, it will run for every invoked sub-command.
    pass

@show.sub_command()
async def user(inter, user: disnake.User):
    """
    Description of the subcommand

    Parameters
    ----------
    user: Enter the user to inspect
    """
    ...

Note

After being registered this command will be visible as /show user in the list, not allowing you to invoke /show without any sub-commands. This is an API limitation.

You can implement double nesting and build commands like /parent group subcmd:

@bot.slash_command()
async def parent(inter):
    pass

@parent.sub_command_group()
async def group(inter):
    pass

@group.sub_command()
async def subcmd(inter):
    # Some stuff
    pass

Note

This is the deepest nesting available.

Injections

We have them, look at this example for more information ✨

Localizations

The names and descriptions of commands and options, as well as the names of choices (for use with fixed choices or autocompletion), support localization for a fixed set of locales.

For currently supported locales, see Locale.

Note

You can supply your own custom localization provider by implementing LocalizationProtocol and using the client’s/bot’s localization_provider parameter. The .json handling mentioned in this section, as well as the Strict Localization section below only apply to the default implementation, LocalizationStore.

The preferred way of adding localizations is to use <locale>.json files, containing mappings from user-defined keys to localized/translated strings, and referencing these keys in the commands’ docstrings. As an example, consider this command:

@bot.slash_command()
async def add_5(inter: disnake.ApplicationCommandInteraction, num: int):
    """
    Adds 5 to a number. {{ADD_NUM}}

    Parameters
    ----------
    num: Some number {{ COOL_NUMBER }}
    """
    await inter.response.send_message(f"{num} + 5 = {num + 5}")

The keys {{XYZ}} are automatically extracted from the docstrings, and used for looking up names XYZ_NAME and descriptions XYZ_DESCRIPTION. Note that whitespace is ignored, and the positioning inside the line doesn’t matter.

For instance, to add German localizations, create a locale/de.json file; the directory name/path can be changed arbitrarily, locale is just the one used here:

{
    "ADD_NUM_NAME": "addiere_5",
    "ADD_NUM_DESCRIPTION": "Addiere 5 zu einer anderen Zahl.",
    "COOL_NUMBER_NAME": "zahl",
    "COOL_NUMBER_DESCRIPTION": "Eine Zahl"
}

To load a directory or file containing localizations, use bot.i18n.load(path):

...
bot.i18n.load("locale/")  # loads all files in the "locale/" directory
bot.run(...)

Note

If Bot.reload is True, all currently loaded localization files are reloaded when an extension gets automatically reloaded.

Strict Localization

By default, missing keys that couldn’t be found are silently ignored. To instead raise an exception when a key is missing, pass the strict_localization=True parameter to the client/bot constructor (see Bot.strict_localization).

Customization

If you want more customization or low-level control over localizations, you can specify arbitrary keys for the commands/options directly. Localized takes the non-localized string (optional depending on target type) to keep the ability of e.g. overwriting name in the command decorator, and either a key or data parameter.

This would create the same command as the code above, though you’re free to change the keys like ADD_NUM_DESCRIPTION however you want:

@bot.slash_command(name=Localized("add_5", key="ADD_NUM_NAME"), description=Localized(key="ADD_NUM_DESCRIPTION"))
async def _add_5_slash(
    inter: disnake.ApplicationCommandInteraction,
    num: int = commands.Param(
        name=Localized(key="COOL_NUMBER_NAME"),
        description=Localized(key="COOL_NUMBER_DESCRIPTION")
    ),
):
    """
    Adds 5 to a number.

    Parameters
    ----------
    num: Some number
    """
    await inter.response.send_message(f"{num} + 5 = {num + 5}")

While not recommended, it is also possible to avoid using .json files at all, and instead specify localizations directly in the code:

@bot.slash_command(
    name=Localized(data={Locale.de: "addiere_5"}),
    description=Localized(data={Locale.de: "Addiere 5 zu einer anderen Zahl."}),
)
async def add_5(
    inter: disnake.ApplicationCommandInteraction,
    num: int = commands.Param(
        name=Localized(data={Locale.de: "zahl"}),
        description=Localized(data={Locale.de: "Eine Zahl"}),
    ),
):
    ...
Choices/Autocomplete

Option choices and autocomplete items can also be localized, through the use of OptionChoice:

@bot.slash_command()
async def example(
    inter: disnake.ApplicationCommandInteraction,
    animal: str = commands.Param(choices=[
        # alternatively:
        # OptionChoice(Localized("Cat", key="OPTION_CAT"), "Cat")
        Localized("Cat", key="OPTION_CAT"),
        Localized("Dolphin", key="OPTION_DOLPHIN"),
    ]),
    language: str = commands.Param(autocomplete=autocomp_langs),
):
    ...

@example.autocomplete("language")
async def language_autocomp(inter: disnake.ApplicationCommandInteraction, user_input: str):
    languages = ("english", "german", "spanish", "japanese")
    return [
        # alternatively:
        # `OptionChoice(Localized(lang, key=f"AUTOCOMP_{lang.upper()}"), lang)`
        Localized(lang, key=f"AUTOCOMP_{lang.upper()}")
        for lang in languages
        if user_input.lower() in lang
    ]

Yet again, with a file like locale/de.json containing localizations like this:

{
    "OPTION_CAT": "Katze",
    "OPTION_DOLPHIN": "Delfin",
    "AUTOCOMP_ENGLISH": "Englisch",
    "AUTOCOMP_GERMAN": "Deutsch",
    "AUTOCOMP_SPANISH": "Spanisch",
    "AUTOCOMP_JAPANESE": "Japanisch"
}
Permissions
Default Member Permissions

These commands will not be enabled/visible for members who do not have all the required guild permissions. In this example both the manage_guild and the moderate_members permissions would be required:

@bot.slash_command()
@commands.default_member_permissions(manage_guild=True, moderate_members=True)
async def command(inter: disnake.ApplicationCommandInteraction):
    ...

Or use the default_member_permissions parameter in the application command decorator:

@bot.slash_command(default_member_permissions=disnake.Permissions(manage_guild=True, moderate_members=True))
async def command(inter: disnake.ApplicationCommandInteraction):
    ...

This can be overridden by moderators on a per-guild basis; default_member_permissions may be ignored entirely once a permission override — application-wide or for this command in particular — is configured in the guild settings, and will be restored if the permissions are re-synced in the settings.

Note that default_member_permissions and dm_permission cannot be configured for a slash subcommand or subcommand group, only in top-level slash commands and user/message commands.

DM Permissions

Using this, you can specify if you want a certain slash command to work in DMs or not:

@bot.slash_command(dm_permission=False)
async def config(inter: disnake.ApplicationCommandInteraction):
    ...

This will make the config slash command invisible in DMs, while it will remain visible in guilds.

Cogs

There comes a point in your bot’s development when you want to organize a collection of commands, listeners, and some state into one class. Cogs allow you to do just that.

The gist:

It should be noted that cogs are typically used alongside with Extensions.

Quick Example

This example cog defines a Greetings category for your commands, with a single command named hello as well as a listener to listen to an Event.

class Greetings(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self._last_member = None

    @commands.Cog.listener()
    async def on_member_join(self, member):
        channel = member.guild.system_channel
        if channel is not None:
            await channel.send(f'Welcome {member.mention}.')

    @commands.command()
    async def hello(self, ctx, *, member: disnake.Member = None):
        """Says hello"""
        member = member or ctx.author
        if self._last_member is None or self._last_member.id != member.id:
            await ctx.send(f'Hello {member.name}~')
        else:
            await ctx.send(f'Hello {member.name}... This feels familiar.')
        self._last_member = member

A couple of technical notes to take into consideration:

  • All listeners must be explicitly marked via decorator, listener().

  • The name of the cog is automatically derived from the class name but can be overridden. See Meta Options.

  • All commands must now take a self parameter to allow usage of instance attributes that can be used to maintain state.

Cog Registration

Once you have defined your cogs, you need to tell the bot to register the cogs to be used. We do this via the add_cog() method.

bot.add_cog(Greetings(bot))

This binds the cog to the bot, adding all commands and listeners to the bot automatically.

Note that we reference the cog by name, which we can override through Meta Options. So if we ever want to remove the cog eventually, we would have to do the following.

bot.remove_cog('Greetings')
Using Cogs

Just as we remove a cog by its name, we can also retrieve it by its name as well. This allows us to use a cog as an inter-command communication protocol to share data. For example:

class Economy(commands.Cog):
    ...

    async def withdraw_money(self, member, money):
        # implementation here
        ...

    async def deposit_money(self, member, money):
        # implementation here
        ...

class Gambling(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    def coinflip(self):
        return random.randint(0, 1)

    @commands.command()
    async def gamble(self, ctx, money: int):
        """Gambles some money."""
        economy = self.bot.get_cog('Economy')
        if economy is not None:
            await economy.withdraw_money(ctx.author, money)
            if self.coinflip() == 1:
                await economy.deposit_money(ctx.author, money * 1.5)
Special Methods

As cogs get more complicated and have more commands, there comes a point where we want to customise the behaviour of the entire cog or bot.

They are as follows:

You can visit the reference to get more detail.

Meta Options

At the heart of a cog resides a metaclass, commands.CogMeta, which can take various options to customise some of the behaviour. To do this, we pass keyword arguments to the class definition line. For example, to change the cog name we can pass the name keyword argument as follows:

class MyCog(commands.Cog, name='My Cog'):
    pass

To see more options that you can set, see the documentation of commands.CogMeta.

Inspection

Since cogs ultimately are classes, we have some tools to help us inspect certain properties of the cog.

To get a list of commands, we can use Cog.get_commands().

>>> cog = bot.get_cog('Greetings')
>>> commands = cog.get_commands()
>>> print([c.name for c in commands])

If we want to get the subcommands as well, we can use the Cog.walk_commands() generator.

>>> print([c.qualified_name for c in cog.walk_commands()])

To do the same with listeners, we can query them with Cog.get_listeners(). This returns a list of tuples – the first element being the listener name and the second one being the actual function itself.

>>> for name, func in cog.get_listeners():
...     print(name, '->', func)

Extensions

There comes a time in the bot development when you want to extend the bot functionality at run-time and quickly unload and reload code (also called hot-reloading). The command framework comes with this ability built-in, with a concept called extensions.

Primer

An extension at its core is a python file with an entry point called setup. This setup must be a plain Python function (not a coroutine). It takes a single parameter – the Bot that loads the extension.

An example extension looks like this:

hello.py
from disnake.ext import commands

@commands.command()
async def hello(ctx):
    await ctx.send(f'Hello {ctx.author.display_name}.')

def setup(bot):
    bot.add_command(hello)

In this example we define a simple command, and when the extension is loaded this command is added to the bot. Now the final step to this is loading the extension, which we do by calling Bot.load_extension(). To load this extension we call bot.load_extension('hello').

Cogs

Extensions are usually used in conjunction with cogs. To read more about them, check out the documentation, Cogs.

Note

Extension paths are ultimately similar to the import mechanism. What this means is that if there is a folder, then it must be dot-qualified. For example to load an extension in plugins/hello.py then we use the string plugins.hello.

Reloading

When you make a change to the extension and want to reload the references, the library comes with a function to do this for you, Bot.reload_extension().

>>> bot.reload_extension('hello')

Once the extension reloads, any changes that we did will be applied. This is useful if we want to add or remove functionality without restarting our bot. If an error occurred during the reloading process, the bot will pretend as if the reload never happened.

Cleaning Up

Although rare, sometimes an extension needs to clean-up or know when it’s being unloaded. For cases like these, there is another entry point named teardown which is similar to setup except called when the extension is unloaded.

basic_ext.py
def setup(bot):
    print('I am being loaded!')

def teardown(bot):
    print('I am being unloaded!')

API Reference

The following section outlines the API of disnake’s command extension module.

Bots
Bot
Methods
class disnake.ext.commands.Bot(command_prefix=None, help_command=<default-help-command>, description=None, *, strip_after_prefix=False, **options)[source]

Represents a discord bot.

This class is a subclass of disnake.Client and as a result anything that you can do with a disnake.Client you can do with this bot.

This class also subclasses GroupMixin to provide the functionality to manage commands.

command_prefix

The command prefix is what the message content must contain initially to have a command invoked. This prefix could either be a string to indicate what the prefix should be, or a callable that takes in the bot as its first parameter and disnake.Message as its second parameter and returns the prefix. This is to facilitate “dynamic” command prefixes. This callable can be either a regular function or a coroutine.

An empty string as the prefix always matches, enabling prefix-less command invocation. While this may be useful in DMs it should be avoided in servers, as it’s likely to cause performance issues and unintended command invocations.

The command prefix could also be an iterable of strings indicating that multiple checks for the prefix should be used and the first one to match will be the invocation prefix. You can get this prefix via Context.prefix. To avoid confusion empty iterables are not allowed.

If the prefix is None, the bot won’t listen to any prefixes, and prefix commands will not be processed. If you don’t need prefix commands, consider using InteractionBot or AutoShardedInteractionBot instead, which are drop-in replacements, just without prefix command support.

Note

When passing multiple prefixes be careful to not pass a prefix that matches a longer prefix occurring later in the sequence. For example, if the command prefix is ('!', '!?') the '!?' prefix will never be matched to any message as the previous one matches messages starting with !?. This is especially important when passing an empty string, it should always be last as no prefix after it will be matched.

case_insensitive

Whether the commands should be case insensitive. Defaults to False. This attribute does not carry over to groups. You must set it to every group if you require group commands to be case insensitive as well.

Type:

bool

description

The content prefixed into the default help message.

Type:

str

help_command[source]

The help command implementation to use. This can be dynamically set at runtime. To remove the help command pass None. For more information on implementing a help command, see Help Commands.

Type:

Optional[HelpCommand]

owner_id

The user ID that owns the bot. If this is not set and is then queried via is_owner() then it is fetched automatically using application_info().

Type:

Optional[int]

owner_ids

The user IDs that owns the bot. This is similar to owner_id. If this is not set and the application is team based, then it is fetched automatically using application_info(). For performance reasons it is recommended to use a set for the collection. You cannot set both owner_id and owner_ids.

New in version 1.3.

Type:

Optional[Collection[int]]

strip_after_prefix

Whether to strip whitespace characters after encountering the command prefix. This allows for !   hello and !hello to both work if the command_prefix is set to !. Defaults to False.

New in version 1.7.

Type:

bool

test_guilds

The list of IDs of the guilds where you’re going to test your application commands. Defaults to None, which means global registration of commands across all guilds.

New in version 2.1.

Type:

List[int]

sync_commands

Whether to enable automatic synchronization of application commands in your code. Defaults to True, which means that commands in API are automatically synced with the commands in your code.

New in version 2.1.

Type:

bool

sync_commands_on_cog_unload

Whether to sync the application commands on cog unload / reload. Defaults to True.

New in version 2.1.

Type:

bool

sync_commands_debug

Whether to always show sync debug logs (uses INFO log level if it’s enabled, prints otherwise). If disabled, uses the default DEBUG log level which isn’t shown unless the log level is changed manually. Useful for tracking the commands being registered in the API. Defaults to False.

New in version 2.1.

Changed in version 2.4: Changes the log level of corresponding messages from DEBUG to INFO or prints them, instead of controlling whether they are enabled at all.

Type:

bool

reload

Whether to enable automatic extension reloading on file modification for debugging. Whenever you save an extension with reloading enabled the file will be automatically reloaded for you so you do not have to reload the extension manually. Defaults to False

New in version 2.1.

Type:

bool

localization_provider

An implementation of LocalizationProtocol to use for localization of application commands. If not provided, the default LocalizationStore implementation is used.

New in version 2.5.

Type:

LocalizationProtocol

strict_localization

Whether to raise an exception when localizations for a specific key couldn’t be found. This is mainly useful for testing/debugging, consider disabling this eventually as missing localized names will automatically fall back to the default/base name without it. Only applicable if the localization_provider parameter is not provided. Defaults to False.

New in version 2.5.

Type:

bool

i18n

An implementation of LocalizationProtocol used for localization of application commands.

New in version 2.5.

Type:

LocalizationProtocol

@after_invoke[source]

A decorator that registers a coroutine as a post-invoke hook.

This is for text commands only, and doesn’t apply to application commands.

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.

This post-invoke hook takes a sole parameter, a Context.

Note

Similar to before_invoke(), this is not called unless checks and argument parsing procedures succeed. This hook is, however, always called regardless of the internal command callback raising an error (i.e. CommandInvokeError). 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.

@after_slash_command_invoke[source]

Similar to Bot.after_invoke() but for slash commands, and it takes an ApplicationCommandInteraction as its only parameter.

@after_user_command_invoke[source]

Similar to Bot.after_slash_command_invoke() but for user commands.

@after_message_command_invoke[source]

Similar to Bot.after_slash_command_invoke() but for message commands.

@before_invoke[source]

A decorator that registers a coroutine as a pre-invoke hook.

This is for text commands only, and doesn’t apply to application commands.

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

Note

The before_invoke() and after_invoke() hooks are only called if all checks and argument parsing procedures pass without error. If any check or argument parsing procedures fail 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.

@before_slash_command_invoke[source]

Similar to Bot.before_invoke() but for slash commands, and it takes an ApplicationCommandInteraction as its only parameter.

@before_user_command_invoke[source]

Similar to Bot.before_slash_command_invoke() but for user commands.

@before_message_command_invoke[source]

Similar to Bot.before_slash_command_invoke() but for message commands.

@check[source]

A decorator that adds a global check to the bot.

This is for text commands only, and doesn’t apply to application commands.

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 command the bot has.

Note

This function can either be a regular function or a coroutine.

Similar to a command check(), this takes a single parameter of type Context and can only raise exceptions inherited from CommandError.

Example

@bot.check
def check_commands(ctx):
    return ctx.command.qualified_name in allowed_commands
@check_once[source]

A decorator that adds a “call once” global check to the bot.

This is for text commands only, and doesn’t apply to application commands.

Unlike regular global checks, this one is called only once per invoke() call.

Regular global checks are called whenever a command is called or Command.can_run() is called. This type of check bypasses that and ensures that it’s called only once, even inside the default help command.

Note

When using this function the Context sent to a group subcommand may only parse the parent command and not the subcommands due to it being invoked once per Bot.invoke() call.

Note

This function can either be a regular function or a coroutine.

Similar to a command check(), this takes a single parameter of type Context and can only raise exceptions inherited from CommandError.

Example

@bot.check_once
def whitelist(ctx):
    return ctx.message.author.id in my_whitelist
@command(*args, **kwargs)[source]

A shortcut decorator that invokes command() and adds it to the internal command list via add_command().

Returns:

A decorator that converts the provided method into a Command, adds it to the bot, then returns it.

Return type:

Callable[…, Command]

@slash_command(*args, **kwargs)[source]

A shortcut decorator that invokes slash_command() and adds it to the internal command list.

Parameters:
  • name (Optional[Union[str, Localized]]) –

    The name of the slash command (defaults to function name).

    Changed in version 2.5: Added support for localizations.

  • description (Optional[Union[str, Localized]]) –

    The description of the slash command. It will be visible in Discord.

    Changed in version 2.5: Added support for localizations.

  • options (List[Option]) – The list of slash command options. The options will be visible in Discord. This is the old way of specifying options. Consider using Parameters instead.

  • dm_permission (bool) – Whether this command can be used in DMs. Defaults to True.

  • default_member_permissions (Optional[Union[Permissions, int]]) –

    The default required permissions for this command. See ApplicationCommand.default_member_permissions for details.

    New in version 2.5.

  • auto_sync (bool) – Whether to automatically register the command. Defaults to True

  • guild_ids (Sequence[int]) – If specified, the client will register the command in these guilds. Otherwise, this command will be registered globally.

  • connectors (Dict[str, str]) – Binds function names to option names. If the name of an option already matches the corresponding function param, you don’t have to specify the connectors. Connectors template: {"option-name": "param_name", ...}. If you’re using Parameters, you don’t need to specify this.

  • extras (Dict[str, Any]) –

    A dict of user provided extras to attach to the command.

    Note

    This object may be copied by the library.

    New in version 2.5.

Returns:

A decorator that converts the provided method into an InvokableSlashCommand, adds it to the bot, then returns it.

Return type:

Callable[…, InvokableSlashCommand]

@user_command(*args, **kwargs)[source]

A shortcut decorator that invokes user_command() and adds it to the internal command list.

Parameters:
  • name (Optional[Union[str, Localized]]) –

    The name of the user command (defaults to function name).

    Changed in version 2.5: Added support for localizations.

  • dm_permission (bool) – Whether this command can be used in DMs. Defaults to True.

  • default_member_permissions (Optional[Union[Permissions, int]]) –

    The default required permissions for this command. See ApplicationCommand.default_member_permissions for details.

    New in version 2.5.

  • auto_sync (bool) – Whether to automatically register the command. Defaults to True.

  • guild_ids (Sequence[int]) – If specified, the client will register the command in these guilds. Otherwise, this command will be registered globally.

  • extras (Dict[str, Any]) –

    A dict of user provided extras to attach to the command.

    Note

    This object may be copied by the library.

    New in version 2.5.

Returns:

A decorator that converts the provided method into an InvokableUserCommand, adds it to the bot, then returns it.

Return type:

Callable[…, InvokableUserCommand]

@message_command(*args, **kwargs)[source]

A shortcut decorator that invokes message_command() and adds it to the internal command list.

Parameters:
  • name (Optional[Union[str, Localized]]) –

    The name of the message command (defaults to function name).

    Changed in version 2.5: Added support for localizations.

  • dm_permission (bool) – Whether this command can be used in DMs. Defaults to True.

  • default_member_permissions (Optional[Union[Permissions, int]]) –

    The default required permissions for this command. See ApplicationCommand.default_member_permissions for details.

    New in version 2.5.

  • auto_sync (bool) – Whether to automatically register the command. Defaults to True

  • guild_ids (Sequence[int]) – If specified, the client will register the command in these guilds. Otherwise, this command will be registered globally.

  • extras (Dict[str, Any]) –

    A dict of user provided extras to attach to the command.

    Note

    This object may be copied by the library.

    New in version 2.5.

Returns:

A decorator that converts the provided method into an InvokableMessageCommand, adds it to the bot, then returns it.

Return type:

Callable[…, InvokableMessageCommand]

@event[source]

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.

@group(*args, **kwargs)[source]

A shortcut decorator that invokes group() and adds it to the internal command list via add_command().

Returns:

A decorator that converts the provided method into a Group, adds it to the bot, then returns it.

Return type:

Callable[…, Group]

@listen(name=None)[source]

A decorator that registers another function as an external event listener. Basically this allows you to listen to multiple events from different places e.g. such as on_ready()

The functions being listened to must be a coroutine.

Example

@bot.listen()
async def on_message(message):
    print('one')

# in some other file...

@bot.listen('on_message')
async def my_message(message):
    print('two')

Would print one and two in an unspecified order.

Raises:

TypeError – The function being listened to is not a coroutine.

property activity[source]

The activity being used upon logging in.

Type:

Optional[BaseActivity]

add_app_command_check(func, *, call_once=False, slash_commands=False, user_commands=False, message_commands=False)[source]

Adds a global application command check to the bot.

This is the non-decorator interface to check(), check_once(), slash_command_check() and etc.

You must specify at least one of the bool parameters, otherwise the check won’t be added.

Parameters:
  • func – The function that will be used as a global check.

  • call_once (bool) – Whether the function should only be called once per InvokableApplicationCommand.invoke() call.

  • slash_commands (bool) – Whether this check is for slash commands.

  • user_commands (bool) – Whether this check is for user commands.

  • message_commands (bool) – Whether this check is for message commands.

add_check(func, *, call_once=False)[source]

Adds a global check to the bot.

This is for text commands only, and doesn’t apply to application commands.

This is the non-decorator interface to check() and check_once().

Parameters:
  • func – The function that was used as a global check.

  • call_once (bool) – If the function should only be called once per invoke() call.

add_cog(cog, *, override=False)[source]

Adds a “cog” to the bot.

A cog is a class that has its own event listeners and commands.

Changed in version 2.0: ClientException is raised when a cog with the same name is already loaded.

Parameters:
  • cog (Cog) – The cog to register to the bot.

  • override (bool) –

    If a previously loaded cog with the same name should be ejected instead of raising an error.

    New in version 2.0.

Raises:
add_command(command)[source]

Adds a Command into the internal list of commands.

This is usually not called, instead the command() or group() shortcut decorators are used instead.

Changed in version 1.4: Raise CommandRegistrationError instead of generic ClientException

Parameters:

command (Command) – The command to add.

Raises:
add_listener(func, name=...)[source]

The non decorator alternative to listen().

Parameters:
  • func (coroutine) – The function to call.

  • name (str) – The name of the event to listen for. Defaults to func.__name__.

Example

async def on_ready(): pass
async def my_message(message): pass

bot.add_listener(on_ready)
bot.add_listener(my_message, 'on_message')
Raises:

TypeError – The function is not a coroutine.

add_message_command(message_command)[source]

Adds an InvokableMessageCommand into the internal list of message commands.

This is usually not called, instead the message_command() or shortcut decorators are used.

Parameters:

message_command (InvokableMessageCommand) – The message command to add.

Raises:
add_slash_command(slash_command)[source]

Adds an InvokableSlashCommand into the internal list of slash commands.

This is usually not called, instead the slash_command() or shortcut decorators are used.

Parameters:

slash_command (InvokableSlashCommand) – The slash command to add.

Raises:
add_user_command(user_command)[source]

Adds an InvokableUserCommand into the internal list of user commands.

This is usually not called, instead the user_command() or shortcut decorators are used.

Parameters:

user_command (InvokableUserCommand) – The user command to add.

Raises:
add_view(view, *, message_id=None)[source]

Registers a View for persistent listening.

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.

Parameters:
  • view (disnake.ui.View) – The view to register for dispatching.

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

Raises:
  • TypeError – A view was not passed.

  • ValueError – The view is not persistent. A persistent view has no timeout and all their components have an explicitly provided custom_id.

property allowed_mentions[source]

The allowed mention configuration.

New in version 1.4.

Type:

Optional[AllowedMentions]

application_command_check(*, call_once=False, slash_commands=False, user_commands=False, message_commands=False)[source]

A decorator that adds a global application command check to the bot.

A global check is similar to a check() that is applied on a per command basis except it is run before any application command checks have been verified and applies to every application command the bot has.

Note

This function can either be a regular function or a coroutine.

Similar to a command check(), this takes a single parameter of type ApplicationCommandInteraction and can only raise exceptions inherited from CommandError.

Example

@bot.application_command_check()
def check_app_commands(inter):
    return inter.channel_id in whitelisted_channels
Parameters:
  • call_once (bool) – Whether the function should only be called once per InvokableApplicationCommand.invoke() call.

  • slash_commands (bool) – Whether this check is for slash commands.

  • user_commands (bool) – Whether this check is for user commands.

  • message_commands (bool) – Whether this check is for message commands.

property application_commands[source]

A set of all application commands the bot has.

Type:

Set[InvokableApplicationCommand]

property application_flags[source]

The client’s application flags.

New in version 2.0.

Type:

ApplicationFlags

property application_id[source]

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]

await application_info()[source]

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 before_identify_hook(shard_id, *, initial=False)[source]

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 bulk_fetch_command_permissions(guild_id)[source]

This function is a coroutine.

Retrieves a list of GuildApplicationCommandPermissions configured for the guild with the given ID.

New in version 2.1.

Parameters:

guild_id (int) – The ID of the guild to inspect.

await bulk_overwrite_global_commands(application_commands)[source]

This function is a coroutine.

Overwrites several global application commands in one API request.

New in version 2.1.

Parameters:

application_commands (List[ApplicationCommand]) – A list of application commands to insert instead of the existing commands.

Returns:

A list of registered application commands.

Return type:

List[Union[APIUserCommand, APIMessageCommand, APISlashCommand]]

await bulk_overwrite_guild_commands(guild_id, application_commands)[source]

This function is a coroutine.

Overwrites several guild application commands in one API request.

New in version 2.1.

Parameters:
  • guild_id (int) – The ID of the guild where the application commands should be overwritten.

  • application_commands (List[ApplicationCommand]) – A list of application commands to insert instead of the existing commands.

Returns:

A list of registered application commands.

Return type:

List[Union[APIUserCommand, APIMessageCommand, APISlashCommand]]

property cached_messages[source]

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

New in version 1.1.

Type:

Sequence[Message]

await change_presence(*, activity=None, status=None)[source]

This function is a coroutine.

Changes the client’s presence.

Changed in version 2.6: Raises TypeError instead of InvalidArgument.

Example

game = disnake.Game("with the API")
await client.change_presence(status=disnake.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:

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

clear()[source]

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 close()[source]

This function is a coroutine.

Closes the connection to Discord.

property cogs[source]

A read-only mapping of cog name to cog.

Type:

Mapping[str, Cog]

property commands[source]

A unique set of commands without aliases that are registered.

Type:

Set[Command]

await connect(*, reconnect=True, ignore_session_start_limit=False)[source]

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.

Changed in version 2.6: Added usage of SessionStartLimit when connecting to the API. Added the ignore_session_start_limit parameter.

Parameters:
  • reconnect (bool) – Whether reconnecting should be attempted, 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).

  • ignore_session_start_limit (bool) –

    Whether the API provided session start limit should be ignored when connecting to the API.

    New in version 2.6.

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.

  • SessionStartLimitReached – If the client doesn’t have enough connects remaining in the current 24-hour window and ignore_session_start_limit is False this will be raised rather than connecting to the gateawy and Discord resetting the token. However, if ignore_session_start_limit is True, the client will connect regardless and this exception will not be raised.

await create_dm(user)[source]

This function is a coroutine.

Creates a DMChannel with the given 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

await create_global_command(application_command)[source]

This function is a coroutine.

Creates a global application command.

New in version 2.1.

Parameters:

application_command (ApplicationCommand) – An object representing the application command to create.

Returns:

The application command that was created.

Return type:

Union[APIUserCommand, APIMessageCommand, APISlashCommand]

await create_guild(*, name, icon=..., code=...)[source]

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.5: Removed the region parameter.

Changed in version 2.6: Raises ValueError instead of InvalidArgument.

Parameters:
Raises:
Returns:

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

Return type:

Guild

await create_guild_command(guild_id, application_command)[source]

This function is a coroutine.

Creates a guild application command.

New in version 2.1.

Parameters:
  • guild_id (int) – The ID of the guild where the application command should be created.

  • application_command (ApplicationCommand) – The application command.

Returns:

The newly created application command.

Return type:

Union[APIUserCommand, APIMessageCommand, APISlashCommand]

await delete_global_command(command_id)[source]

This function is a coroutine.

Deletes a global application command.

New in version 2.1.

Parameters:

command_id (int) – The ID of the application command to delete.

await delete_guild_command(guild_id, command_id)[source]

This function is a coroutine.

Deletes a guild application command.

New in version 2.1.

Parameters:
  • guild_id (int) – The ID of the guild where the applcation command should be deleted.

  • command_id (int) – The ID of the application command to delete.

await delete_invite(invite)[source]

This function is a coroutine.

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

You must have 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 edit_global_command(command_id, new_command)[source]

This function is a coroutine.

Edits a global application command.

New in version 2.1.

Parameters:
  • command_id (int) – The ID of the application command to edit.

  • new_command (ApplicationCommand) – An object representing the edited application command.

Returns:

The edited application command.

Return type:

Union[APIUserCommand, APIMessageCommand, APISlashCommand]

await edit_guild_command(guild_id, command_id, new_command)[source]

This function is a coroutine.

Edits a guild application command.

New in version 2.1.

Parameters:
  • guild_id (int) – The ID of the guild where the application command should be edited.

  • command_id (int) – The ID of the application command to edit.

  • new_command (ApplicationCommand) – An object representing the edited application command.

Returns:

The newly edited application command.

Return type:

Union[APIUserCommand, APIMessageCommand, APISlashCommand]

property emojis[source]

The emojis that the connected client has.

Type:

List[Emoji]

property extensions[source]

A read-only mapping of extension name to extension.

Type:

Mapping[str, types.ModuleType]

await fetch_channel(channel_id, /)[source]

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.

Parameters:

channel_id (int) – The ID of the channel to retrieve.

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_command_permissions(guild_id, command_id)[source]

This function is a coroutine.

Retrieves GuildApplicationCommandPermissions for a specific application command in the guild with the given ID.

New in version 2.1.

Parameters:
  • guild_id (int) – The ID of the guild to inspect.

  • command_id (int) –

    The ID of the application command, or the application ID to fetch application-wide permissions.

    Changed in version 2.5: Can now also fetch application-wide permissions.

Returns:

The permissions configured for the specified application command.

Return type:

GuildApplicationCommandPermissions

await fetch_global_command(command_id)[source]

This function is a coroutine.

Retrieves a global application command.

New in version 2.1.

Parameters:

command_id (int) – The ID of the command to retrieve.

Returns:

The requested application command.

Return type:

Union[APIUserCommand, APIMessageCommand, APISlashCommand]

await fetch_global_commands(*, with_localizations=True)[source]

This function is a coroutine.

Retrieves a list of global application commands.

New in version 2.1.

Parameters:

with_localizations (bool) –

Whether to include localizations in the response. Defaults to True.

New in version 2.5.

Returns:

A list of application commands.

Return type:

List[Union[APIUserCommand, APIMessageCommand, APISlashCommand]]

await fetch_guild(guild_id, /)[source]

This function is a coroutine.

Retrieves a Guild from the given ID.

Note

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

Note

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

Parameters:

guild_id (int) – The ID of the guild to retrieve.

Raises:
Returns:

The guild from the given ID.

Return type:

Guild

await fetch_guild_command(guild_id, command_id)[source]

This function is a coroutine.

Retrieves a guild application command.

New in version 2.1.

Parameters:
  • guild_id (int) – The ID of the guild to fetch command from.

  • command_id (int) – The ID of the application command to retrieve.

Returns:

The requested application command.

Return type:

Union[APIUserCommand, APIMessageCommand, APISlashCommand]

await fetch_guild_commands(guild_id, *, with_localizations=True)[source]

This function is a coroutine.

Retrieves a list of guild application commands.

New in version 2.1.

Parameters:
  • guild_id (int) – The ID of the guild to fetch commands from.

  • with_localizations (bool) –

    Whether to include localizations in the response. Defaults to True.

    New in version 2.5.

Returns:

A list of application commands.

Return type:

List[Union[APIUserCommand, APIMessageCommand, APISlashCommand]]

await fetch_guild_preview(guild_id, /)[source]

This function is a coroutine.

Retrieves a GuildPreview from the given ID. Your bot does not have to be in this guild.

Note

This method may fetch any guild that has DISCOVERABLE in Guild.features, but this information can not be known ahead of time.

This will work for any guild that you are in.

Parameters:

guild_id (int) – The ID of the guild to to retrieve a preview object.

Raises:

NotFound – Retrieving the guild preview failed.

Returns:

The guild preview from the given ID.

Return type:

GuildPreview

fetch_guilds(*, limit=100, before=None, after=None)[source]

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

  • 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 – Retrieving the guilds failed.

Yields:

Guild – The guild with the guild data parsed.

await fetch_invite(url, *, with_counts=True, with_expiration=True, guild_scheduled_event_id=None)[source]

This function is a coroutine.

Retrieves 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:
  • url (Union[Invite, str]) – The Discord invite ID or URL (must be a discord.gg URL).

  • with_counts (bool) – Whether to include count information in the invite. This fills the Invite.approximate_member_count and Invite.approximate_presence_count fields.

  • with_expiration (bool) –

    Whether to include the expiration date of the invite. This fills the Invite.expires_at field.

    New in version 2.0.

  • guild_scheduled_event_id (int) –

    The ID of the scheduled event to include in the invite. If not provided, defaults to the event parameter in the URL if it exists, or the ID of the scheduled event contained in the provided invite object.

    New in version 2.3.

Raises:
Returns:

The invite from the URL/ID.

Return type:

Invite

await fetch_premium_sticker_packs()[source]

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 fetch_stage_instance(channel_id, /)[source]

This function is a coroutine.

Retrieves a StageInstance with the given ID.

Note

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

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 – Retrieving the stage instance failed.

Returns:

The stage instance from the given ID.

Return type:

StageInstance

await fetch_sticker(sticker_id, /)[source]

This function is a coroutine.

Retrieves a Sticker with the given ID.

New in version 2.0.

Parameters:

sticker_id (int) – The ID of the sticker to retrieve.

Raises:
Returns:

The sticker you requested.

Return type:

Union[StandardSticker, GuildSticker]

await fetch_template(code)[source]

This function is a coroutine.

Retrieves 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:
Returns:

The template from the URL/code.

Return type:

Template

await fetch_user(user_id, /)[source]

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 disnake.Intents.members and member cache enabled, consider get_user() instead.

Parameters:

user_id (int) – The ID of the user to retrieve.

Raises:
Returns:

The user you requested.

Return type:

User

await fetch_voice_regions(guild_id=None)[source]

Retrieves a list of VoiceRegions.

Retrieves voice regions for the user, or a guild if provided.

New in version 2.5.

Parameters:

guild_id (Optional[int]) – The guild to get regions for, if provided.

Raises:
  • HTTPException – Retrieving voice regions failed.

  • NotFound – The provided guild_id could not be found.

await fetch_webhook(webhook_id, /)[source]

This function is a coroutine.

Retrieves a Webhook with the given ID.

Parameters:

webhook_id (int) – The ID of the webhook to retrieve.

Raises:
Returns:

The webhook you requested.

Return type:

Webhook

await fetch_widget(guild_id, /)[source]

This function is a coroutine.

Retrieves a Widget for the given guild ID.

Note

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

Parameters:

guild_id (int) – The ID of the guild.

Raises:
Returns:

The guild’s widget.

Return type:

Widget

for ... in get_all_channels()[source]

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()[source]

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.

get_channel(id, /)[source]

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_cog(name)[source]

Gets the cog instance requested.

If the cog is not found, None is returned instead.

Parameters:

name (str) – The name of the cog you are requesting. This is equivalent to the name passed via keyword argument in class creation or the class name if unspecified.

Returns:

The cog that was requested. If not found, returns None.

Return type:

Optional[Cog]

get_command(name)[source]

Get a Command from the internal list of commands.

This could also be used as a way to get aliases.

The name could be fully qualified (e.g. 'foo bar') will get the subcommand bar of the group command foo. If a subcommand is not found then None is returned just as usual.

Parameters:

name (str) – The name of the command to get.

Returns:

The command that was requested. If not found, returns None.

Return type:

Optional[Command]

await get_context(message, *, cls=<class 'disnake.ext.commands.context.Context'>)[source]

This function is a coroutine.

Returns the invocation context from the message.

This is a more low-level counter-part for process_commands() to allow users more fine grained control over the processing.

The returned context is not guaranteed to be a valid invocation context, Context.valid must be checked to make sure it is. If the context is not valid then it is not a valid candidate to be invoked under invoke().

Parameters:
  • message (disnake.Message) – The message to get the invocation context from.

  • cls – The factory class that will be used to create the context. By default, this is Context. Should a custom class be provided, it must be similar enough to Context’s interface.

Returns:

The invocation context. The type of this can change via the cls parameter.

Return type:

Context

get_emoji(id, /)[source]

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_global_command(id)[source]

Returns a global application command with the given ID.

Parameters:

id (int) – The ID to search for.

Returns:

The application command.

Return type:

Optional[Union[APIUserCommand, APIMessageCommand, APISlashCommand]]

get_global_command_named(name, cmd_type=None)[source]

Returns a global application command matching the given name.

Parameters:
  • name (str) – The name to look for.

  • cmd_type (ApplicationCommandType) – The type to look for. By default, no types are checked.

Returns:

The application command.

Return type:

Optional[Union[APIUserCommand, APIMessageCommand, APISlashCommand]]

get_guild(id, /)[source]

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_guild_application_commands(guild_id)[source]

Returns a list of all application commands in the guild with the given ID.

Parameters:

guild_id (int) – The ID to search for.

Returns:

The list of application commands.

Return type:

List[Union[APIUserCommand, APIMessageCommand, APISlashCommand]]

get_guild_command(guild_id, id)[source]

Returns a guild application command with the given guild ID and application command ID.

Parameters:
  • guild_id (int) – The guild ID to search for.

  • id (int) – The command ID to search for.

Returns:

The application command.

Return type:

Optional[Union[APIUserCommand, APIMessageCommand, APISlashCommand]]

get_guild_command_named(guild_id, name, cmd_type=None)[source]

Returns a guild application command matching the given name.

Parameters:
  • guild_id (int) – The guild ID to search for.

  • name (str) – The command name to search for.

  • cmd_type (ApplicationCommandType) – The type to look for. By default, no types are checked.

Returns:

The application command.

Return type:

Optional[Union[APIUserCommand, APIMessageCommand, APISlashCommand]]

get_guild_message_commands(guild_id)[source]

Returns a list of all message commands in the guild with the given ID.

Parameters:

guild_id (int) – The ID to search for.

Returns:

The list of message commands.

Return type:

List[APIMessageCommand]

get_guild_slash_commands(guild_id)[source]

Returns a list of all slash commands in the guild with the given ID.

Parameters:

guild_id (int) – The ID to search for.

Returns:

The list of slash commands.

Return type:

List[APISlashCommand]

get_guild_user_commands(guild_id)[source]

Returns a list of all user commands in the guild with the given ID.

Parameters:

guild_id (int) – The ID to search for.

Returns:

The list of user commands.

Return type:

List[APIUserCommand]

get_message(id)[source]

Gets the message with the given ID from the bot’s message cache.

Parameters:

id (int) – The ID of the message to look for.

Returns:

The corresponding message.

Return type:

Optional[Message]

get_message_command(name)[source]

Gets an InvokableMessageCommand from the internal list of message commands.

Parameters:

name (str) – The name of the message command to get.

Returns:

The message command that was requested. If not found, returns None.

Return type:

Optional[InvokableMessageCommand]

await get_or_fetch_user(user_id, *, strict=False)[source]

This function is a coroutine.

Tries to get the user from the cache. If fails, it tries to fetch the user from the API.

Parameters:
  • user_id (int) – The ID to search for.

  • strict (bool) – Whether to propagate exceptions from fetch_user() instead of returning None in case of failure (e.g. if the user wasn’t found). Defaults to False.

Returns:

The user with the given ID, or None if not found and strict is set to False.

Return type:

Optional[User]

get_partial_messageable(id, *, type=None)[source]

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

await get_prefix(message)[source]

This function is a coroutine.

Retrieves the prefix the bot is listening to with the message as a context.

Parameters:

message (disnake.Message) – The message context to get the prefix of.

Returns:

A list of prefixes or a single prefix that the bot is listening for. None if the bot isn’t listening for prefixes.

Return type:

Optional[Union[List[str], str]]

get_slash_command(name)[source]

Works like Bot.get_command, but for slash commands.

If the name contains spaces, then it will assume that you are looking for a SubCommand or a SubCommandGroup. e.g: 'foo bar' will get the sub command group, or the sub command bar of the top-level slash command foo if found, otherwise None.

Parameters:

name (str) – The name of the slash command to get.

Raises:

TypeError – The name is not a string.

Returns:

The slash command that was requested. If not found, returns None.

Return type:

Optional[Union[InvokableSlashCommand, SubCommandGroup, SubCommand]]

get_stage_instance(id, /)[source]

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 or None if not found.

Return type:

Optional[StageInstance]

get_sticker(id, /)[source]

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_user(id, /)[source]

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_user_command(name)[source]

Gets an InvokableUserCommand from the internal list of user commands.

Parameters:

name (str) – The name of the user command to get.

Returns:

The user command that was requested. If not found, returns None.

Return type:

Optional[InvokableUserCommand]

await getch_user(user_id, *, strict=False)[source]

This function is a coroutine.

Tries to get the user from the cache. If fails, it tries to fetch the user from the API.

Parameters:
  • user_id (int) – The ID to search for.

  • strict (bool) – Whether to propagate exceptions from fetch_user() instead of returning None in case of failure (e.g. if the user wasn’t found). Defaults to False.

Returns:

The user with the given ID, or None if not found and strict is set to False.

Return type:

Optional[User]

property global_application_commands[source]

The client’s global application commands.

Type:

List[Union[APIUserCommand, APIMessageCommand, APISlashCommand]

property global_message_commands[source]

The client’s global message commands.

Type:

List[APIMessageCommand]

property global_slash_commands[source]

The client’s global slash commands.

Type:

List[APISlashCommand]

property global_user_commands[source]

The client’s global user commands.

Type:

List[APIUserCommand]

property guilds[source]

The guilds that the connected client is a member of.

Type:

List[Guild]

property intents[source]

The intents configured for this connection.

New in version 1.5.

Type:

Intents

await invoke(ctx)[source]

This function is a coroutine.

Invokes the command given under the invocation context and handles all the internal event dispatch mechanisms.

Parameters:

ctx (Context) – The invocation context to invoke.

is_closed()[source]

Whether the websocket connection is closed.

Return type:

bool

await is_owner(user)[source]

This function is a coroutine.

Checks if a User or Member is the owner of this bot.

If an owner_id is not set, it is fetched automatically through the use of application_info().

Changed in version 1.3: The function also checks if the application is team-owned if owner_ids is not set.

Parameters:

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

Returns:

Whether the user is the owner.

Return type:

bool

is_ready()[source]

Whether the client’s internal cache is ready for use.

Return type:

bool

is_ws_ratelimited()[source]

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.

Return type:

bool

property latency[source]

Measures latency between a HEARTBEAT and a HEARTBEAT_ACK in seconds.

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

Type:

float

load_extension(name, *, package=None)[source]

Loads an extension.

An extension is a python module that contains commands, cogs, or listeners.

An extension must have a global function, setup defined as the entry point on what to do when the extension is loaded. This entry point must have a single argument, the bot.

Parameters:
  • name (str) – The extension name to load. It must be dot separated like regular Python imports if accessing a sub-module. e.g. foo.test if you want to import foo/test.py.

  • package (Optional[str]) –

    The package name to resolve relative imports with. This is required when loading an extension using a relative path, e.g .foo.test. Defaults to None.

    New in version 1.7.

Raises:
  • ExtensionNotFound – The extension could not be imported. This is also raised if the name of the extension could not be resolved using the provided package parameter.

  • ExtensionAlreadyLoaded – The extension is already loaded.

  • NoEntryPointError – The extension does not have a setup function.

  • ExtensionFailed – The extension or its setup function had an execution error.

load_extensions(path)[source]

Loads all extensions in a directory.

New in version 2.4.

Parameters:

path (str) – The path to search for extensions

await login(token)[source]

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.

message_command_check(func)[source]

Similar to check() but for message commands.

message_command_check_once(func)[source]

Similar to check_once() but for message commands.

property message_commands[source]

A set of all message commands the bot has.

Type:

Set[InvokableMessageCommand]

await on_command_error(context, exception)[source]

This function is a coroutine.

The default command error handler provided by the bot.

This is for text commands only, and doesn’t apply to application commands.

By default this prints to sys.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 on_error(event_method, *args, **kwargs)[source]

This function is a coroutine.

The default error handler provided by the client.

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

await on_gateway_error(event, data, shard_id, exc, /)[source]

This function is a coroutine.

The default gateway error handler provided by the client.

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

New in version 2.6.

Note

Unlike on_error(), the exception is available as the exc parameter and cannot be obtained through sys.exc_info().

await on_message_command_error(interaction, exception)[source]

This function is a coroutine.

Similar to on_slash_command_error() but for message commands.

await on_slash_command_error(interaction, exception)[source]

This function is a coroutine.

The default slash command error handler provided by the bot.

By default this prints to sys.stderr however it could be overridden to have a different implementation.

This only fires if you do not specify any listeners for slash command error.

await on_user_command_error(interaction, exception)[source]

This function is a coroutine.

Similar to on_slash_command_error() but for user commands.

property persistent_views[source]

A sequence of persistent views added to the client.

New in version 2.0.

Type:

Sequence[View]

property private_channels[source]

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]

await process_app_command_autocompletion(inter)[source]

This function is a coroutine.

This function processes the application command autocompletions. Without this coroutine, none of the autocompletions will be performed.

By default, this coroutine is called inside the on_application_command_autocomplete() event. If you choose to override the on_application_command_autocomplete() event, then you should invoke this coroutine as well.

Parameters:

inter (disnake.ApplicationCommandInteraction) – The interaction to process.

await process_application_commands(interaction)[source]

This function is a coroutine.

This function processes the application commands that have been registered to the bot and other groups. Without this coroutine, none of the application commands will be triggered.

By default, this coroutine is called inside the on_application_command() event. If you choose to override the on_application_command() event, then you should invoke this coroutine as well.

Parameters:

interaction (disnake.ApplicationCommandInteraction) – The interaction to process commands for.

await process_commands(message)[source]

This function is a coroutine.

This function processes the commands that have been registered to the bot and other groups. Without this coroutine, none of the commands will be triggered.

By default, this coroutine is called inside the on_message() event. If you choose to override the on_message() event, then you should invoke this coroutine as well.

This is built using other low level tools, and is equivalent to a call to get_context() followed by a call to invoke().

This also checks if the message’s author is a bot and doesn’t call get_context() or invoke() if so.

Parameters:

message (disnake.Message) – The message to process commands for.

reload_extension(name, *, package=None)[source]

Atomically reloads an extension.

This replaces the extension with the same extension, only refreshed. This is equivalent to a unload_extension() followed by a load_extension() except done in an atomic way. That is, if an operation fails mid-reload then the bot will roll-back to the prior working state.

Parameters:
  • name (str) – The extension name to reload. It must be dot separated like regular Python imports if accessing a sub-module. e.g. foo.test if you want to import foo/test.py.

  • package (Optional[str]) –

    The package name to resolve relative imports with. This is required when reloading an extension using a relative path, e.g .foo.test. Defaults to None.

    New in version 1.7.

Raises:
  • ExtensionNotLoaded – The extension was not loaded.

  • ExtensionNotFound – The extension could not be imported. This is also raised if the name of the extension could not be resolved using the provided package parameter.

  • NoEntryPointError – The extension does not have a setup function.

  • ExtensionFailed – The extension setup function had an execution error.

remove_app_command_check(func, *, call_once=False, slash_commands=False, user_commands=False, message_commands=False)[source]

Removes a global application command check from the bot.

This function is idempotent and will not raise an exception if the function is not in the global checks.

You must specify at least one of the bool parameters, otherwise the check won’t be removed.

Parameters:
  • func – The function to remove from the global checks.

  • call_once (bool) – Whether the function was added with call_once=True in the Bot.add_check() call or using check_once().

  • slash_commands (bool) – Whether this check was for slash commands.

  • user_commands (bool) – Whether this check was for user commands.

  • message_commands (bool) – Whether this check was for message commands.

remove_check(func, *, call_once=False)[source]

Removes a global check from the bot.

This is for text commands only, and doesn’t apply to application commands.

This function is idempotent and will not raise an exception if the function is not in the global checks.

Parameters:
  • func – The function to remove from the global checks.

  • call_once (bool) – If the function was added with call_once=True in the Bot.add_check() call or using check_once().

remove_cog(name)[source]

Removes a cog from the bot and returns it.

All registered commands and event listeners that the cog has registered will be removed as well.

If no cog is found then this method has no effect.

Parameters:

name (str) – The name of the cog to remove.

Returns:

The cog that was removed. Returns None if not found.

Return type:

Optional[Cog]

remove_command(name)[source]

Remove a Command from the internal list of commands.

This could also be used as a way to remove aliases.

Parameters:

name (str) – The name of the command to remove.

Returns:

The command that was removed. If the name is not valid then None is returned instead.

Return type:

Optional[Command]

remove_listener(func, name=...)[source]

Removes a listener from the pool of listeners.

Parameters:
  • func – The function that was used as a listener to remove.

  • name (str) – The name of the event we want to remove. Defaults to func.__name__.

remove_message_command(name)[source]

Removes an InvokableMessageCommand from the internal list of message commands.

Parameters:

name (str) – The name of the message command to remove.

Returns:

The message command that was removed. If the name is not valid then None is returned instead.

Return type:

Optional[InvokableMessageCommand]

remove_slash_command(name)[source]

Removes an InvokableSlashCommand from the internal list of slash commands.

Parameters:

name (str) – The name of the slash command to remove.

Returns:

The slash command that was removed. If the name is not valid then None is returned instead.

Return type:

Optional[InvokableSlashCommand]

remove_user_command(name)[source]

Removes an InvokableUserCommand from the internal list of user commands.

Parameters:

name (str) – The name of the user command to remove.

Returns:

The user command that was removed. If the name is not valid then None is returned instead.

Return type:

Optional[InvokableUserCommand]

run(*args, **kwargs)[source]

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.

slash_command_check(func)[source]

Similar to check() but for slash commands.

slash_command_check_once(func)[source]

Similar to check_once() but for slash commands.

property slash_commands[source]

A set of all slash commands the bot has.

Type:

Set[InvokableSlashCommand]

await start(token, *, reconnect=True, ignore_session_start_limit=False)[source]

This function is a coroutine.

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

Raises:

TypeError – An unexpected keyword argument was received.

property status[source]

The status being used upon logging on to Discord.

New in version 2.0.

Type:

Status

property stickers[source]

The stickers that the connected client has.

New in version 2.0.

Type:

List[GuildSticker]

unload_extension(name, *, package=None)[source]

Unloads an extension.

When the extension is unloaded, all commands, listeners, and cogs are removed from the bot and the module is un-imported.

The extension can provide an optional global function, teardown, to do miscellaneous clean-up if necessary. This function takes a single parameter, the bot, similar to setup from load_extension().

Parameters:
  • name (str) – The extension name to unload. It must be dot separated like regular Python imports if accessing a sub-module. e.g. foo.test if you want to import foo/test.py.

  • package (Optional[str]) –

    The package name to resolve relative imports with. This is required when unloading an extension using a relative path, e.g .foo.test. Defaults to None.

    New in version 1.7.

Raises:
property user[source]

Represents the connected client. None if not logged in.

Type:

Optional[ClientUser]

user_command_check(func)[source]

Similar to check() but for user commands.

user_command_check_once(func)[source]

Similar to check_once() but for user commands.

property user_commands[source]

A set of all user commands the bot has.

Type:

Set[InvokableUserCommand]

property users[source]

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

Type:

List[User]

property voice_clients[source]

Represents a list of voice connections.

These are usually VoiceClient instances.

Type:

List[VoiceProtocol]

wait_for(event, *, check=None, timeout=None)[source]

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 wait_until_first_connect()[source]

This function is a coroutine.

Waits until the first connect.

await wait_until_ready()[source]

This function is a coroutine.

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

for ... in walk_commands()[source]

An iterator that recursively walks through all commands and subcommands.

Changed in version 1.4: Duplicates due to aliases are no longer returned

Yields:

Union[Command, Group] – A command or group from the internal list of commands.

AutoShardedBot
class disnake.ext.commands.AutoShardedBot(command_prefix=None, help_command=<default-help-command>, description=None, *, strip_after_prefix=False, **options)[source]

This is similar to Bot except that it is inherited from disnake.AutoShardedClient instead.

InteractionBot
Methods
class disnake.ext.commands.InteractionBot(*, sync_commands=True, sync_commands_debug=False, sync_commands_on_cog_unload=True, test_guilds=None, **options)[source]

Represents a discord bot for application commands only.

This class is a subclass of disnake.Client and as a result anything that you can do with a disnake.Client you can do with this bot.

This class also subclasses InteractionBotBase to provide the functionality to manage application commands.

owner_id

The user ID that owns the bot. If this is not set and is then queried via is_owner() then it is fetched automatically using application_info().

Type:

Optional[int]

owner_ids

The user IDs that owns the bot. This is similar to owner_id. If this is not set and the application is team based, then it is fetched automatically using application_info(). For performance reasons it is recommended to use a set for the collection. You cannot set both owner_id and owner_ids.

Type:

Optional[Collection[int]]

test_guilds

The list of IDs of the guilds where you’re going to test your application commands. Defaults to None, which means global registration of commands across all guilds.

New in version 2.1.

Type:

List[int]

sync_commands

Whether to enable automatic synchronization of application commands in your code. Defaults to True, which means that commands in API are automatically synced with the commands in your code.

New in version 2.1.

Type:

bool

sync_commands_on_cog_unload

Whether to sync the application commands on cog unload / reload. Defaults to True.

New in version 2.1.

Type:

bool

sync_commands_debug

Whether to always show sync debug logs (uses INFO log level if it’s enabled, prints otherwise). If disabled, uses the default DEBUG log level which isn’t shown unless the log level is changed manually. Useful for tracking the commands being registered in the API. Defaults to False.

New in version 2.1.

Changed in version 2.4: Changes the log level of corresponding messages from DEBUG to INFO or prints them, instead of controlling whether they are enabled at all.

Type:

bool

reload

Whether to enable automatic extension reloading on file modification for debugging. Whenever you save an extension with reloading enabled the file will be automatically reloaded for you so you do not have to reload the extension manually. Defaults to False

New in version 2.1.

Type:

bool

localization_provider

An implementation of LocalizationProtocol to use for localization of application commands. If not provided, the default LocalizationStore implementation is used.

New in version 2.5.

Type:

LocalizationProtocol

strict_localization

Whether to raise an exception when localizations for a specific key couldn’t be found. This is mainly useful for testing/debugging, consider disabling this eventually as missing localized names will automatically fall back to the default/base name without it. Only applicable if the localization_provider parameter is not provided. Defaults to False.

New in version 2.5.

Type:

bool

i18n

An implementation of LocalizationProtocol used for localization of application commands.

New in version 2.5.

Type:

LocalizationProtocol

@after_slash_command_invoke[source]

Similar to Bot.after_invoke() but for slash commands, and it takes an ApplicationCommandInteraction as its only parameter.

@after_user_command_invoke[source]

Similar to Bot.after_slash_command_invoke() but for user commands.

@after_message_command_invoke[source]

Similar to Bot.after_slash_command_invoke() but for message commands.

@before_slash_command_invoke[source]

Similar to Bot.before_invoke() but for slash commands, and it takes an ApplicationCommandInteraction as its only parameter.

@before_user_command_invoke[source]

Similar to Bot.before_slash_command_invoke() but for user commands.

@before_message_command_invoke[source]

Similar to Bot.before_slash_command_invoke() but for message commands.

@application_command_check[source]

A decorator that adds a global application command check to the bot.

A global check is similar to a check() that is applied on a per command basis except it is run before any application command checks have been verified and applies to every application command the bot has.

Note

This function can either be a regular function or a coroutine.

Similar to a command check(), this takes a single parameter of type ApplicationCommandInteraction and can only raise exceptions inherited from CommandError.

Example

@bot.application_command_check()
def check_app_commands(inter):
    return inter.channel_id in whitelisted_channels
Parameters:
  • call_once (bool) – Whether the function should only be called once per InvokableApplicationCommand.invoke() call.

  • slash_commands (bool) – Whether this check is for slash commands.

  • user_commands (bool) – Whether this check is for user commands.

  • message_commands (bool) – Whether this check is for message commands.

@slash_command_check[source]

Similar to check() but for slash commands.

@user_command_check[source]

Similar to check() but for user commands.

@message_command_check[source]

Similar to check() but for message commands.

@slash_command_check_once[source]

Similar to check_once() but for slash commands.

@user_command_check_once[source]

Similar to check_once() but for user commands.

@message_command_check_once[source]

Similar to check_once() but for message commands.

@slash_command(*args, **kwargs)[source]

A shortcut decorator that invokes slash_command() and adds it to the internal command list.

Parameters:
  • name (Optional[Union[str, Localized]]) –

    The name of the slash command (defaults to function name).

    Changed in version 2.5: Added support for localizations.

  • description (Optional[Union[str, Localized]]) –

    The description of the slash command. It will be visible in Discord.

    Changed in version 2.5: Added support for localizations.

  • options (List[Option]) – The list of slash command options. The options will be visible in Discord. This is the old way of specifying options. Consider using Parameters instead.

  • dm_permission (bool) – Whether this command can be used in DMs. Defaults to True.

  • default_member_permissions (Optional[Union[Permissions, int]]) –

    The default required permissions for this command. See ApplicationCommand.default_member_permissions for details.

    New in version 2.5.

  • auto_sync (bool) – Whether to automatically register the command. Defaults to True

  • guild_ids (Sequence[int]) – If specified, the client will register the command in these guilds. Otherwise, this command will be registered globally.

  • connectors (Dict[str, str]) – Binds function names to option names. If the name of an option already matches the corresponding function param, you don’t have to specify the connectors. Connectors template: {"option-name": "param_name", ...}. If you’re using Parameters, you don’t need to specify this.

  • extras (Dict[str, Any]) –

    A dict of user provided extras to attach to the command.

    Note

    This object may be copied by the library.

    New in version 2.5.

Returns:

A decorator that converts the provided method into an InvokableSlashCommand, adds it to the bot, then returns it.

Return type:

Callable[…, InvokableSlashCommand]

@user_command(*args, **kwargs)[source]

A shortcut decorator that invokes user_command() and adds it to the internal command list.

Parameters:
  • name (Optional[Union[str, Localized]]) –

    The name of the user command (defaults to function name).

    Changed in version 2.5: Added support for localizations.

  • dm_permission (bool) – Whether this command can be used in DMs. Defaults to True.

  • default_member_permissions (Optional[Union[Permissions, int]]) –

    The default required permissions for this command. See ApplicationCommand.default_member_permissions for details.

    New in version 2.5.

  • auto_sync (bool) – Whether to automatically register the command. Defaults to True.

  • guild_ids (Sequence[int]) – If specified, the client will register the command in these guilds. Otherwise, this command will be registered globally.

  • extras (Dict[str, Any]) –

    A dict of user provided extras to attach to the command.

    Note

    This object may be copied by the library.

    New in version 2.5.

Returns:

A decorator that converts the provided method into an InvokableUserCommand, adds it to the bot, then returns it.

Return type:

Callable[…, InvokableUserCommand]

@message_command(*args, **kwargs)[source]

A shortcut decorator that invokes message_command() and adds it to the internal command list.

Parameters:
  • name (Optional[Union[str, Localized]]) –

    The name of the message command (defaults to function name).

    Changed in version 2.5: Added support for localizations.

  • dm_permission (bool) – Whether this command can be used in DMs. Defaults to True.

  • default_member_permissions (Optional[Union[Permissions, int]]) –

    The default required permissions for this command. See ApplicationCommand.default_member_permissions for details.

    New in version 2.5.

  • auto_sync (bool) – Whether to automatically register the command. Defaults to True

  • guild_ids (Sequence[int]) – If specified, the client will register the command in these guilds. Otherwise, this command will be registered globally.

  • extras (Dict[str, Any]) –

    A dict of user provided extras to attach to the command.

    Note

    This object may be copied by the library.

    New in version 2.5.

Returns:

A decorator that converts the provided method into an InvokableMessageCommand, adds it to the bot, then returns it.

Return type:

Callable[…, InvokableMessageCommand]

@event[source]

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.

@listen(name=None)[source]

A decorator that registers another function as an external event listener. Basically this allows you to listen to multiple events from different places e.g. such as on_ready()

The functions being listened to must be a coroutine.

Example

@bot.listen()
async def on_message(message):
    print('one')

# in some other file...

@bot.listen('on_message')
async def my_message(message):
    print('two')

Would print one and two in an unspecified order.

Raises:

TypeError – The function being listened to is not a coroutine.

property activity[source]

The activity being used upon logging in.

Type:

Optional[BaseActivity]

add_app_command_check(func, *, call_once=False, slash_commands=False, user_commands=False, message_commands=False)[source]

Adds a global application command check to the bot.

This is the non-decorator interface to check(), check_once(), slash_command_check() and etc.

You must specify at least one of the bool parameters, otherwise the check won’t be added.

Parameters:
  • func – The function that will be used as a global check.

  • call_once (bool) – Whether the function should only be called once per InvokableApplicationCommand.invoke() call.

  • slash_commands (bool) – Whether this check is for slash commands.

  • user_commands (bool) – Whether this check is for user commands.

  • message_commands (bool) – Whether this check is for message commands.

add_cog(cog, *, override=False)[source]

Adds a “cog” to the bot.

A cog is a class that has its own event listeners and commands.

Changed in version 2.0: ClientException is raised when a cog with the same name is already loaded.

Parameters:
  • cog (Cog) – The cog to register to the bot.

  • override (bool) –

    If a previously loaded cog with the same name should be ejected instead of raising an error.

    New in version 2.0.

Raises:
add_listener(func, name=...)[source]

The non decorator alternative to listen().

Parameters:
  • func (coroutine) – The function to call.

  • name (str) – The name of the event to listen for. Defaults to func.__name__.

Example

async def on_ready(): pass
async def my_message(message): pass

bot.add_listener(on_ready)
bot.add_listener(my_message, 'on_message')
Raises:

TypeError – The function is not a coroutine.

add_message_command(message_command)[source]

Adds an InvokableMessageCommand into the internal list of message commands.

This is usually not called, instead the message_command() or shortcut decorators are used.

Parameters:

message_command (InvokableMessageCommand) – The message command to add.

Raises:
add_slash_command(slash_command)[source]

Adds an InvokableSlashCommand into the internal list of slash commands.

This is usually not called, instead the slash_command() or shortcut decorators are used.

Parameters:

slash_command (InvokableSlashCommand) – The slash command to add.

Raises:
add_user_command(user_command)[source]

Adds an InvokableUserCommand into the internal list of user commands.

This is usually not called, instead the user_command() or shortcut decorators are used.

Parameters:

user_command (InvokableUserCommand) – The user command to add.

Raises:
add_view(view, *, message_id=None)[source]

Registers a View for persistent listening.

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.

Parameters:
  • view (disnake.ui.View) – The view to register for dispatching.

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

Raises:
  • TypeError – A view was not passed.

  • ValueError – The view is not persistent. A persistent view has no timeout and all their components have an explicitly provided custom_id.

property allowed_mentions[source]

The allowed mention configuration.

New in version 1.4.

Type:

Optional[AllowedMentions]

property application_commands[source]

A set of all application commands the bot has.

Type:

Set[InvokableApplicationCommand]

property application_flags[source]

The client’s application flags.

New in version 2.0.

Type:

ApplicationFlags

property application_id[source]

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]

await application_info()[source]

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 before_identify_hook(shard_id, *, initial=False)[source]

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 bulk_fetch_command_permissions(guild_id)[source]

This function is a coroutine.

Retrieves a list of GuildApplicationCommandPermissions configured for the guild with the given ID.

New in version 2.1.

Parameters:

guild_id (int) – The ID of the guild to inspect.

await bulk_overwrite_global_commands(application_commands)[source]

This function is a coroutine.

Overwrites several global application commands in one API request.

New in version 2.1.

Parameters:

application_commands (List[ApplicationCommand]) – A list of application commands to insert instead of the existing commands.

Returns:

A list of registered application commands.

Return type:

List[Union[APIUserCommand, APIMessageCommand, APISlashCommand]]

await bulk_overwrite_guild_commands(guild_id, application_commands)[source]

This function is a coroutine.

Overwrites several guild application commands in one API request.

New in version 2.1.

Parameters:
  • guild_id (int) – The ID of the guild where the application commands should be overwritten.

  • application_commands (List[ApplicationCommand]) – A list of application commands to insert instead of the existing commands.

Returns:

A list of registered application commands.

Return type:

List[Union[APIUserCommand, APIMessageCommand, APISlashCommand]]

property cached_messages[source]

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

New in version 1.1.

Type:

Sequence[Message]

await change_presence(*, activity=None, status=None)[source]

This function is a coroutine.

Changes the client’s presence.

Changed in version 2.6: Raises TypeError instead of InvalidArgument.

Example

game = disnake.Game("with the API")
await client.change_presence(status=disnake.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:

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

clear()[source]

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 close()[source]

This function is a coroutine.

Closes the connection to Discord.

property cogs[source]

A read-only mapping of cog name to cog.

Type:

Mapping[str, Cog]

await connect(*, reconnect=True, ignore_session_start_limit=False)[source]

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.

Changed in version 2.6: Added usage of SessionStartLimit when connecting to the API. Added the ignore_session_start_limit parameter.

Parameters:
  • reconnect (bool) – Whether reconnecting should be attempted, 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).

  • ignore_session_start_limit (bool) –

    Whether the API provided session start limit should be ignored when connecting to the API.

    New in version 2.6.

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.

  • SessionStartLimitReached – If the client doesn’t have enough connects remaining in the current 24-hour window and ignore_session_start_limit is False this will be raised rather than connecting to the gateawy and Discord resetting the token. However, if ignore_session_start_limit is True, the client will connect regardless and this exception will not be raised.

await create_dm(user)[source]

This function is a coroutine.

Creates a DMChannel with the given 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

await create_global_command(application_command)[source]

This function is a coroutine.

Creates a global application command.

New in version 2.1.

Parameters:

application_command (ApplicationCommand) – An object representing the application command to create.

Returns:

The application command that was created.

Return type:

Union[APIUserCommand, APIMessageCommand, APISlashCommand]

await create_guild(*, name, icon=..., code=...)[source]

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.5: Removed the region parameter.

Changed in version 2.6: Raises ValueError instead of InvalidArgument.

Parameters:
Raises:
Returns:

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

Return type:

Guild

await create_guild_command(guild_id, application_command)[source]

This function is a coroutine.

Creates a guild application command.

New in version 2.1.

Parameters:
  • guild_id (int) – The ID of the guild where the application command should be created.

  • application_command (ApplicationCommand) – The application command.

Returns:

The newly created application command.

Return type:

Union[APIUserCommand, APIMessageCommand, APISlashCommand]

await delete_global_command(command_id)[source]

This function is a coroutine.

Deletes a global application command.

New in version 2.1.

Parameters:

command_id (int) – The ID of the application command to delete.

await delete_guild_command(guild_id, command_id)[source]

This function is a coroutine.

Deletes a guild application command.

New in version 2.1.

Parameters:
  • guild_id (int) – The ID of the guild where the applcation command should be deleted.

  • command_id (int) – The ID of the application command to delete.

await delete_invite(invite)[source]

This function is a coroutine.

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

You must have 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 edit_global_command(command_id, new_command)[source]

This function is a coroutine.

Edits a global application command.

New in version 2.1.

Parameters:
  • command_id (int) – The ID of the application command to edit.

  • new_command (ApplicationCommand) – An object representing the edited application command.

Returns:

The edited application command.

Return type:

Union[APIUserCommand, APIMessageCommand, APISlashCommand]

await edit_guild_command(guild_id, command_id, new_command)[source]

This function is a coroutine.

Edits a guild application command.

New in version 2.1.

Parameters:
  • guild_id (int) – The ID of the guild where the application command should be edited.

  • command_id (int) – The ID of the application command to edit.

  • new_command (ApplicationCommand) – An object representing the edited application command.

Returns:

The newly edited application command.

Return type:

Union[APIUserCommand, APIMessageCommand, APISlashCommand]

property emojis[source]

The emojis that the connected client has.

Type:

List[Emoji]

property extensions[source]

A read-only mapping of extension name to extension.

Type:

Mapping[str, types.ModuleType]

await fetch_channel(channel_id, /)[source]

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.

Parameters:

channel_id (int) – The ID of the channel to retrieve.

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_command_permissions(guild_id, command_id)[source]

This function is a coroutine.

Retrieves GuildApplicationCommandPermissions for a specific application command in the guild with the given ID.

New in version 2.1.

Parameters:
  • guild_id (int) – The ID of the guild to inspect.

  • command_id (int) –

    The ID of the application command, or the application ID to fetch application-wide permissions.

    Changed in version 2.5: Can now also fetch application-wide permissions.

Returns:

The permissions configured for the specified application command.

Return type:

GuildApplicationCommandPermissions

await fetch_global_command(command_id)[source]

This function is a coroutine.

Retrieves a global application command.

New in version 2.1.

Parameters:

command_id (int) – The ID of the command to retrieve.

Returns:

The requested application command.

Return type:

Union[APIUserCommand, APIMessageCommand, APISlashCommand]

await fetch_global_commands(*, with_localizations=True)[source]

This function is a coroutine.

Retrieves a list of global application commands.

New in version 2.1.

Parameters:

with_localizations (bool) –

Whether to include localizations in the response. Defaults to True.

New in version 2.5.

Returns:

A list of application commands.

Return type:

List[Union[APIUserCommand, APIMessageCommand, APISlashCommand]]

await fetch_guild(guild_id, /)[source]

This function is a coroutine.

Retrieves a Guild from the given ID.

Note

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

Note

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

Parameters:

guild_id (int) – The ID of the guild to retrieve.

Raises:
Returns:

The guild from the given ID.

Return type:

Guild

await fetch_guild_command(guild_id, command_id)[source]

This function is a coroutine.

Retrieves a guild application command.

New in version 2.1.

Parameters:
  • guild_id (int) – The ID of the guild to fetch command from.

  • command_id (int) – The ID of the application command to retrieve.

Returns:

The requested application command.

Return type:

Union[APIUserCommand, APIMessageCommand, APISlashCommand]

await fetch_guild_commands(guild_id, *, with_localizations=True)[source]

This function is a coroutine.

Retrieves a list of guild application commands.

New in version 2.1.

Parameters:
  • guild_id (int) – The ID of the guild to fetch commands from.

  • with_localizations (bool) –

    Whether to include localizations in the response. Defaults to True.

    New in version 2.5.

Returns:

A list of application commands.

Return type:

List[Union[APIUserCommand, APIMessageCommand, APISlashCommand]]

await fetch_guild_preview(guild_id, /)[source]

This function is a coroutine.

Retrieves a GuildPreview from the given ID. Your bot does not have to be in this guild.

Note

This method may fetch any guild that has DISCOVERABLE in Guild.features, but this information can not be known ahead of time.

This will work for any guild that you are in.

Parameters:

guild_id (int) – The ID of the guild to to retrieve a preview object.

Raises:

NotFound – Retrieving the guild preview failed.

Returns:

The guild preview from the given ID.

Return type:

GuildPreview

fetch_guilds(*, limit=100, before=None, after=None)[source]

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

  • 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 – Retrieving the guilds failed.

Yields:

Guild – The guild with the guild data parsed.

await fetch_invite(url, *, with_counts=True, with_expiration=True, guild_scheduled_event_id=None)[source]

This function is a coroutine.

Retrieves 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:
  • url (Union[Invite, str]) – The Discord invite ID or URL (must be a discord.gg URL).

  • with_counts (bool) – Whether to include count information in the invite. This fills the Invite.approximate_member_count and Invite.approximate_presence_count fields.

  • with_expiration (bool) –

    Whether to include the expiration date of the invite. This fills the Invite.expires_at field.

    New in version 2.0.

  • guild_scheduled_event_id (int) –

    The ID of the scheduled event to include in the invite. If not provided, defaults to the event parameter in the URL if it exists, or the ID of the scheduled event contained in the provided invite object.

    New in version 2.3.

Raises:
Returns:

The invite from the URL/ID.

Return type:

Invite

await fetch_premium_sticker_packs()[source]

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 fetch_stage_instance(channel_id, /)[source]

This function is a coroutine.

Retrieves a StageInstance with the given ID.

Note

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

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 – Retrieving the stage instance failed.

Returns:

The stage instance from the given ID.

Return type:

StageInstance

await fetch_sticker(sticker_id, /)[source]

This function is a coroutine.

Retrieves a Sticker with the given ID.

New in version 2.0.

Parameters:

sticker_id (int) – The ID of the sticker to retrieve.

Raises:
Returns:

The sticker you requested.

Return type:

Union[StandardSticker, GuildSticker]

await fetch_template(code)[source]

This function is a coroutine.

Retrieves 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:
Returns:

The template from the URL/code.

Return type:

Template

await fetch_user(user_id, /)[source]

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 disnake.Intents.members and member cache enabled, consider get_user() instead.

Parameters:

user_id (int) – The ID of the user to retrieve.

Raises:
Returns:

The user you requested.

Return type:

User

await fetch_voice_regions(guild_id=None)[source]

Retrieves a list of VoiceRegions.

Retrieves voice regions for the user, or a guild if provided.

New in version 2.5.

Parameters:

guild_id (Optional[int]) – The guild to get regions for, if provided.

Raises:
  • HTTPException – Retrieving voice regions failed.

  • NotFound – The provided guild_id could not be found.

await fetch_webhook(webhook_id, /)[source]

This function is a coroutine.

Retrieves a Webhook with the given ID.

Parameters:

webhook_id (int) – The ID of the webhook to retrieve.

Raises:
Returns:

The webhook you requested.

Return type:

Webhook

await fetch_widget(guild_id, /)[source]

This function is a coroutine.

Retrieves a Widget for the given guild ID.

Note

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

Parameters:

guild_id (int) – The ID of the guild.

Raises:
Returns:

The guild’s widget.

Return type:

Widget

for ... in get_all_channels()[source]

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()[source]

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.

get_channel(id, /)[source]

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_cog(name)[source]

Gets the cog instance requested.

If the cog is not found, None is returned instead.

Parameters:

name (str) – The name of the cog you are requesting. This is equivalent to the name passed via keyword argument in class creation or the class name if unspecified.

Returns:

The cog that was requested. If not found, returns None.

Return type:

Optional[Cog]

get_emoji(id, /)[source]

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_global_command(id)[source]

Returns a global application command with the given ID.

Parameters:

id (int) – The ID to search for.

Returns:

The application command.

Return type:

Optional[Union[APIUserCommand, APIMessageCommand, APISlashCommand]]

get_global_command_named(name, cmd_type=None)[source]

Returns a global application command matching the given name.

Parameters:
  • name (str) – The name to look for.

  • cmd_type (ApplicationCommandType) – The type to look for. By default, no types are checked.

Returns:

The application command.

Return type:

Optional[Union[APIUserCommand, APIMessageCommand, APISlashCommand]]

get_guild(id, /)[source]

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_guild_application_commands(guild_id)[source]

Returns a list of all application commands in the guild with the given ID.

Parameters:

guild_id (int) – The ID to search for.

Returns:

The list of application commands.

Return type:

List[Union[APIUserCommand, APIMessageCommand, APISlashCommand]]

get_guild_command(guild_id, id)[source]

Returns a guild application command with the given guild ID and application command ID.

Parameters:
  • guild_id (int) – The guild ID to search for.

  • id (int) – The command ID to search for.

Returns:

The application command.

Return type:

Optional[Union[APIUserCommand, APIMessageCommand, APISlashCommand]]

get_guild_command_named(guild_id, name, cmd_type=None)[source]

Returns a guild application command matching the given name.

Parameters:
  • guild_id (int) – The guild ID to search for.

  • name (str) – The command name to search for.

  • cmd_type (ApplicationCommandType) – The type to look for. By default, no types are checked.

Returns:

The application command.

Return type:

Optional[Union[APIUserCommand, APIMessageCommand, APISlashCommand]]

get_guild_message_commands(guild_id)[source]

Returns a list of all message commands in the guild with the given ID.

Parameters:

guild_id (int) – The ID to search for.

Returns:

The list of message commands.

Return type:

List[APIMessageCommand]

get_guild_slash_commands(guild_id)[source]

Returns a list of all slash commands in the guild with the given ID.

Parameters:

guild_id (int) – The ID to search for.

Returns:

The list of slash commands.

Return type:

List[APISlashCommand]

get_guild_user_commands(guild_id)[source]

Returns a list of all user commands in the guild with the given ID.

Parameters:

guild_id (int) – The ID to search for.

Returns:

The list of user commands.

Return type:

List[APIUserCommand]

get_message(id)[source]

Gets the message with the given ID from the bot’s message cache.

Parameters:

id (int) – The ID of the message to look for.

Returns:

The corresponding message.

Return type:

Optional[Message]

get_message_command(name)[source]

Gets an InvokableMessageCommand from the internal list of message commands.

Parameters:

name (str) – The name of the message command to get.

Returns:

The message command that was requested. If not found, returns None.

Return type:

Optional[InvokableMessageCommand]

await get_or_fetch_user(user_id, *, strict=False)[source]

This function is a coroutine.

Tries to get the user from the cache. If fails, it tries to fetch the user from the API.

Parameters:
  • user_id (int) – The ID to search for.

  • strict (bool) – Whether to propagate exceptions from fetch_user() instead of returning None in case of failure (e.g. if the user wasn’t found). Defaults to False.

Returns:

The user with the given ID, or None if not found and strict is set to False.

Return type:

Optional[User]

get_partial_messageable(id, *, type=None)[source]

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_slash_command(name)[source]

Works like Bot.get_command, but for slash commands.

If the name contains spaces, then it will assume that you are looking for a SubCommand or a SubCommandGroup. e.g: 'foo bar' will get the sub command group, or the sub command bar of the top-level slash command foo if found, otherwise None.

Parameters:

name (str) – The name of the slash command to get.

Raises:

TypeError – The name is not a string.

Returns:

The slash command that was requested. If not found, returns None.

Return type:

Optional[Union[InvokableSlashCommand, SubCommandGroup, SubCommand]]

get_stage_instance(id, /)[source]

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 or None if not found.

Return type:

Optional[StageInstance]

get_sticker(id, /)[source]

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_user(id, /)[source]

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_user_command(name)[source]

Gets an InvokableUserCommand from the internal list of user commands.

Parameters:

name (str) – The name of the user command to get.

Returns:

The user command that was requested. If not found, returns None.

Return type:

Optional[InvokableUserCommand]

await getch_user(user_id, *, strict=False)[source]

This function is a coroutine.

Tries to get the user from the cache. If fails, it tries to fetch the user from the API.

Parameters:
  • user_id (int) – The ID to search for.

  • strict (bool) – Whether to propagate exceptions from fetch_user() instead of returning None in case of failure (e.g. if the user wasn’t found). Defaults to False.

Returns:

The user with the given ID, or None if not found and strict is set to False.

Return type:

Optional[User]

property global_application_commands[source]

The client’s global application commands.

Type:

List[Union[APIUserCommand, APIMessageCommand, APISlashCommand]

property global_message_commands[source]

The client’s global message commands.

Type:

List[APIMessageCommand]

property global_slash_commands[source]

The client’s global slash commands.

Type:

List[APISlashCommand]

property global_user_commands[source]

The client’s global user commands.

Type:

List[APIUserCommand]

property guilds[source]

The guilds that the connected client is a member of.

Type:

List[Guild]

property intents[source]

The intents configured for this connection.

New in version 1.5.

Type:

Intents

is_closed()[source]

Whether the websocket connection is closed.

Return type:

bool

await is_owner(user)[source]

This function is a coroutine.

Checks if a User or Member is the owner of this bot.

If an owner_id is not set, it is fetched automatically through the use of application_info().

Changed in version 1.3: The function also checks if the application is team-owned if owner_ids is not set.

Parameters:

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

Returns:

Whether the user is the owner.

Return type:

bool

is_ready()[source]

Whether the client’s internal cache is ready for use.

Return type:

bool

is_ws_ratelimited()[source]

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.

Return type:

bool

property latency[source]

Measures latency between a HEARTBEAT and a HEARTBEAT_ACK in seconds.

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

Type:

float

load_extension(name, *, package=None)[source]

Loads an extension.

An extension is a python module that contains commands, cogs, or listeners.

An extension must have a global function, setup defined as the entry point on what to do when the extension is loaded. This entry point must have a single argument, the bot.

Parameters:
  • name (str) – The extension name to load. It must be dot separated like regular Python imports if accessing a sub-module. e.g. foo.test if you want to import foo/test.py.

  • package (Optional[str]) –

    The package name to resolve relative imports with. This is required when loading an extension using a relative path, e.g .foo.test. Defaults to None.

    New in version 1.7.

Raises:
  • ExtensionNotFound – The extension could not be imported. This is also raised if the name of the extension could not be resolved using the provided package parameter.

  • ExtensionAlreadyLoaded – The extension is already loaded.

  • NoEntryPointError – The extension does not have a setup function.

  • ExtensionFailed – The extension or its setup function had an execution error.

load_extensions(path)[source]

Loads all extensions in a directory.

New in version 2.4.

Parameters:

path (str) – The path to search for extensions

await login(token)[source]

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.

property message_commands[source]

A set of all message commands the bot has.

Type:

Set[InvokableMessageCommand]

await on_error(event_method, *args, **kwargs)[source]

This function is a coroutine.

The default error handler provided by the client.

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

await on_gateway_error(event, data, shard_id, exc, /)[source]

This function is a coroutine.

The default gateway error handler provided by the client.

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

New in version 2.6.

Note

Unlike on_error(), the exception is available as the exc parameter and cannot be obtained through sys.exc_info().

await on_message_command_error(interaction, exception)[source]

This function is a coroutine.

Similar to on_slash_command_error() but for message commands.

await on_slash_command_error(interaction, exception)[source]

This function is a coroutine.

The default slash command error handler provided by the bot.

By default this prints to sys.stderr however it could be overridden to have a different implementation.

This only fires if you do not specify any listeners for slash command error.

await on_user_command_error(interaction, exception)[source]

This function is a coroutine.

Similar to on_slash_command_error() but for user commands.

property persistent_views[source]

A sequence of persistent views added to the client.

New in version 2.0.

Type:

Sequence[View]

property private_channels[source]

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]

await process_app_command_autocompletion(inter)[source]

This function is a coroutine.

This function processes the application command autocompletions. Without this coroutine, none of the autocompletions will be performed.

By default, this coroutine is called inside the on_application_command_autocomplete() event. If you choose to override the on_application_command_autocomplete() event, then you should invoke this coroutine as well.

Parameters:

inter (disnake.ApplicationCommandInteraction) – The interaction to process.

await process_application_commands(interaction)[source]

This function is a coroutine.

This function processes the application commands that have been registered to the bot and other groups. Without this coroutine, none of the application commands will be triggered.

By default, this coroutine is called inside the on_application_command() event. If you choose to override the on_application_command() event, then you should invoke this coroutine as well.

Parameters:

interaction (disnake.ApplicationCommandInteraction) – The interaction to process commands for.

reload_extension(name, *, package=None)[source]

Atomically reloads an extension.

This replaces the extension with the same extension, only refreshed. This is equivalent to a unload_extension() followed by a load_extension() except done in an atomic way. That is, if an operation fails mid-reload then the bot will roll-back to the prior working state.

Parameters:
  • name (str) – The extension name to reload. It must be dot separated like regular Python imports if accessing a sub-module. e.g. foo.test if you want to import foo/test.py.

  • package (Optional[str]) –

    The package name to resolve relative imports with. This is required when reloading an extension using a relative path, e.g .foo.test. Defaults to None.

    New in version 1.7.

Raises:
  • ExtensionNotLoaded – The extension was not loaded.

  • ExtensionNotFound – The extension could not be imported. This is also raised if the name of the extension could not be resolved using the provided package parameter.

  • NoEntryPointError – The extension does not have a setup function.

  • ExtensionFailed – The extension setup function had an execution error.

remove_app_command_check(func, *, call_once=False, slash_commands=False, user_commands=False, message_commands=False)[source]

Removes a global application command check from the bot.

This function is idempotent and will not raise an exception if the function is not in the global checks.

You must specify at least one of the bool parameters, otherwise the check won’t be removed.

Parameters:
  • func – The function to remove from the global checks.

  • call_once (bool) – Whether the function was added with call_once=True in the Bot.add_check() call or using check_once().

  • slash_commands (bool) – Whether this check was for slash commands.

  • user_commands (bool) – Whether this check was for user commands.

  • message_commands (bool) – Whether this check was for message commands.

remove_cog(name)[source]

Removes a cog from the bot and returns it.

All registered commands and event listeners that the cog has registered will be removed as well.

If no cog is found then this method has no effect.

Parameters:

name (str) – The name of the cog to remove.

Returns:

The cog that was removed. Returns None if not found.

Return type:

Optional[Cog]

remove_listener(func, name=...)[source]

Removes a listener from the pool of listeners.

Parameters:
  • func – The function that was used as a listener to remove.

  • name (str) – The name of the event we want to remove. Defaults to func.__name__.

remove_message_command(name)[source]

Removes an InvokableMessageCommand from the internal list of message commands.

Parameters:

name (str) – The name of the message command to remove.

Returns:

The message command that was removed. If the name is not valid then None is returned instead.

Return type:

Optional[InvokableMessageCommand]

remove_slash_command(name)[source]

Removes an InvokableSlashCommand from the internal list of slash commands.

Parameters:

name (str) – The name of the slash command to remove.

Returns:

The slash command that was removed. If the name is not valid then None is returned instead.

Return type:

Optional[InvokableSlashCommand]

remove_user_command(name)[source]

Removes an InvokableUserCommand from the internal list of user commands.

Parameters:

name (str) – The name of the user command to remove.

Returns:

The user command that was removed. If the name is not valid then None is returned instead.

Return type:

Optional[InvokableUserCommand]

run(*args, **kwargs)[source]

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.

property slash_commands[source]

A set of all slash commands the bot has.

Type:

Set[InvokableSlashCommand]

await start(token, *, reconnect=True, ignore_session_start_limit=False)[source]

This function is a coroutine.

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

Raises:

TypeError – An unexpected keyword argument was received.

property status[source]

The status being used upon logging on to Discord.

New in version 2.0.

Type:

Status

property stickers[source]

The stickers that the connected client has.

New in version 2.0.

Type:

List[GuildSticker]

unload_extension(name, *, package=None)[source]

Unloads an extension.

When the extension is unloaded, all commands, listeners, and cogs are removed from the bot and the module is un-imported.

The extension can provide an optional global function, teardown, to do miscellaneous clean-up if necessary. This function takes a single parameter, the bot, similar to setup from load_extension().

Parameters:
  • name (str) – The extension name to unload. It must be dot separated like regular Python imports if accessing a sub-module. e.g. foo.test if you want to import foo/test.py.

  • package (Optional[str]) –

    The package name to resolve relative imports with. This is required when unloading an extension using a relative path, e.g .foo.test. Defaults to None.

    New in version 1.7.

Raises:
property user[source]

Represents the connected client. None if not logged in.

Type:

Optional[ClientUser]

property user_commands[source]

A set of all user commands the bot has.

Type:

Set[InvokableUserCommand]

property users[source]

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

Type:

List[User]

property voice_clients[source]

Represents a list of voice connections.

These are usually VoiceClient instances.

Type:

List[VoiceProtocol]

wait_for(event, *, check=None, timeout=None)[source]

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 wait_until_first_connect()[source]

This function is a coroutine.

Waits until the first connect.

await wait_until_ready()[source]

This function is a coroutine.

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

AutoShardedInteractionBot
class disnake.ext.commands.AutoShardedInteractionBot(*, sync_commands=True, sync_commands_debug=False, sync_commands_on_cog_unload=True, test_guilds=None, **options)[source]

This is similar to InteractionBot except that it is inherited from disnake.AutoShardedClient instead.

Prefix Helpers
disnake.ext.commands.when_mentioned(bot, msg)[source]

A callable that implements a command prefix equivalent to being mentioned.

These are meant to be passed into the Bot.command_prefix attribute.

disnake.ext.commands.when_mentioned_or(*prefixes)[source]

A callable that implements when mentioned or other prefixes provided.

These are meant to be passed into the Bot.command_prefix attribute.

Example

bot = commands.Bot(command_prefix=commands.when_mentioned_or('!'))

Note

This callable returns another callable, so if this is done inside a custom callable, you must call the returned callable, for example:

async def get_prefix(bot, message):
    extras = await prefixes_for(message.guild) # returns a list
    return commands.when_mentioned_or(*extras)(bot, message)

See also

when_mentioned()

Event Reference

These events function similar to the regular events, except they are custom to the command extension module.

disnake.ext.commands.on_command_error(ctx, error)

An error handler that is called when an error is raised inside a command either through user input error, check failure, or an error in your own code.

A default one is provided (Bot.on_command_error()).

Parameters:
  • ctx (Context) – The invocation context.

  • error (CommandError derived) – The error that was raised.

disnake.ext.commands.on_slash_command_error(inter, error)

An error handler that is called when an error is raised inside a slash command either through user input error, check failure, or an error in your own code.

A default one is provided (Bot.on_slash_command_error()).

Parameters:
disnake.ext.commands.on_user_command_error(inter, error)

An error handler that is called when an error is raised inside a user command either through check failure, or an error in your own code.

A default one is provided (Bot.on_user_command_error()).

Parameters:
disnake.ext.commands.on_message_command_error(inter, error)

An error handler that is called when an error is raised inside a message command either through check failure, or an error in your own code.

A default one is provided (Bot.on_message_command_error()).

Parameters:
disnake.ext.commands.on_command(ctx)

An event that is called when a command is found and is about to be invoked.

This event is called regardless of whether the command itself succeeds via error or completes.

Parameters:

ctx (Context) – The invocation context.

disnake.ext.commands.on_slash_command(inter)

An event that is called when a slash command is found and is about to be invoked.

This event is called regardless of whether the slash command itself succeeds via error or completes.

Parameters:

inter (ApplicationCommandInteraction) – The interaction that invoked this slash command.

disnake.ext.commands.on_user_command(inter)

An event that is called when a user command is found and is about to be invoked.

This event is called regardless of whether the user command itself succeeds via error or completes.

Parameters:

inter (ApplicationCommandInteraction) – The interaction that invoked this user command.

disnake.ext.commands.on_message_command(inter)

An event that is called when a message command is found and is about to be invoked.

This event is called regardless of whether the message command itself succeeds via error or completes.

Parameters:

inter (ApplicationCommandInteraction) – The interaction that invoked this message command.

disnake.ext.commands.on_command_completion(ctx)

An event that is called when a command has completed its invocation.

This event is called only if the command succeeded, i.e. all checks have passed and the user input it correctly.

Parameters:

ctx (Context) – The invocation context.

disnake.ext.commands.on_slash_command_completion(inter)

An event that is called when a slash command has completed its invocation.

This event is called only if the slash command succeeded, i.e. all checks have passed and command handler ran successfully.

Parameters:

inter (ApplicationCommandInteraction) – The interaction that invoked this slash command.

disnake.ext.commands.on_user_command_completion(inter)

An event that is called when a user command has completed its invocation.

This event is called only if the user command succeeded, i.e. all checks have passed and command handler ran successfully.

Parameters:

inter (ApplicationCommandInteraction) – The interaction that invoked this user command.

disnake.ext.commands.on_message_command_completion(inter)

An event that is called when a message command has completed its invocation.

This event is called only if the message command succeeded, i.e. all checks have passed and command handler ran successfully.

Parameters:

inter (ApplicationCommandInteraction) – The interaction that invoked this message command.

Commands
Decorators
@disnake.ext.commands.command(name=..., cls=..., **attrs)[source]

A decorator that transforms a function into a Command or if called with group(), Group.

By default the help attribute is received automatically from the docstring of the function and is cleaned up with the use of inspect.cleandoc. If the docstring is bytes, then it is decoded into str using utf-8 encoding.

All checks added using the check() & co. decorators are added into the function. There is no way to supply your own checks through this decorator.

Parameters:
  • name (str) – The name to create the command with. By default this uses the function name unchanged.

  • cls – The class to construct with. By default this is Command. You usually do not change this.

  • attrs – Keyword arguments to pass into the construction of the class denoted by cls.

Raises:

TypeError – If the function is not a coroutine or is already a command.

@disnake.ext.commands.slash_command(*, name=None, description=None, dm_permission=None, default_member_permissions=None, options=None, guild_ids=None, connectors=None, auto_sync=None, extras=None, **kwargs)[source]

A decorator that builds a slash command.

Parameters:
  • auto_sync (bool) – Whether to automatically register the command. Defaults to True.

  • name (Optional[Union[str, Localized]]) –

    The name of the slash command (defaults to function name).

    Changed in version 2.5: Added support for localizations.

  • description (Optional[Union[str, Localized]]) –

    The description of the slash command. It will be visible in Discord.

    Changed in version 2.5: Added support for localizations.

  • options (List[Option]) – The list of slash command options. The options will be visible in Discord. This is the old way of specifying options. Consider using Parameters instead.

  • dm_permission (bool) – Whether this command can be used in DMs. Defaults to True.

  • default_member_permissions (Optional[Union[Permissions, int]]) –

    The default required permissions for this command. See ApplicationCommand.default_member_permissions for details.

    New in version 2.5.

  • guild_ids (List[int]) – If specified, the client will register the command in these guilds. Otherwise, this command will be registered globally.

  • connectors (Dict[str, str]) – Binds function names to option names. If the name of an option already matches the corresponding function param, you don’t have to specify the connectors. Connectors template: {"option-name": "param_name", ...}. If you’re using Parameters, you don’t need to specify this.

  • extras (Dict[str, Any]) –

    A dict of user provided extras to attach to the command.

    Note

    This object may be copied by the library.

    New in version 2.5.

Returns:

A decorator that converts the provided method into an InvokableSlashCommand and returns it.

Return type:

Callable[…, InvokableSlashCommand]

@disnake.ext.commands.user_command(*, name=None, dm_permission=None, default_member_permissions=None, guild_ids=None, auto_sync=None, extras=None, **kwargs)[source]

A shortcut decorator that builds a user command.

Parameters:
  • name (Optional[Union[str, Localized]]) –

    The name of the user command (defaults to the function name).

    Changed in version 2.5: Added support for localizations.

  • dm_permission (bool) – Whether this command can be used in DMs. Defaults to True.

  • default_member_permissions (Optional[Union[Permissions, int]]) –

    The default required permissions for this command. See ApplicationCommand.default_member_permissions for details.

    New in version 2.5.

  • auto_sync (bool) – Whether to automatically register the command. Defaults to True.

  • guild_ids (Sequence[int]) – If specified, the client will register the command in these guilds. Otherwise, this command will be registered globally.

  • extras (Dict[str, Any]) –

    A dict of user provided extras to attach to the command.

    Note

    This object may be copied by the library.

    New in version 2.5.

Returns:

A decorator that converts the provided method into an InvokableUserCommand and returns it.

Return type:

Callable[…, InvokableUserCommand]

@disnake.ext.commands.message_command(*, name=None, dm_permission=None, default_member_permissions=None, guild_ids=None, auto_sync=None, extras=None, **kwargs)[source]

A shortcut decorator that builds a message command.

Parameters:
  • name (Optional[Union[str, Localized]]) –

    The name of the message command (defaults to the function name).

    Changed in version 2.5: Added support for localizations.

  • dm_permission (bool) – Whether this command can be used in DMs. Defaults to True.

  • default_member_permissions (Optional[Union[Permissions, int]]) –

    The default required permissions for this command. See ApplicationCommand.default_member_permissions for details.

    New in version 2.5.

  • auto_sync (bool) – Whether to automatically register the command. Defaults to True.

  • guild_ids (Sequence[int]) – If specified, the client will register the command in these guilds. Otherwise, this command will be registered globally.

  • extras (Dict[str, Any]) –

    A dict of user provided extras to attach to the command.

    Note

    This object may be copied by the library.

    New in version 2.5.

Returns:

A decorator that converts the provided method into an InvokableMessageCommand and then returns it.

Return type:

Callable[…, InvokableMessageCommand]

@disnake.ext.commands.group(name=..., cls=..., **attrs)[source]

A decorator that transforms a function into a Group.

This is similar to the command() decorator but the cls parameter is set to Group by default.

Changed in version 1.1: The cls parameter can now be passed.

Helper Functions
disnake.ext.commands.Param(default=Ellipsis, *, name=None, description=None, choices=None, converter=None, convert_defaults=False, autocomplete=None, channel_types=None, lt=None, le=None, gt=None, ge=None, large=False, min_length=None, max_length=None, **kwargs)[source]

A special function that creates an instance of ParamInfo that contains some information about a slash command option. This instance should be assigned to a parameter of a function representing your slash command.

See Parameters for more info.

Parameters:
  • default (Union[Any, Callable[[ApplicationCommandInteraction], Any]]) – The actual default value of the function parameter that should be passed instead of the ParamInfo instance. Can be a sync/async callable taking an interaction and returning a dynamic default value, if the user didn’t pass a value for this parameter.

  • name (Optional[Union[str, Localized]]) –

    The name of the option. By default, the option name is the parameter name.

    Changed in version 2.5: Added support for localizations.

  • description (Optional[Union[str, Localized]]) –

    The description of the option. You can skip this kwarg and use docstrings. See Parameters. Kwarg aliases: desc.

    Changed in version 2.5: Added support for localizations.

  • choices (Union[List[OptionChoice], List[Union[str, int]], Dict[str, Union[str, int]]]) – A list of choices for this option.

  • converter (Callable[[ApplicationCommandInteraction, Any], Any]) – A function that will convert the original input to a desired format. Kwarg aliases: conv.

  • convert_defaults (bool) –

    Whether to also apply the converter to the provided default value. Defaults to False.

    New in version 2.3.

  • autocomplete (Callable[[ApplicationCommandInteraction, str], Any]) – A function that will suggest possible autocomplete options while typing. See Parameters. Kwarg aliases: autocomp.

  • channel_types (Iterable[ChannelType]) – A list of channel types that should be allowed. By default these are discerned from the annotation.

  • lt (float) – The (exclusive) upper bound of values for this option (less-than).

  • le (float) – The (inclusive) upper bound of values for this option (less-than-or-equal). Kwarg aliases: max_value.

  • gt (float) – The (exclusive) lower bound of values for this option (greater-than).

  • ge (float) – The (inclusive) lower bound of values for this option (greater-than-or-equal). Kwarg aliases: min_value.

  • large (bool) –

    Whether to accept large int values (if this is False, only values in the range (-2^53, 2^53) would be accepted due to an API limitation).

    New in version 2.3.

  • min_length (int) –

    The minimum length for this option if this is a string option.

    New in version 2.6.

  • max_length (int) –

    The maximum length for this option if this is a string option.

    New in version 2.6.

Raises:

TypeError – Unexpected keyword arguments were provided.

Returns:

An instance with the option info.

Note

In terms of typing, this returns Any to avoid typing issues, but at runtime this is always a ParamInfo instance. You can find a more in-depth explanation here.

Return type:

ParamInfo

disnake.ext.commands.option_enum(choices, **kwargs)[source]

A utility function to create an enum type. Returns a new Enum based on the provided parameters.

New in version 2.1.

Parameters:
  • choices (Union[Dict[str, Any], List[Any]]) – A name/value mapping of choices, or a list of values whose stringified representations will be used as the names.

  • **kwargs – Name/value pairs to use instead of the choices parameter.

@disnake.ext.commands.converter_method(function)[source]

A decorator to register a method as the converter method.

New in version 2.3.

Application Command
class disnake.ext.commands.InvokableApplicationCommand(*args, **kwargs)[source]

A base class that implements the protocol for a bot application command.

These are not created manually, instead they are created via the decorator or functional interface.

The following classes implement this ABC:

name

The name of the command.

Type:

str

qualified_name

The full command name, including parent names in the case of slash subcommands or groups. For example, the qualified name for /one two three would be one two three.

Type:

str

body

An object being registered in the API.

Type:

ApplicationCommand

callback[source]

The coroutine that is executed when the command is called.

Type:

coroutine

cog

The cog that this command belongs to. None if there isn’t one.

Type:

Optional[Cog]

checks

A list of predicates that verifies if the command could be executed with the given ApplicationCommandInteraction as the sole parameter. If an exception is necessary to be thrown to signal failure, then one inherited from CommandError should be used. Note that if the checks fail then CheckFailure exception is raised to the on_slash_command_error() event.

Type:

List[Callable[[ApplicationCommandInteraction], bool]]

guild_ids

The list of IDs of the guilds where the command is synced. None if this command is global.

Type:

Optional[Tuple[int, …]]

auto_sync

Whether to automatically register the command.

Type:

bool

extras

A dict of user provided extras to attach to the command.

New in version 2.5.

Type:

Dict[str, Any]

@before_invoke[source]

A decorator that registers a coroutine as a pre-invoke hook.

A pre-invoke hook is called directly before the command is called.

This pre-invoke hook takes a sole parameter, a ApplicationCommandInteraction.

Parameters:

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

Raises:

TypeError – The coroutine passed is not actually a coroutine.

@after_invoke[source]

A decorator that registers a coroutine as a post-invoke hook.

A post-invoke hook is called directly after the command is called.

This post-invoke hook takes a sole parameter, a ApplicationCommandInteraction.

Parameters:

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

Raises:

TypeError – The coroutine passed is not actually a coroutine.

@error[source]

A decorator that registers a coroutine as a local error handler.

A local error handler is an error event limited to a single application command.

Parameters:

coro (coroutine) – The coroutine to register as the local error handler.

Raises:

TypeError – The coroutine passed is not actually a coroutine.

copy()[source]

Create a copy of this application command.

Returns:

A new instance of this application command.

Return type:

InvokableApplicationCommand

property dm_permission[source]

Whether this command can be used in DMs.

Type:

bool

property default_member_permissions[source]

The default required member permissions for this command. A member must have all these permissions to be able to invoke the command in a guild.

This is a default value, the set of users/roles that may invoke this command can be overridden by moderators on a guild-specific basis, disregarding this setting.

If None is returned, it means everyone can use the command by default. If an empty Permissions object is returned (that is, all permissions set to False), this means no one can use the command.

New in version 2.5.

Type:

Optional[Permissions]

add_check(func)[source]

Adds a check to the application command.

This is the non-decorator interface to check().

Parameters:

func – The function that will be used as a check.

remove_check(func)[source]

Removes a check from the application command.

This function is idempotent and will not raise an exception if the function is not in the command’s checks.

Parameters:

func – The function to remove from the checks.

is_on_cooldown(inter)[source]

Checks whether the application command is currently on cooldown.

Parameters:

inter (ApplicationCommandInteraction) – The interaction with the application command currently being invoked.

Returns:

A boolean indicating if the application command is on cooldown.

Return type:

bool

reset_cooldown(inter)[source]

Resets the cooldown on this application command.

Parameters:

inter (ApplicationCommandInteraction) – The interaction with this application command

get_cooldown_retry_after(inter)[source]

Retrieves the amount of seconds before this application command can be tried again.

Parameters:

inter (ApplicationCommandInteraction) – The interaction with this application command.

Returns:

The amount of time left on this command’s cooldown in seconds. If this is 0.0 then the command isn’t on cooldown.

Return type:

float

await invoke(inter, *args, **kwargs)[source]

This method isn’t really usable in this class, but it’s usable in subclasses.

has_error_handler()[source]

Checks whether the application command has an error handler registered.

property cog_name[source]

The name of the cog this application command belongs to, if any.

Type:

Optional[str]

await can_run(inter)[source]

This function is a coroutine.

Checks if the command can be executed by checking all the predicates inside the checks attribute.

Parameters:

inter (ApplicationCommandInteraction) – The interaction with the application command currently being invoked.

Raises:

CommandError – Any application command error that was raised during a check call will be propagated by this function.

Returns:

A boolean indicating if the application command can be invoked.

Return type:

bool

Slash Command
class disnake.ext.commands.InvokableSlashCommand(*args, **kwargs)[source]

A class that implements the protocol for a bot slash command.

These are not created manually, instead they are created via the decorator or functional interface.

name

The name of the command.

Type:

str

qualified_name

The full command name, including parent names in the case of slash subcommands or groups. For example, the qualified name for /one two three would be one two three.

Type:

str

body

An object being registered in the API.

Type:

SlashCommand

callback[source]

The coroutine that is executed when the command is called.

Type:

coroutine

cog

The cog that this command belongs to. None if there isn’t one.

Type:

Optional[Cog]

checks

A list of predicates that verifies if the command could be executed with the given ApplicationCommandInteraction as the sole parameter. If an exception is necessary to be thrown to signal failure, then one inherited from CommandError should be used. Note that if the checks fail then CheckFailure exception is raised to the on_slash_command_error() event.

Type:

List[Callable[[ApplicationCommandInteraction], bool]]

guild_ids

The list of IDs of the guilds where the command is synced. None if this command is global.

Type:

Optional[Tuple[int, …]]

connectors

A mapping of option names to function parameter names, mainly for internal processes.

Type:

Dict[str, str]

auto_sync

Whether to automatically register the command.

Type:

bool

extras

A dict of user provided extras to attach to the command.

Note

This object may be copied by the library.

New in version 2.5.

Type:

Dict[str, Any]

parent

This exists for consistency with SubCommand and SubCommandGroup. Always None.

New in version 2.6.

Type:

None

@sub_command(*args, **kwargs)[source]

A decorator that creates a subcommand under the base command.

Parameters:
  • name (Optional[Union[str, Localized]]) –

    The name of the subcommand (defaults to function name).

    Changed in version 2.5: Added support for localizations.

  • description (Optional[Union[str, Localized]]) –

    The description of the subcommand.

    Changed in version 2.5: Added support for localizations.

  • options (List[Option]) – the options of the subcommand for registration in API

  • connectors (Dict[str, str]) – which function param states for each option. If the name of an option already matches the corresponding function param, you don’t have to specify the connectors. Connectors template: {"option-name": "param_name", ...}

  • extras (Dict[str, Any]) –

    A dict of user provided extras to attach to the subcommand.

    Note

    This object may be copied by the library.

    New in version 2.5.

Returns:

A decorator that converts the provided method into a SubCommand, adds it to the bot, then returns it.

Return type:

Callable[…, SubCommand]

@sub_command_group(*args, **kwargs)[source]

A decorator that creates a subcommand group under the base command.

Parameters:
  • name (Optional[Union[str, Localized]]) –

    The name of the subcommand group (defaults to function name).

    Changed in version 2.5: Added support for localizations.

  • extras (Dict[str, Any]) –

    A dict of user provided extras to attach to the subcommand group.

    Note

    This object may be copied by the library.

    New in version 2.5.

Returns:

A decorator that converts the provided method into a SubCommandGroup, adds it to the bot, then returns it.

Return type:

Callable[…, SubCommandGroup]

@after_invoke[source]

A decorator that registers a coroutine as a post-invoke hook.

A post-invoke hook is called directly after the command is called.

This post-invoke hook takes a sole parameter, a ApplicationCommandInteraction.

Parameters:

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

Raises:

TypeError – The coroutine passed is not actually a coroutine.

@before_invoke[source]

A decorator that registers a coroutine as a pre-invoke hook.

A pre-invoke hook is called directly before the command is called.

This pre-invoke hook takes a sole parameter, a ApplicationCommandInteraction.

Parameters:

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

Raises:

TypeError – The coroutine passed is not actually a coroutine.

@error[source]

A decorator that registers a coroutine as a local error handler.

A local error handler is an error event limited to a single application command.

Parameters:

coro (coroutine) – The coroutine to register as the local error handler.

Raises:

TypeError – The coroutine passed is not actually a coroutine.

property root_parent[source]

This is for consistency with SubCommand and SubCommandGroup.

New in version 2.6.

Type:

None

property parents[source]

This is mainly for consistency with SubCommand, and is equivalent to an empty tuple.

New in version 2.6.

Type:

Tuple[()]

autocomplete(option_name)[source]

A decorator that registers an autocomplete function for the specified option.

Parameters:

option_name (str) – The name of the slash command option.

await invoke(inter)[source]

This method isn’t really usable in this class, but it’s usable in subclasses.

Slash Subcommand
class disnake.ext.commands.SubCommand(*args, **kwargs)[source]

A class that implements the protocol for a bot slash subcommand.

These are not created manually, instead they are created via the decorator or functional interface.

name

The name of the subcommand.

Type:

str

qualified_name

The full command name, including parent names in the case of slash subcommands or groups. For example, the qualified name for /one two three would be one two three.

Type:

str

parent

The parent command or group this subcommand belongs to.

New in version 2.6.

Type:

Union[InvokableSlashCommand, SubCommandGroup]

option

API representation of this subcommand.

Type:

Option

callback[source]

The coroutine that is executed when the subcommand is called.

Type:

coroutine

cog

The cog that this subcommand belongs to. None if there isn’t one.

Type:

Optional[Cog]

checks

A list of predicates that verifies if the subcommand could be executed with the given ApplicationCommandInteraction as the sole parameter. If an exception is necessary to be thrown to signal failure, then one inherited from CommandError should be used. Note that if the checks fail then CheckFailure exception is raised to the on_slash_command_error() event.

Type:

List[Callable[[ApplicationCommandInteraction], bool]]

connectors

A mapping of option names to function parameter names, mainly for internal processes.

Type:

Dict[str, str]

extras

A dict of user provided extras to attach to the subcommand.

Note

This object may be copied by the library.

New in version 2.5.

Type:

Dict[str, Any]

@after_invoke[source]

A decorator that registers a coroutine as a post-invoke hook.

A post-invoke hook is called directly after the command is called.

This post-invoke hook takes a sole parameter, a ApplicationCommandInteraction.

Parameters:

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

Raises:

TypeError – The coroutine passed is not actually a coroutine.

@before_invoke[source]

A decorator that registers a coroutine as a pre-invoke hook.

A pre-invoke hook is called directly before the command is called.

This pre-invoke hook takes a sole parameter, a ApplicationCommandInteraction.

Parameters:

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

Raises:

TypeError – The coroutine passed is not actually a coroutine.

@error[source]

A decorator that registers a coroutine as a local error handler.

A local error handler is an error event limited to a single application command.

Parameters:

coro (coroutine) – The coroutine to register as the local error handler.

Raises:

TypeError – The coroutine passed is not actually a coroutine.

property root_parent[source]

Returns the top-level slash command containing this subcommand, even if the parent is a SubCommandGroup.

New in version 2.6.

Type:

InvokableSlashCommand

property parents[source]

Union[Tuple[InvokableSlashCommand], Tuple[SubCommandGroup, InvokableSlashCommand]]: Returns all parents of this subcommand.

For example, the parents of the c subcommand in /a b c are (b, a).

New in version 2.6.

await invoke(inter, *args, **kwargs)[source]

This method isn’t really usable in this class, but it’s usable in subclasses.

autocomplete(option_name)[source]

A decorator that registers an autocomplete function for the specified option.

Parameters:

option_name (str) – The name of the slash command option.

Slash Subcommand Group
class disnake.ext.commands.SubCommandGroup(*args, **kwargs)[source]

A class that implements the protocol for a bot slash command group.

These are not created manually, instead they are created via the decorator or functional interface.

name

The name of the group.

Type:

str

qualified_name

The full command name, including parent names in the case of slash subcommands or groups. For example, the qualified name for /one two three would be one two three.

Type:

str

parent

The parent command this group belongs to.

New in version 2.6.

Type:

InvokableSlashCommand

option

API representation of this subcommand.

Type:

Option

callback[source]

The coroutine that is executed when the command group is invoked.

Type:

coroutine

cog

The cog that this group belongs to. None if there isn’t one.

Type:

Optional[Cog]

checks

A list of predicates that verifies if the group could be executed with the given ApplicationCommandInteraction as the sole parameter. If an exception is necessary to be thrown to signal failure, then one inherited from CommandError should be used. Note that if the checks fail then CheckFailure exception is raised to the on_slash_command_error() event.

Type:

List[Callable[[ApplicationCommandInteraction], bool]]

extras

A dict of user provided extras to attach to the subcommand group.

Note

This object may be copied by the library.

New in version 2.5.

Type:

Dict[str, Any]

@sub_command(*args, **kwargs)[source]

A decorator that creates a subcommand in the subcommand group. Parameters are the same as in InvokableSlashCommand.sub_command

Returns:

A decorator that converts the provided method into a SubCommand, adds it to the bot, then returns it.

Return type:

Callable[…, SubCommand]

@after_invoke[source]

A decorator that registers a coroutine as a post-invoke hook.

A post-invoke hook is called directly after the command is called.

This post-invoke hook takes a sole parameter, a ApplicationCommandInteraction.

Parameters:

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

Raises:

TypeError – The coroutine passed is not actually a coroutine.

@before_invoke[source]

A decorator that registers a coroutine as a pre-invoke hook.

A pre-invoke hook is called directly before the command is called.

This pre-invoke hook takes a sole parameter, a ApplicationCommandInteraction.

Parameters:

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

Raises:

TypeError – The coroutine passed is not actually a coroutine.

@error[source]

A decorator that registers a coroutine as a local error handler.

A local error handler is an error event limited to a single application command.

Parameters:

coro (coroutine) – The coroutine to register as the local error handler.

Raises:

TypeError – The coroutine passed is not actually a coroutine.

property root_parent[source]

Returns the slash command containing this group. This is mainly for consistency with SubCommand, and is equivalent to parent.

New in version 2.6.

Type:

InvokableSlashCommand

property parents[source]

Returns all parents of this group.

New in version 2.6.

Type:

Tuple[InvokableSlashCommand]

ParamInfo
class disnake.ext.commands.ParamInfo(default=Ellipsis, *, name=None, description=None, converter=None, convert_default=False, autocomplete=None, choices=None, type=None, channel_types=None, lt=None, le=None, gt=None, ge=None, large=False, min_length=None, max_length=None)[source]

A class that basically connects function params with slash command options. The instances of this class are not created manually, but via the functional interface instead. See Param().

Parameters:
  • default (Union[Any, Callable[[ApplicationCommandInteraction], Any]]) – The actual default value for the corresponding function param. Can be a sync/async callable taking an interaction and returning a dynamic default value, if the user didn’t pass a value for this parameter.

  • name (Optional[Union[str, Localized]]) –

    The name of this slash command option.

    Changed in version 2.5: Added support for localizations.

  • description (Optional[Union[str, Localized]]) –

    The description of this slash command option.

    Changed in version 2.5: Added support for localizations.

  • choices (Union[List[OptionChoice], List[Union[str, int]], Dict[str, Union[str, int]]]) – The list of choices of this slash command option.

  • ge (float) – The lowest allowed value for this option.

  • le (float) – The greatest allowed value for this option.

  • type (Any) – The type of the parameter.

  • channel_types (List[ChannelType]) – The list of channel types supported by this slash command option.

  • autocomplete (Callable[[ApplicationCommandInteraction, str], Any]) – The function that will suggest possible autocomplete options while typing.

  • converter (Callable[[ApplicationCommandInteraction, Any], Any]) – The function that will convert the original input to a desired format.

  • min_length (int) –

    The minimum length for this option, if it is a string option.

    New in version 2.6.

  • max_length (int) –

    The maximum length for this option, if it is a string option.

    New in version 2.6.

Injections
Methods
class disnake.ext.commands.Injection(function, *, autocompleters=None)[source]

Represents a slash command injection.

New in version 2.3.

Changed in version 2.6: Added keyword-only argument autocompleters.

function

The underlying injection function.

Type:

Callable

autocompleters

A mapping of injection’s option names to their respective autocompleters.

New in version 2.6.

Type:

Dict[str, Callable]

@autocomplete(option_name)[source]

A decorator that registers an autocomplete function for the specified option.

New in version 2.6.

Parameters:

option_name (str) – The name of the option.

Raises:
  • ValueError – This injection already has an autocompleter set for the given option

  • TypeErroroption_name is not str

__call__(*args, **kwargs)[source]

Calls the underlying function that the injection holds.

New in version 2.6.

disnake.ext.commands.inject(function, *, autocompleters=None)[source]

A special function to use the provided function for injections. This should be assigned to a parameter of a function representing your slash command.

New in version 2.3.

Changed in version 2.6: Added autocompleters keyword-only argument.

Parameters:
  • function (Callable) – The injection function.

  • autocompleters (Dict[str, Callable]) –

    A mapping of the injection’s option names to their respective autocompleters.

    See also Injection.autocomplete().

    New in version 2.6.

Returns:

The resulting injection

Note

The return type is annotated with Any to avoid typing issues caused by how this extension works, but at runtime this is always an Injection instance. You can find more in-depth explanation here.

Return type:

Injection

@disnake.ext.commands.register_injection(function, *, autocompleters=None)[source]

A decorator to register a global injection.

New in version 2.3.

Changed in version 2.6: Now returns disnake.ext.commands.Injection.

Changed in version 2.6: Added autocompleters keyword-only argument.

Raises:

TypeError – Injection doesn’t have a return annotation, or tries to overwrite builtin types.

Returns:

The injection being registered.

Return type:

Injection

@disnake.ext.commands.injection(*, autocompleters=None)[source]

Decorator interface for inject(). You can then assign this value to your slash commands’ parameters.

New in version 2.6.

Parameters:

autocompleters (Dict[str, Callable]) –

A mapping of the injection’s option names to their respective autocompleters.

See also Injection.autocomplete().

Returns:

Decorator which turns your injection function into actual Injection.

Note

The decorator return type is annotated with Any to avoid typing issues caused by how this extension works, but at runtime this is always an Injection instance. You can find more in-depth explanation here.

Return type:

Callable[[Callable[…, Any]], Injection]

User Command
class disnake.ext.commands.InvokableUserCommand(*args, **kwargs)[source]

A class that implements the protocol for a bot user command (context menu).

These are not created manually, instead they are created via the decorator or functional interface.

name

The name of the user command.

Type:

str

qualified_name

The full command name, equivalent to name for this type of command.

Type:

str

body

An object being registered in the API.

Type:

UserCommand

callback[source]

The coroutine that is executed when the user command is called.

Type:

coroutine

cog

The cog that this user command belongs to. None if there isn’t one.

Type:

Optional[Cog]

checks

A list of predicates that verifies if the command could be executed with the given ApplicationCommandInteraction as the sole parameter. If an exception is necessary to be thrown to signal failure, then one inherited from CommandError should be used. Note that if the checks fail then CheckFailure exception is raised to the on_user_command_error() event.

Type:

List[Callable[[ApplicationCommandInteraction], bool]]

guild_ids

The list of IDs of the guilds where the command is synced. None if this command is global.

Type:

Optional[Tuple[int, …]]

auto_sync

Whether to automatically register the command.

Type:

bool

extras

A dict of user provided extras to attach to the command.

Note

This object may be copied by the library.

New in version 2.5.

Type:

Dict[str, Any]

@after_invoke[source]

A decorator that registers a coroutine as a post-invoke hook.

A post-invoke hook is called directly after the command is called.

This post-invoke hook takes a sole parameter, a ApplicationCommandInteraction.

Parameters:

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

Raises:

TypeError – The coroutine passed is not actually a coroutine.

@before_invoke[source]

A decorator that registers a coroutine as a pre-invoke hook.

A pre-invoke hook is called directly before the command is called.

This pre-invoke hook takes a sole parameter, a ApplicationCommandInteraction.

Parameters:

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

Raises:

TypeError – The coroutine passed is not actually a coroutine.

@error[source]

A decorator that registers a coroutine as a local error handler.

A local error handler is an error event limited to a single application command.

Parameters:

coro (coroutine) – The coroutine to register as the local error handler.

Raises:

TypeError – The coroutine passed is not actually a coroutine.

await __call__(interaction, target=None, *args, **kwargs)[source]

This function is a coroutine.

Calls the internal callback that the application command holds.

Note

This bypasses all mechanisms – including checks, converters, invoke hooks, cooldowns, etc. You must take care to pass the proper arguments and types to this function.

Message Command
class disnake.ext.commands.InvokableMessageCommand(*args, **kwargs)[source]

A class that implements the protocol for a bot message command (context menu).

These are not created manually, instead they are created via the decorator or functional interface.

name

The name of the message command.

Type:

str

qualified_name

The full command name, equivalent to name for this type of command.

Type:

str

body

An object being registered in the API.

Type:

MessageCommand

callback[source]

The coroutine that is executed when the message command is called.

Type:

coroutine

cog

The cog that this message command belongs to. None if there isn’t one.

Type:

Optional[Cog]

checks

A list of predicates that verifies if the command could be executed with the given ApplicationCommandInteraction as the sole parameter. If an exception is necessary to be thrown to signal failure, then one inherited from CommandError should be used. Note that if the checks fail then CheckFailure exception is raised to the on_message_command_error() event.

Type:

List[Callable[[ApplicationCommandInteraction], bool]]

guild_ids

The list of IDs of the guilds where the command is synced. None if this command is global.

Type:

Optional[Tuple[int, …]]

auto_sync

Whether to automatically register the command.

Type:

bool

extras

A dict of user provided extras to attach to the command.

Note

This object may be copied by the library.

New in version 2.5.

Type:

Dict[str, Any]

@after_invoke[source]

A decorator that registers a coroutine as a post-invoke hook.

A post-invoke hook is called directly after the command is called.

This post-invoke hook takes a sole parameter, a ApplicationCommandInteraction.

Parameters:

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

Raises:

TypeError – The coroutine passed is not actually a coroutine.

@before_invoke[source]

A decorator that registers a coroutine as a pre-invoke hook.

A pre-invoke hook is called directly before the command is called.

This pre-invoke hook takes a sole parameter, a ApplicationCommandInteraction.

Parameters:

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

Raises:

TypeError – The coroutine passed is not actually a coroutine.

@error[source]

A decorator that registers a coroutine as a local error handler.

A local error handler is an error event limited to a single application command.

Parameters:

coro (coroutine) – The coroutine to register as the local error handler.

Raises:

TypeError – The coroutine passed is not actually a coroutine.

await __call__(interaction, target=None, *args, **kwargs)[source]

This function is a coroutine.

Calls the internal callback that the application command holds.

Note

This bypasses all mechanisms – including checks, converters, invoke hooks, cooldowns, etc. You must take care to pass the proper arguments and types to this function.

Command
class disnake.ext.commands.Command(*args, **kwargs)[source]

A class that implements the protocol for a bot text command.

These are not created manually, instead they are created via the decorator or functional interface.

name

The name of the command.

Type:

str

callback[source]

The coroutine that is executed when the command is called.

Type:

coroutine

help

The long help text for the command.

Type:

Optional[str]

brief

The short help text for the command.

Type:

Optional[str]

usage

A replacement for arguments in the default help text.

Type:

Optional[str]

aliases

The list of aliases the command can be invoked under.

Type:

Union[List[str], Tuple[str]]

enabled

Whether the command is currently enabled. If the command is invoked while it is disabled, then DisabledCommand is raised to the on_command_error() event. Defaults to True.

Type:

bool

parent

The parent group that this command belongs to. None if there isn’t one.

Type:

Optional[Group]

cog

The cog that this command belongs to. None if there isn’t one.

Type:

Optional[Cog]

checks

A list of predicates that verifies if the command could be executed with the given Context as the sole parameter. If an exception is necessary to be thrown to signal failure, then one inherited from CommandError should be used. Note that if the checks fail then CheckFailure exception is raised to the on_command_error() event.

Type:

List[Callable[[Context], bool]]

description

The message prefixed into the default help command.

Type:

str

hidden

If True, the default help command does not show this in the help output.

Type:

bool

rest_is_raw

If False and a keyword-only argument is provided then the keyword only argument is stripped and handled as if it was a regular argument that handles MissingRequiredArgument and default values in a regular matter rather than passing the rest completely raw. If True then the keyword-only argument will pass in the rest of the arguments in a completely raw matter. Defaults to False.

Type:

bool

invoked_subcommand

The subcommand that was invoked, if any.

Type:

Optional[Command]

require_var_positional

If True and a variadic positional argument is specified, requires the user to specify at least one argument. Defaults to False.

New in version 1.5.

Type:

bool

ignore_extra

If True, ignores extraneous strings passed to a command if all its requirements are met (e.g. ?foo a b c when only expecting a and b). Otherwise on_command_error() and local error handlers are called with TooManyArguments. Defaults to True.

Type:

bool

cooldown_after_parsing

If True, cooldown processing is done after argument parsing, which calls converters. If False then cooldown processing is done first and then the converters are called second. Defaults to False.

Type:

bool

extras

A dict of user provided extras to attach to the Command.

Note

This object may be copied by the library.

New in version 2.0.

Type:

dict

@after_invoke[source]

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.

This post-invoke hook takes a sole parameter, a Context.

See Bot.after_invoke() for more info.

Parameters:

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

Raises:

TypeError – The coroutine passed is not actually a coroutine.

@before_invoke[source]

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

See Bot.before_invoke() for more info.

Parameters:

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

Raises:

TypeError – The coroutine passed is not actually a coroutine.

@error[source]

A decorator that registers a coroutine as a local error handler.

A local error handler is an on_command_error() event limited to a single command. However, the on_command_error() is still invoked afterwards as the catch-all.

Parameters:

coro (coroutine) – The coroutine to register as the local error handler.

Raises:

TypeError – The coroutine passed is not actually a coroutine.

add_check(func)[source]

Adds a check to the command.

This is the non-decorator interface to check().

New in version 1.3.

Parameters:

func – The function that will be used as a check.

remove_check(func)[source]

Removes a check from the command.

This function is idempotent and will not raise an exception if the function is not in the command’s checks.

New in version 1.3.

Parameters:

func – The function to remove from the checks.

update(**kwargs)[source]

Updates Command instance with updated attribute.

This works similarly to the command() decorator in terms of parameters in that they are passed to the Command or subclass constructors, sans the name and callback.

await __call__(context, *args, **kwargs)[source]

This function is a coroutine.

Calls the internal callback that the command holds.

Note

This bypasses all mechanisms – including checks, converters, invoke hooks, cooldowns, etc. You must take care to pass the proper arguments and types to this function.

New in version 1.3.

copy()[source]

Creates a copy of this command.

Returns:

A new instance of this command.

Return type:

Command

property clean_params[source]

Dict[str, inspect.Parameter]: Retrieves the parameter dictionary without the context or self parameters.

Useful for inspecting signature.

property full_parent_name[source]

Retrieves the fully qualified parent command name.

This the base command name required to execute it. For example, in ?one two three the parent name would be one two.

Type:

str

property parents[source]

Retrieves the parents of this command.

If the command has no parents then it returns an empty list.

For example in commands ?a b c test, the parents are [c, b, a].

New in version 1.1.

Type:

List[Group]

property root_parent[source]

Retrieves the root parent of this command.

If the command has no parents then it returns None.

For example in commands ?a b c test, the root parent is a.

Type:

Optional[Group]

property qualified_name[source]

Retrieves the fully qualified command name.

This is the full parent name with the command name as well. For example, in ?one two three the qualified name would be one two three.

Type:

str

is_on_cooldown(ctx)[source]

Checks whether the command is currently on cooldown.

Parameters:

ctx (Context) – The invocation context to use when checking the commands cooldown status.

Returns:

A boolean indicating if the command is on cooldown.

Return type:

bool

reset_cooldown(ctx)[source]

Resets the cooldown on this command.

Parameters:

ctx (Context) – The invocation context to reset the cooldown under.

get_cooldown_retry_after(ctx)[source]

Retrieves the amount of seconds before this command can be tried again.

New in version 1.4.

Parameters:

ctx (Context) – The invocation context to retrieve the cooldown from.

Returns:

The amount of time left on this command’s cooldown in seconds. If this is 0.0 then the command isn’t on cooldown.

Return type:

float

has_error_handler()[source]

Whether the command has an error handler registered.

New in version 1.7.

Return type:

bool

property cog_name[source]

The name of the cog this command belongs to, if any.

Type:

Optional[str]

property short_doc[source]

Gets the “short” documentation of a command.

By default, this is the brief attribute. If that lookup leads to an empty string then the first line of the help attribute is used instead.

Type:

str

property signature[source]

Returns a POSIX-like signature useful for help command output.

Type:

str

await can_run(ctx)[source]

This function is a coroutine.

Checks if the command can be executed by checking all the predicates inside the checks attribute. This also checks whether the command is disabled.

Changed in version 1.3: Checks whether the command is disabled.

Parameters:

ctx (Context) – The ctx of the command currently being invoked.

Raises:

CommandError – Any command error that was raised during a check call will be propagated by this function.

Returns:

Whether the command can be invoked.

Return type:

bool

Group
class disnake.ext.commands.Group(*args, **kwargs)[source]

A class that implements a grouping protocol for commands to be executed as subcommands.

This class is a subclass of Command and thus all options valid in Command are valid in here as well.

invoke_without_command

Indicates if the group callback should begin parsing and invocation only if no subcommand was found. Useful for making it an error handling function to tell the user that no subcommand was found or to have different functionality in case no subcommand was found. If this is False, then the group callback will always be invoked first. This means that the checks and the parsing dictated by its parameters will be executed. Defaults to False.

Type:

bool

case_insensitive

Indicates if the group’s commands should be case insensitive. Defaults to False.

Type:

bool

@after_invoke[source]

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.

This post-invoke hook takes a sole parameter, a Context.

See Bot.after_invoke() for more info.

Parameters:

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

Raises:

TypeError – The coroutine passed is not actually a coroutine.

@before_invoke[source]

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

See Bot.before_invoke() for more info.

Parameters:

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

Raises:

TypeError – The coroutine passed is not actually a coroutine.

@command(*args, **kwargs)[source]

A shortcut decorator that invokes command() and adds it to the internal command list via add_command().

Returns:

A decorator that converts the provided method into a Command, adds it to the bot, then returns it.

Return type:

Callable[…, Command]

@error[source]

A decorator that registers a coroutine as a local error handler.

A local error handler is an on_command_error() event limited to a single command. However, the on_command_error() is still invoked afterwards as the catch-all.

Parameters:

coro (coroutine) – The coroutine to register as the local error handler.

Raises:

TypeError – The coroutine passed is not actually a coroutine.

@group(*args, **kwargs)[source]

A shortcut decorator that invokes group() and adds it to the internal command list via add_command().

Returns:

A decorator that converts the provided method into a Group, adds it to the bot, then returns it.

Return type:

Callable[…, Group]

copy()[source]

Creates a copy of this Group.

Returns:

A new instance of this group.

Return type:

Group

add_check(func)[source]

Adds a check to the command.

This is the non-decorator interface to check().

New in version 1.3.

Parameters:

func – The function that will be used as a check.

add_command(command)[source]

Adds a Command into the internal list of commands.

This is usually not called, instead the command() or group() shortcut decorators are used instead.

Changed in version 1.4: Raise CommandRegistrationError instead of generic ClientException

Parameters:

command (Command) – The command to add.

Raises:
await can_run(ctx)[source]

This function is a coroutine.

Checks if the command can be executed by checking all the predicates inside the checks attribute. This also checks whether the command is disabled.

Changed in version 1.3: Checks whether the command is disabled.

Parameters:

ctx (Context) – The ctx of the command currently being invoked.

Raises:

CommandError – Any command error that was raised during a check call will be propagated by this function.

Returns:

Whether the command can be invoked.

Return type:

bool

property clean_params[source]

Dict[str, inspect.Parameter]: Retrieves the parameter dictionary without the context or self parameters.

Useful for inspecting signature.

property cog_name[source]

The name of the cog this command belongs to, if any.

Type:

Optional[str]

property commands[source]

A unique set of commands without aliases that are registered.

Type:

Set[Command]

property full_parent_name[source]

Retrieves the fully qualified parent command name.

This the base command name required to execute it. For example, in ?one two three the parent name would be one two.

Type:

str

get_command(name)[source]

Get a Command from the internal list of commands.

This could also be used as a way to get aliases.

The name could be fully qualified (e.g. 'foo bar') will get the subcommand bar of the group command foo. If a subcommand is not found then None is returned just as usual.

Parameters:

name (str) – The name of the command to get.

Returns:

The command that was requested. If not found, returns None.

Return type:

Optional[Command]

get_cooldown_retry_after(ctx)[source]

Retrieves the amount of seconds before this command can be tried again.

New in version 1.4.

Parameters:

ctx (Context) – The invocation context to retrieve the cooldown from.

Returns:

The amount of time left on this command’s cooldown in seconds. If this is 0.0 then the command isn’t on cooldown.

Return type:

float

has_error_handler()[source]

Whether the command has an error handler registered.

New in version 1.7.

Return type:

bool

is_on_cooldown(ctx)[source]

Checks whether the command is currently on cooldown.

Parameters:

ctx (Context) – The invocation context to use when checking the commands cooldown status.

Returns:

A boolean indicating if the command is on cooldown.

Return type:

bool

property parents[source]

Retrieves the parents of this command.

If the command has no parents then it returns an empty list.

For example in commands ?a b c test, the parents are [c, b, a].

New in version 1.1.

Type:

List[Group]

property qualified_name[source]

Retrieves the fully qualified command name.

This is the full parent name with the command name as well. For example, in ?one two three the qualified name would be one two three.

Type:

str

remove_check(func)[source]

Removes a check from the command.

This function is idempotent and will not raise an exception if the function is not in the command’s checks.

New in version 1.3.

Parameters:

func – The function to remove from the checks.

remove_command(name)[source]

Remove a Command from the internal list of commands.

This could also be used as a way to remove aliases.

Parameters:

name (str) – The name of the command to remove.

Returns:

The command that was removed. If the name is not valid then None is returned instead.

Return type:

Optional[Command]

reset_cooldown(ctx)[source]

Resets the cooldown on this command.

Parameters:

ctx (Context) – The invocation context to reset the cooldown under.

property root_parent[source]

Retrieves the root parent of this command.

If the command has no parents then it returns None.

For example in commands ?a b c test, the root parent is a.

Type:

Optional[Group]

property short_doc[source]

Gets the “short” documentation of a command.

By default, this is the brief attribute. If that lookup leads to an empty string then the first line of the help attribute is used instead.

Type:

str

property signature[source]

Returns a POSIX-like signature useful for help command output.

Type:

str

update(**kwargs)[source]

Updates Command instance with updated attribute.

This works similarly to the command() decorator in terms of parameters in that they are passed to the Command or subclass constructors, sans the name and callback.

for ... in walk_commands()[source]

An iterator that recursively walks through all commands and subcommands.

Changed in version 1.4: Duplicates due to aliases are no longer returned

Yields:

Union[Command, Group] – A command or group from the internal list of commands.

GroupMixin
class disnake.ext.commands.GroupMixin(*args, case_insensitive=False, **kwargs)[source]

A mixin that implements common functionality for classes that behave similar to Group and are allowed to register commands.

all_commands

A mapping of command name to Command objects.

Type:

dict

case_insensitive

Whether the commands should be case insensitive. Defaults to False.

Type:

bool

@command(*args, **kwargs)[source]

A shortcut decorator that invokes command() and adds it to the internal command list via add_command().

Returns:

A decorator that converts the provided method into a Command, adds it to the bot, then returns it.

Return type:

Callable[…, Command]

@group(*args, **kwargs)[source]

A shortcut decorator that invokes group() and adds it to the internal command list via add_command().

Returns:

A decorator that converts the provided method into a Group, adds it to the bot, then returns it.

Return type:

Callable[…, Group]

property commands[source]

A unique set of commands without aliases that are registered.

Type:

Set[Command]

add_command(command)[source]

Adds a Command into the internal list of commands.

This is usually not called, instead the command() or group() shortcut decorators are used instead.

Changed in version 1.4: Raise CommandRegistrationError instead of generic ClientException

Parameters:

command (Command) – The command to add.

Raises:
remove_command(name)[source]

Remove a Command from the internal list of commands.

This could also be used as a way to remove aliases.

Parameters:

name (str) – The name of the command to remove.

Returns:

The command that was removed. If the name is not valid then None is returned instead.

Return type:

Optional[Command]

for ... in walk_commands()[source]

An iterator that recursively walks through all commands and subcommands.

Changed in version 1.4: Duplicates due to aliases are no longer returned

Yields:

Union[Command, Group] – A command or group from the internal list of commands.

get_command(name)[source]

Get a Command from the internal list of commands.

This could also be used as a way to get aliases.

The name could be fully qualified (e.g. 'foo bar') will get the subcommand bar of the group command foo. If a subcommand is not found then None is returned just as usual.

Parameters:

name (str) – The name of the command to get.

Returns:

The command that was requested. If not found, returns None.

Return type:

Optional[Command]

LargeInt
class disnake.ext.commands.LargeInt[source]

Type for large integers in slash commands.

This is a class which inherits from int to allow large numbers in slash commands, meant to be used only for annotations.

Range
class disnake.ext.commands.Range[source]

Type depicting a limited range of allowed values.

See Number Ranges for more information.

New in version 2.4.

String
class disnake.ext.commands.String[source]

Type depicting a string option with limited length.

See String Lengths for more information.

New in version 2.6.

Cogs
Cog
class disnake.ext.commands.Cog(*args, **kwargs)[source]

The base class that all cogs must inherit from.

A cog is a collection of commands, listeners, and optional state to help group commands together. More information on them can be found on the Cogs page.

When inheriting from this class, the options shown in CogMeta are equally valid here.

get_commands()[source]

Returns a list of commands the cog has.

Returns:

A list of Commands that are defined inside this cog.

Note

This does not include subcommands.

Return type:

List[Command]

get_application_commands()[source]

Returns a list of application commands the cog has.

Returns:

A list of InvokableApplicationCommands that are defined inside this cog.

Note

This does not include subcommands.

Return type:

List[InvokableApplicationCommand]

get_slash_commands()[source]

Returns a list of slash commands the cog has.

Returns:

A list of InvokableSlashCommands that are defined inside this cog.

Note

This does not include subcommands.

Return type:

List[InvokableSlashCommand]

get_user_commands()[source]

Returns a list of user commands the cog has.

Returns:

A list of InvokableUserCommands that are defined inside this cog.

Return type:

List[InvokableUserCommand]

get_message_commands()[source]

Returns a list of message commands the cog has.

Returns:

A list of InvokableMessageCommands that are defined inside this cog.

Return type:

List[InvokableMessageCommand]

property qualified_name[source]

Returns the cog’s specified name, not the class name.

Type:

str

property description[source]

Returns the cog’s description, typically the cleaned docstring.

Type:

str

for ... in walk_commands()[source]

An iterator that recursively walks through this cog’s commands and subcommands.

Yields:

Union[Command, Group] – A command or group from the cog.

get_listeners()[source]

Returns a list of (name, function) listener pairs the cog has.

Returns:

The listeners defined in this cog.

Return type:

List[Tuple[str, coroutine]]

classmethod listener(name=...)[source]

A decorator that marks a function as a listener.

This is the cog equivalent of Bot.listen().

Parameters:

name (str) – The name of the event being listened to. If not provided, it defaults to the function’s name.

Raises:

TypeError – The function is not a coroutine function or a string was not passed as the name.

has_error_handler()[source]

Whether the cog has an error handler.

New in version 1.7.

Return type:

bool

has_slash_error_handler()[source]

Whether the cog has a slash command error handler.

Return type:

bool

has_user_error_handler()[source]

Whether the cog has a user command error handler.

Return type:

bool

has_message_error_handler()[source]

Whether the cog has a message command error handler.

Return type:

bool

await cog_load()[source]

A special method that is called as a task when the cog is added.

cog_unload()[source]

A special method that is called when the cog gets removed.

This function cannot be a coroutine. It must be a regular function.

Subclasses must replace this if they want special unloading behaviour.

bot_check_once(ctx)[source]

A special method that registers as a Bot.check_once() check.

This is for text commands only, and doesn’t apply to application commands.

This function can be a coroutine and must take a sole parameter, ctx, to represent the Context.

bot_check(ctx)[source]

A special method that registers as a Bot.check() check.

This is for text commands only, and doesn’t apply to application commands.

This function can be a coroutine and must take a sole parameter, ctx, to represent the Context.

bot_slash_command_check_once(inter)[source]

A special method that registers as a Bot.slash_command_check_once() check.

This function can be a coroutine and must take a sole parameter, inter, to represent the ApplicationCommandInteraction.

bot_slash_command_check(inter)[source]

A special method that registers as a Bot.slash_command_check() check.

This function can be a coroutine and must take a sole parameter, inter, to represent the ApplicationCommandInteraction.

bot_user_command_check_once(inter)[source]

Similar to Bot.slash_command_check_once() but for user commands.

bot_user_command_check(inter)[source]

Similar to Bot.slash_command_check() but for user commands.

bot_message_command_check_once(inter)[source]

Similar to Bot.slash_command_check_once() but for message commands.

bot_message_command_check(inter)[source]

Similar to Bot.slash_command_check() but for message commands.

cog_check(ctx)[source]

A special method that registers as a check() for every text command and subcommand in this cog.

This is for text commands only, and doesn’t apply to application commands.

This function can be a coroutine and must take a sole parameter, ctx, to represent the Context.

cog_slash_command_check(inter)[source]

A special method that registers as a check() for every slash command and subcommand in this cog.

This function can be a coroutine and must take a sole parameter, inter, to represent the ApplicationCommandInteraction.

cog_user_command_check(inter)[source]

Similar to Cog.cog_slash_command_check() but for user commands.

cog_message_command_check(inter)[source]

Similar to Cog.cog_slash_command_check() but for message commands.

await cog_command_error(ctx, error)[source]

A special method that is called whenever an error is dispatched inside this cog.

This is for text commands only, and doesn’t apply to application commands.

This is similar to on_command_error() except only applying to the commands inside this cog.

This must be a coroutine.

Parameters:
  • ctx (Context) – The invocation context where the error happened.

  • error (CommandError) – The error that was raised.

await cog_slash_command_error(inter, error)[source]

A special method that is called whenever an error is dispatched inside this cog.

This is similar to on_slash_command_error() except only applying to the slash commands inside this cog.

This must be a coroutine.

Parameters:
await cog_user_command_error(inter, error)[source]

Similar to cog_slash_command_error() but for user commands.

await cog_message_command_error(inter, error)[source]

Similar to cog_slash_command_error() but for message commands.

await cog_before_invoke(ctx)[source]

A special method that acts as a cog local pre-invoke hook, similar to Command.before_invoke().

This is for text commands only, and doesn’t apply to application commands.

This must be a coroutine.

Parameters:

ctx (Context) – The invocation context.

await cog_after_invoke(ctx)[source]

A special method that acts as a cog local post-invoke hook, similar to Command.after_invoke().

This is for text commands only, and doesn’t apply to application commands.

This must be a coroutine.

Parameters:

ctx (Context) – The invocation context.

await cog_before_slash_command_invoke(inter)[source]

A special method that acts as a cog local pre-invoke hook.

This is similar to Command.before_invoke() but for slash commands.

This must be a coroutine.

Parameters:

inter (ApplicationCommandInteraction) – The interaction of the slash command.

await cog_after_slash_command_invoke(inter)[source]

A special method that acts as a cog local post-invoke hook.

This is similar to Command.after_invoke() but for slash commands.

This must be a coroutine.

Parameters:

inter (ApplicationCommandInteraction) – The interaction of the slash command.

await cog_before_user_command_invoke(inter)[source]

Similar to cog_before_slash_command_invoke() but for user commands.

await cog_after_user_command_invoke(inter)[source]

Similar to cog_after_slash_command_invoke() but for user commands.

await cog_before_message_command_invoke(inter)[source]

Similar to cog_before_slash_command_invoke() but for message commands.

await cog_after_message_command_invoke(inter)[source]

Similar to cog_after_slash_command_invoke() but for message commands.

CogMeta
class disnake.ext.commands.CogMeta(*args, **kwargs)[source]

A metaclass for defining a cog.

Note that you should probably not use this directly. It is exposed purely for documentation purposes along with making custom metaclasses to intermix with other metaclasses such as the abc.ABCMeta metaclass.

For example, to create an abstract cog mixin class, the following would be done.

import abc

class CogABCMeta(commands.CogMeta, abc.ABCMeta):
    pass

class SomeMixin(metaclass=abc.ABCMeta):
    pass

class SomeCogMixin(SomeMixin, commands.Cog, metaclass=CogABCMeta):
    pass

Note

When passing an attribute of a metaclass that is documented below, note that you must pass it as a keyword-only argument to the class creation like the following example:

class MyCog(commands.Cog, name='My Cog'):
    pass
name

The cog name. By default, it is the name of the class with no modification.

Type:

str

description

The cog description. By default, it is the cleaned docstring of the class.

New in version 1.6.

Type:

str

command_attrs

A list of attributes to apply to every command inside this cog. The dictionary is passed into the Command options at __init__. If you specify attributes inside the command attribute in the class, it will override the one specified inside this attribute. For example:

class MyCog(commands.Cog, command_attrs=dict(hidden=True)):
    @commands.command()
    async def foo(self, ctx):
        pass # hidden -> True

    @commands.command(hidden=False)
    async def bar(self, ctx):
        pass # hidden -> False
Type:

Dict[str, Any]

slash_command_attrs

A list of attributes to apply to every slash command inside this cog. The dictionary is passed into the options of every InvokableSlashCommand at __init__. Usage of this kwarg is otherwise the same as with command_attrs.

Note

This does not apply to instances of SubCommand or SubCommandGroup.

New in version 2.5.

Type:

Dict[str, Any]

user_command_attrs

A list of attributes to apply to every user command inside this cog. The dictionary is passed into the options of every InvokableUserCommand at __init__. Usage of this kwarg is otherwise the same as with command_attrs.

New in version 2.5.

Type:

Dict[str, Any]

message_command_attrs

A list of attributes to apply to every message command inside this cog. The dictionary is passed into the options of every InvokableMessageCommand at __init__. Usage of this kwarg is otherwise the same as with command_attrs.

New in version 2.5.

Type:

Dict[str, Any]

Help Commands
HelpCommand
class disnake.ext.commands.HelpCommand(*args, **kwargs)[source]

The base implementation for help command formatting.

Note

Internally instances of this class are deep copied every time the command itself is invoked to prevent a race condition mentioned in #2123.

This means that relying on the state of this class to be the same between command invocations would not work as expected.

context

The context that invoked this help formatter. This is generally set after the help command assigned, command_callback(), has been called.

Type:

Optional[Context]

show_hidden

Specifies if hidden commands should be shown in the output. Defaults to False.

Type:

bool

verify_checks

Specifies if commands should have their Command.checks called and verified. If True, always calls Command.checks. If None, only calls Command.checks in a guild setting. If False, never calls Command.checks. Defaults to True.

Changed in version 1.7.

Type:

Optional[bool]

command_attrs

A dictionary of options to pass in for the construction of the help command. This allows you to change the command behaviour without actually changing the implementation of the command. The attributes will be the same as the ones passed in the Command constructor.

Type:

dict

add_check(func)[source]

Adds a check to the help command.

New in version 1.4.

Parameters:

func – The function that will be used as a check.

remove_check(func)[source]

Removes a check from the help command.

This function is idempotent and will not raise an exception if the function is not in the command’s checks.

New in version 1.4.

Parameters:

func – The function to remove from the checks.

get_bot_mapping()[source]

Retrieves the bot mapping passed to send_bot_help().

property invoked_with[source]

Similar to Context.invoked_with except properly handles the case where Context.send_help() is used.

If the help command was used regularly then this returns the Context.invoked_with attribute. Otherwise, if it the help command was called using Context.send_help() then it returns the internal command name of the help command.

Returns:

The command name that triggered this invocation.

Return type:

str

get_command_signature(command)[source]

Retrieves the signature portion of the help page.

Parameters:

command (Command) – The command to get the signature of.

Returns:

The signature for the command.

Return type:

str

remove_mentions(string)[source]

Removes mentions from the string to prevent abuse.

This includes @everyone, @here, member mentions and role mentions.

Returns:

The string with mentions removed.

Return type:

str

property cog[source]

A property for retrieving or setting the cog for the help command.

When a cog is set for the help command, it is as-if the help command belongs to that cog. All cog special methods will apply to the help command and it will be automatically unset on unload.

To unbind the cog from the help command, you can set it to None.

Returns:

The cog that is currently set for the help command.

Return type:

Optional[Cog]

command_not_found(string)[source]

This function could be a coroutine.

A method called when a command is not found in the help command. This is useful to override for i18n.

Defaults to No command called {0} found.

Parameters:

string (str) – The string that contains the invalid command. Note that this has had mentions removed to prevent abuse.

Returns:

The string to use when a command has not been found.

Return type:

str

subcommand_not_found(command, string)[source]

This function could be a coroutine.

A method called when a command did not have a subcommand requested in the help command. This is useful to override for i18n.

Defaults to either:

  • 'Command "{command.qualified_name}" has no subcommands.'
    • If there is no subcommand in the command parameter.

  • 'Command "{command.qualified_name}" has no subcommand named {string}'
    • If the command parameter has subcommands but not one named string.

Parameters:
  • command (Command) – The command that did not have the subcommand requested.

  • string (str) – The string that contains the invalid subcommand. Note that this has had mentions removed to prevent abuse.

Returns:

The string to use when the command did not have the subcommand requested.

Return type:

str

await filter_commands(commands, *, sort=False, key=None)[source]

This function is a coroutine.

Returns a filtered list of commands and optionally sorts them.

This takes into account the verify_checks and show_hidden attributes.

Parameters:
  • commands (Iterable[Command]) – An iterable of commands that are getting filtered.

  • sort (bool) – Whether to sort the result.

  • key (Optional[Callable[Command, Any]]) – An optional key function to pass to sorted() that takes a Command as its sole parameter. If sort is passed as True then this will default as the command name.

Returns:

A list of commands that passed the filter.

Return type:

List[Command]

get_max_size(commands)[source]

Returns the largest name length of the specified command list.

Parameters:

commands (Sequence[Command]) – A sequence of commands to check for the largest size.

Returns:

The maximum width of the commands.

Return type:

int

get_destination()[source]

Returns the Messageable where the help command will be output.

You can override this method to customise the behaviour.

By default this returns the context’s channel.

Returns:

The destination where the help command will be output.

Return type:

abc.Messageable

await send_error_message(error)[source]

This function is a coroutine.

Handles the implementation when an error happens in the help command. For example, the result of command_not_found() will be passed here.

You can override this method to customise the behaviour.

By default, this sends the error message to the destination specified by get_destination().

Note

You can access the invocation context with HelpCommand.context.

Parameters:

error (str) – The error message to display to the user. Note that this has had mentions removed to prevent abuse.

await on_help_command_error(ctx, error)[source]

This function is a coroutine.

The help command’s error handler, as specified by Error Handling.

Useful to override if you need some specific behaviour when the error handler is called.

By default this method does nothing and just propagates to the default error handlers.

Parameters:
  • ctx (Context) – The invocation context.

  • error (CommandError) – The error that was raised.

await send_bot_help(mapping)[source]

This function is a coroutine.

Handles the implementation of the bot command page in the help command. This function is called when the help command is called with no arguments.

It should be noted that this method does not return anything – rather the actual message sending should be done inside this method. Well behaved subclasses should use get_destination() to know where to send, as this is a customisation point for other users.

You can override this method to customise the behaviour.

Note

You can access the invocation context with HelpCommand.context.

Also, the commands in the mapping are not filtered. To do the filtering you will have to call filter_commands() yourself.

Parameters:

mapping (Mapping[Optional[Cog], List[Command]]) – A mapping of cogs to commands that have been requested by the user for help. The key of the mapping is the Cog that the command belongs to, or None if there isn’t one, and the value is a list of commands that belongs to that cog.

await send_cog_help(cog)[source]

This function is a coroutine.

Handles the implementation of the cog page in the help command. This function is called when the help command is called with a cog as the argument.

It should be noted that this method does not return anything – rather the actual message sending should be done inside this method. Well behaved subclasses should use get_destination() to know where to send, as this is a customisation point for other users.

You can override this method to customise the behaviour.

Note

You can access the invocation context with HelpCommand.context.

To get the commands that belong to this cog see Cog.get_commands(). The commands returned not filtered. To do the filtering you will have to call filter_commands() yourself.

Parameters:

cog (Cog) – The cog that was requested for help.

await send_group_help(group)[source]

This function is a coroutine.

Handles the implementation of the group page in the help command. This function is called when the help command is called with a group as the argument.

It should be noted that this method does not return anything – rather the actual message sending should be done inside this method. Well behaved subclasses should use get_destination() to know where to send, as this is a customisation point for other users.

You can override this method to customise the behaviour.

Note

You can access the invocation context with HelpCommand.context.

To get the commands that belong to this group without aliases see Group.commands. The commands returned are not filtered. To do the filtering you will have to call filter_commands() yourself.

Parameters:

group (Group) – The group that was requested for help.

await send_command_help(command)[source]

This function is a coroutine.

Handles the implementation of the single command page in the help command.

It should be noted that this method does not return anything – rather the actual message sending should be done inside this method. Well behaved subclasses should use get_destination() to know where to send, as this is a customisation point for other users.

You can override this method to customise the behaviour.

Note

You can access the invocation context with HelpCommand.context.

Showing Help

There are certain attributes and methods that are helpful for a help command to show such as the following:

There are more than just these attributes but feel free to play around with these to help you get started to get the output that you want.

Parameters:

command (Command) – The command that was requested for help.

await prepare_help_command(ctx, command=None)[source]

This function is a coroutine.

A low level method that can be used to prepare the help command before it does anything. For example, if you need to prepare some state in your subclass before the command does its processing then this would be the place to do it.

The default implementation does nothing.

Note

This is called inside the help command callback body. So all the usual rules that happen inside apply here as well.

Parameters:
  • ctx (Context) – The invocation context.

  • command (Optional[str]) – The argument passed to the help command.

await command_callback(ctx, *, command=None)[source]

This function is a coroutine.

The actual implementation of the help command.

It is not recommended to override this method and instead change the behaviour through the methods that actually get dispatched.

DefaultHelpCommand
class disnake.ext.commands.DefaultHelpCommand(*args, **kwargs)[source]

The implementation of the default help command.

This inherits from HelpCommand.

It extends it with the following attributes.

width

The maximum number of characters that fit in a line. Defaults to 80.

Type:

int

sort_commands

Whether to sort the commands in the output alphabetically. Defaults to True.

Type:

bool

dm_help

A tribool that indicates if the help command should DM the user instead of sending it to the channel it received it from. If the boolean is set to True, then all help output is DM’d. If False, none of the help output is DM’d. If None, then the bot will only DM when the help message becomes too long (dictated by more than dm_help_threshold characters). Defaults to False.

Type:

Optional[bool]

dm_help_threshold

The number of characters the paginator must accumulate before getting DM’d to the user if dm_help is set to None. Defaults to 1000.

Type:

Optional[int]

indent

How much to indent the commands from a heading. Defaults to 2.

Type:

int

commands_heading

The command list’s heading string used when the help command is invoked with a category name. Useful for i18n. Defaults to "Commands:"

Type:

str

no_category

The string used when there is a command which does not belong to any category(cog). Useful for i18n. Defaults to "No Category"

Type:

str

paginator

The paginator used to paginate the help command output.

Type:

Paginator

shorten_text(text)[source]

Shortens text to fit into the width.

Return type:

str

get_ending_note()[source]

Returns help command’s ending note. This is mainly useful to override for i18n purposes.

Return type:

str

add_indented_commands(commands, *, heading, max_size=None)[source]

Indents a list of commands after the specified heading.

The formatting is added to the paginator.

The default implementation is the command name indented by indent spaces, padded to max_size followed by the command’s Command.short_doc and then shortened to fit into the width.

Parameters:
  • commands (Sequence[Command]) – A list of commands to indent for output.

  • heading (str) – The heading to add to the output. This is only added if the list of commands is greater than 0.

  • max_size (Optional[int]) – The max size to use for the gap between indents. If unspecified, calls get_max_size() on the commands parameter.

await send_pages()[source]

A helper utility to send the page output from paginator to the destination.

add_command_formatting(command)[source]

A utility function to format the non-indented block of commands and groups.

Parameters:

command (Command) – The command to format.

get_destination()[source]

Returns the Messageable where the help command will be output.

You can override this method to customise the behaviour.

By default this returns the context’s channel.

Returns:

The destination where the help command will be output.

Return type:

abc.Messageable

MinimalHelpCommand
class disnake.ext.commands.MinimalHelpCommand(*args, **kwargs)[source]

An implementation of a help command with minimal output.

This inherits from HelpCommand.

sort_commands

Whether to sort the commands in the output alphabetically. Defaults to True.

Type:

bool

commands_heading

The command list’s heading string used when the help command is invoked with a category name. Useful for i18n. Defaults to "Commands"

Type:

str

aliases_heading

The alias list’s heading string used to list the aliases of the command. Useful for i18n. Defaults to "Aliases:".

Type:

str

dm_help

A tribool that indicates if the help command should DM the user instead of sending it to the channel it received it from. If the boolean is set to True, then all help output is DM’d. If False, none of the help output is DM’d. If None, then the bot will only DM when the help message becomes too long (dictated by more than dm_help_threshold characters). Defaults to False.

Type:

Optional[bool]

dm_help_threshold

The number of characters the paginator must accumulate before getting DM’d to the user if dm_help is set to None. Defaults to 1000.

Type:

Optional[int]

no_category

The string used when there is a command which does not belong to any category(cog). Useful for i18n. Defaults to "No Category"

Type:

str

paginator

The paginator used to paginate the help command output.

Type:

Paginator

await send_pages()[source]

A helper utility to send the page output from paginator to the destination.

get_opening_note()[source]

Returns help command’s opening note. This is mainly useful to override for i18n purposes.

The default implementation returns

Use `{prefix}{command_name} [command]` for more info on a command.
You can also use `{prefix}{command_name} [category]` for more info on a category.
Returns:

The help command opening note.

Return type:

str

get_command_signature(command)[source]

Retrieves the signature portion of the help page.

Parameters:

command (Command) – The command to get the signature of.

Returns:

The signature for the command.

Return type:

str

get_ending_note()[source]

Return the help command’s ending note. This is mainly useful to override for i18n purposes.

The default implementation does nothing.

Returns:

The help command ending note.

Return type:

str

add_bot_commands_formatting(commands, heading)[source]

Adds the minified bot heading with commands to the output.

The formatting should be added to the paginator.

The default implementation is a bold underline heading followed by commands separated by an EN SPACE (U+2002) in the next line.

Parameters:
  • commands (Sequence[Command]) – A list of commands that belong to the heading.

  • heading (str) – The heading to add to the line.

add_subcommand_formatting(command)[source]

Adds formatting information on a subcommand.

The formatting should be added to the paginator.

The default implementation is the prefix and the Command.qualified_name optionally followed by an En dash and the command’s Command.short_doc.

Parameters:

command (Command) – The command to show information of.

add_aliases_formatting(aliases)[source]

Adds the formatting information on a command’s aliases.

The formatting should be added to the paginator.

The default implementation is the aliases_heading bolded followed by a comma separated list of aliases.

This is not called if there are no aliases to format.

Parameters:

aliases (Sequence[str]) – A list of aliases to format.

add_command_formatting(command)[source]

A utility function to format commands and groups.

Parameters:

command (Command) – The command to format.

get_destination()[source]

Returns the Messageable where the help command will be output.

You can override this method to customise the behaviour.

By default this returns the context’s channel.

Returns:

The destination where the help command will be output.

Return type:

abc.Messageable

Paginator
Methods
class disnake.ext.commands.Paginator(prefix='```', suffix='```', max_size=2000, linesep='\n')[source]

A class that aids in paginating code blocks for Discord messages.

len(x)

Returns the total number of characters in the paginator.

prefix

The prefix inserted to every page. e.g. three backticks.

Type:

str

suffix

The suffix appended at the end of every page. e.g. three backticks.

Type:

str

max_size

The maximum amount of codepoints allowed in a page.

Type:

int

linesep
The character string inserted between lines. e.g. a newline character.

New in version 1.7.

Type:

str

clear()[source]

Clears the paginator to have no pages.

add_line(line='', *, empty=False)[source]

Adds a line to the current page.

If the line exceeds the max_size then an exception is raised.

Parameters:
  • line (str) – The line to add.

  • empty (bool) – Whether another empty line should be added.

Raises:

RuntimeError – The line was too big for the current max_size.

close_page()[source]

Prematurely terminate a page.

property pages[source]

Returns the rendered list of pages.

Type:

List[str]

Enums
class disnake.ext.commands.BucketType[source]

Specifies a type of bucket for, e.g. a cooldown.

default

The default bucket operates on a global basis.

user

The user bucket operates on a per-user basis.

guild

The guild bucket operates on a per-guild basis.

channel

The channel bucket operates on a per-channel basis.

member

The member bucket operates on a per-member basis.

category

The category bucket operates on a per-category basis.

role

The role bucket operates on a per-role basis.

New in version 1.3.

Checks
@disnake.ext.commands.check(predicate)[source]

A decorator that adds a check to the Command or its subclasses. These checks could be accessed via Command.checks.

These checks should be predicates that take in a single parameter taking a Context. If the check returns a False-like value then during invocation a CheckFailure exception is raised and sent to the on_command_error() event.

If an exception should be thrown in the predicate then it should be a subclass of CommandError. Any exception not subclassed from it will be propagated while those subclassed will be sent to on_command_error().

A special attribute named predicate is bound to the value returned by this decorator to retrieve the predicate passed to the decorator. This allows the following introspection and chaining to be done:

def owner_or_permissions(**perms):
    original = commands.has_permissions(**perms).predicate
    async def extended_check(ctx):
        if ctx.guild is None:
            return False
        return ctx.guild.owner_id == ctx.author.id or await original(ctx)
    return commands.check(extended_check)

Note

The function returned by predicate is always a coroutine, even if the original function was not a coroutine.

Changed in version 1.3: The predicate attribute was added.

Examples

Creating a basic check to see if the command invoker is you.

def check_if_it_is_me(ctx):
    return ctx.message.author.id == 85309593344815104

@bot.command()
@commands.check(check_if_it_is_me)
async def only_for_me(ctx):
    await ctx.send('I know you!')

Transforming common checks into its own decorator:

def is_me():
    def predicate(ctx):
        return ctx.message.author.id == 85309593344815104
    return commands.check(predicate)

@bot.command()
@is_me()
async def only_me(ctx):
    await ctx.send('Only you!')
Parameters:

predicate (Callable[[Context], bool]) – The predicate to check if the command should be invoked.

@disnake.ext.commands.check_any(*checks)[source]

A check() that is added that checks if any of the checks passed will pass, i.e. using logical OR.

If all checks fail then CheckAnyFailure is raised to signal the failure. It inherits from CheckFailure.

Note

The predicate attribute for this function is a coroutine.

New in version 1.3.

Parameters:

*checks (Callable[[Context], bool]) – An argument list of checks that have been decorated with the check() decorator.

Raises:

TypeError – A check passed has not been decorated with the check() decorator.

Examples

Creating a basic check to see if it’s the bot owner or the server owner:

def is_guild_owner():
    def predicate(ctx):
        return ctx.guild is not None and ctx.guild.owner_id == ctx.author.id
    return commands.check(predicate)

@bot.command()
@commands.check_any(commands.is_owner(), is_guild_owner())
async def only_for_owners(ctx):
    await ctx.send('Hello mister owner!')
@disnake.ext.commands.has_role(item)[source]

A check() that is added that checks if the member invoking the command has the role specified via the name or ID specified.

If a string is specified, you must give the exact name of the role, including caps and spelling.

If an integer is specified, you must give the exact snowflake ID of the role.

If the message is invoked in a private message context then the check will return False.

This check raises one of two special exceptions, MissingRole if the user is missing a role, or NoPrivateMessage if it is used in a private message. Both inherit from CheckFailure.

Changed in version 1.1: Raise MissingRole or NoPrivateMessage instead of generic CheckFailure

Parameters:

item (Union[int, str]) – The name or ID of the role to check.

@disnake.ext.commands.has_permissions(**perms)[source]

A check() that is added that checks if the member has all of the permissions necessary.

Note that this check operates on the current channel permissions, not the guild wide permissions.

The permissions passed in must be exactly like the properties shown under disnake.Permissions.

This check raises a special exception, MissingPermissions that is inherited from CheckFailure.

Changed in version 2.6: Considers if the author is timed out.

Parameters:

perms – An argument list of permissions to check for.

Example

@bot.command()
@commands.has_permissions(manage_messages=True)
async def test(ctx):
    await ctx.send('You can manage messages.')
@disnake.ext.commands.has_guild_permissions(**perms)[source]

Similar to has_permissions(), but operates on guild wide permissions instead of the current channel permissions.

If this check is called in a DM context, it will raise an exception, NoPrivateMessage.

New in version 1.3.

@disnake.ext.commands.has_any_role(*items)[source]

A check() that is added that checks if the member invoking the command has any of the roles specified. This means that if they have one out of the three roles specified, then this check will return True.

Similar to has_role(), the names or IDs passed in must be exact.

This check raises one of two special exceptions, MissingAnyRole if the user is missing all roles, or NoPrivateMessage if it is used in a private message. Both inherit from CheckFailure.

Changed in version 1.1: Raise MissingAnyRole or NoPrivateMessage instead of generic CheckFailure

Parameters:

items (List[Union[str, int]]) – An argument list of names or IDs to check that the member has roles wise.

Example

@bot.command()
@commands.has_any_role('Library Devs', 'Moderators', 492212595072434186)
async def cool(ctx):
    await ctx.send('You are cool indeed')
@disnake.ext.commands.bot_has_role(item)[source]

Similar to has_role() except checks if the bot itself has the role.

This check raises one of two special exceptions, BotMissingRole if the bot is missing the role, or NoPrivateMessage if it is used in a private message. Both inherit from CheckFailure.

Changed in version 1.1: Raise BotMissingRole or NoPrivateMessage instead of generic CheckFailure

@disnake.ext.commands.bot_has_permissions(**perms)[source]

Similar to has_permissions() except checks if the bot itself has the permissions listed.

This check raises a special exception, BotMissingPermissions that is inherited from CheckFailure.

Changed in version 2.6: Considers if the author is timed out.

@disnake.ext.commands.bot_has_guild_permissions(**perms)[source]

Similar to has_guild_permissions(), but checks the bot members guild permissions.

New in version 1.3.

@disnake.ext.commands.bot_has_any_role(*items)[source]

Similar to has_any_role() except checks if the bot itself has any of the roles listed.

This check raises one of two special exceptions, BotMissingAnyRole if the bot is missing all roles, or NoPrivateMessage if it is used in a private message. Both inherit from CheckFailure.

Changed in version 1.1: Raise BotMissingAnyRole or NoPrivateMessage instead of generic checkfailure

@disnake.ext.commands.cooldown(rate, per, type=disnake.ext.commands.BucketType.default)[source]

A decorator that adds a cooldown to a Command

A cooldown allows a command to only be used a specific amount of times in a specific time frame. These cooldowns can be based either on a per-guild, per-channel, per-user, per-role or global basis. Denoted by the third argument of type which must be of enum type BucketType.

If a cooldown is triggered, then CommandOnCooldown is triggered in on_command_error() and the local error handler.

A command can only have a single cooldown.

Parameters:
  • rate (int) – The number of times a command can be used before triggering a cooldown.

  • per (float) – The amount of seconds to wait for a cooldown when it’s been triggered.

  • type (Union[BucketType, Callable[[Message], Any]]) –

    The type of cooldown to have. If callable, should return a key for the mapping.

    Changed in version 1.7: Callables are now supported for custom bucket types.

@disnake.ext.commands.dynamic_cooldown(cooldown, type=BucketType.default)[source]

A decorator that adds a dynamic cooldown to a Command

This differs from cooldown() in that it takes a function that accepts a single parameter of type disnake.Message and must return a Cooldown or None. If None is returned then that cooldown is effectively bypassed.

A cooldown allows a command to only be used a specific amount of times in a specific time frame. These cooldowns can be based either on a per-guild, per-channel, per-user, per-role or global basis. Denoted by the third argument of type which must be of enum type BucketType.

If a cooldown is triggered, then CommandOnCooldown is triggered in on_command_error() and the local error handler.

A command can only have a single cooldown.

New in version 2.0.

Parameters:
  • cooldown (Callable[[disnake.Message], Optional[Cooldown]]) – A function that takes a message and returns a cooldown that will apply to this invocation or None if the cooldown should be bypassed.

  • type (BucketType) – The type of cooldown to have.

@disnake.ext.commands.max_concurrency(number, per=disnake.ext.commands.BucketType.default, *, wait=False)[source]

A decorator that adds a maximum concurrency to a Command or its subclasses.

This enables you to only allow a certain number of command invocations at the same time, for example if a command takes too long or if only one user can use it at a time. This differs from a cooldown in that there is no set waiting period or token bucket – only a set number of people can run the command.

New in version 1.3.

Parameters:
  • number (int) – The maximum number of invocations of this command that can be running at the same time.

  • per (BucketType) – The bucket that this concurrency is based on, e.g. BucketType.guild would allow it to be used up to number times per guild.

  • wait (bool) – Whether the command should wait for the queue to be over. If this is set to False then instead of waiting until the command can run again, the command raises MaxConcurrencyReached to its error handler. If this is set to True then the command waits until it can be executed.

@disnake.ext.commands.before_invoke(coro)[source]

A decorator that registers a coroutine as a pre-invoke hook.

This allows you to refer to one before invoke hook for several commands that do not have to be within the same cog.

New in version 1.4.

Example

async def record_usage(ctx):
    print(ctx.author, 'used', ctx.command, 'at', ctx.message.created_at)

@bot.command()
@commands.before_invoke(record_usage)
async def who(ctx): # Output: <User> used who at <Time>
    await ctx.send('i am a bot')

class What(commands.Cog):

    @commands.before_invoke(record_usage)
    @commands.command()
    async def when(self, ctx): # Output: <User> used when at <Time>
        await ctx.send(f'and i have existed since {ctx.bot.user.created_at}')

    @commands.command()
    async def where(self, ctx): # Output: <Nothing>
        await ctx.send('on Discord')

    @commands.command()
    async def why(self, ctx): # Output: <Nothing>
        await ctx.send('because someone made me')

bot.add_cog(What())
@disnake.ext.commands.after_invoke(coro)[source]

A decorator that registers a coroutine as a post-invoke hook.

This allows you to refer to one after invoke hook for several commands that do not have to be within the same cog.

New in version 1.4.

@disnake.ext.commands.guild_only()[source]

A check() that indicates this command must only be used in a guild context only. Basically, no private messages are allowed when using the command.

This check raises a special exception, NoPrivateMessage that is inherited from CheckFailure.

@disnake.ext.commands.dm_only()[source]

A check() that indicates this command must only be used in a DM context. Only private messages are allowed when using the command.

This check raises a special exception, PrivateMessageOnly that is inherited from CheckFailure.

New in version 1.1.

@disnake.ext.commands.is_owner()[source]

A check() that checks if the person invoking this command is the owner of the bot.

This is powered by Bot.is_owner().

This check raises a special exception, NotOwner that is derived from CheckFailure.

@disnake.ext.commands.is_nsfw()[source]

A check() that checks if the channel is a NSFW channel.

This check raises a special exception, NSFWChannelRequired that is derived from CheckFailure.

Changed in version 1.1: Raise NSFWChannelRequired instead of generic CheckFailure. DM channels will also now pass this check.

@disnake.ext.commands.default_member_permissions(value=0, **permissions)[source]

A decorator that sets default required member permissions for the command. Unlike has_permissions(), this decorator does not add any checks. Instead, it prevents the command from being run by members without all required permissions, if not overridden by moderators on a guild-specific basis.

See also the default_member_permissions parameter for application command decorators.

Note

This does not work with slash subcommands/groups.

Example

This would only allow members with manage_messages and view_audit_log permissions to use the command by default, however moderators can override this and allow/disallow specific users and roles to use the command in their guilds regardless of this setting.

@bot.slash_command()
@commands.default_member_permissions(manage_messages=True, view_audit_log=True)
async def purge(inter, num: int):
    ...
Parameters:
  • value (int) – A raw permission bitfield of an integer representing the required permissions. May be used instead of specifying kwargs.

  • **permissions (bool) – The required permissions for a command. A member must have all these permissions to be able to invoke the command. Setting a permission to False does not affect the result.

Cooldown
Attributes
class disnake.ext.commands.Cooldown(rate, per)[source]

Represents a cooldown for a command.

rate

The total number of tokens available per per seconds.

Type:

int

per

The length of the cooldown period in seconds.

Type:

float

get_tokens(current=None)[source]

Returns the number of available tokens before rate limiting is applied.

Parameters:

current (Optional[float]) – The time in seconds since Unix epoch to calculate tokens at. If not supplied then time.time() is used.

Returns:

The number of tokens available before the cooldown is to be applied.

Return type:

int

get_retry_after(current=None)[source]

Returns the time in seconds until the cooldown will be reset.

Parameters:

current (Optional[float]) – The current time in seconds since Unix epoch. If not supplied, then time.time() is used.

Returns:

The number of seconds to wait before this cooldown will be reset.

Return type:

float

update_rate_limit(current=None)[source]

Updates the cooldown rate limit.

Parameters:

current (Optional[float]) – The time in seconds since Unix epoch to update the rate limit at. If not supplied, then time.time() is used.

Returns:

The retry-after time in seconds if rate limited.

Return type:

Optional[float]

reset()[source]

Reset the cooldown to its initial state.

copy()[source]

Creates a copy of this cooldown.

Returns:

A new instance of this cooldown.

Return type:

Cooldown

Context
class disnake.ext.commands.Context(*, message, bot, view, args=..., kwargs=..., prefix=None, command=None, invoked_with=None, invoked_parents=..., invoked_subcommand=None, subcommand_passed=None, command_failed=False, current_parameter=None)[source]

Represents the context in which a command is being invoked under.

This class contains a lot of meta data to help you understand more about the invocation context. This class is not created manually and is instead passed around to commands as the first parameter.

This class implements the abc.Messageable ABC.

message

The message that triggered the command being executed.

Type:

Message

bot

The bot that contains the command being executed.

Type:

Bot

args

The list of transformed arguments that were passed into the command. If this is accessed during the on_command_error() event then this list could be incomplete.

Type:

list

kwargs

A dictionary of transformed arguments that were passed into the command. Similar to args, if this is accessed in the on_command_error() event then this dict could be incomplete.

Type:

dict

current_parameter

The parameter that is currently being inspected and converted. This is only of use for within converters.

New in version 2.0.

Type:

Optional[inspect.Parameter]

prefix

The prefix that was used to invoke the command.

Type:

Optional[str]

command

The command that is being invoked currently.

Type:

Optional[Command]

invoked_with

The command name that triggered this invocation. Useful for finding out which alias called the command.

Type:

Optional[str]

invoked_parents

The command names of the parents that triggered this invocation. Useful for finding out which aliases called the command.

For example in commands ?a b c test, the invoked parents are ['a', 'b', 'c'].

New in version 1.7.

Type:

List[str]

invoked_subcommand

The subcommand that was invoked. If no valid subcommand was invoked then this is equal to None.

Type:

Optional[Command]

subcommand_passed

The string that was attempted to call a subcommand. This does not have to point to a valid registered subcommand and could just point to a nonsense string. If nothing was passed to attempt a call to a subcommand then this is set to None.

Type:

Optional[str]

command_failed

Whether the command failed to be parsed, checked, or invoked.

Type:

bool

async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)[source]

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

You must have Permissions.read_message_history permission to use this.

Examples

Usage

counter = 0
async for message in channel.history(limit=200):
    if message.author == client.user:
        counter += 1

Flattening into a list:

messages = await channel.history(limit=123).flatten()
# messages is now a list of Message...

All parameters are optional.

Parameters:
  • limit (Optional[int]) – The number of messages to retrieve. If None, retrieves every message in the channel. Note, however, that this would make it a slow operation.

  • before (Optional[Union[abc.Snowflake, datetime.datetime]]) – Retrieve messages before this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.

  • after (Optional[Union[abc.Snowflake, datetime.datetime]]) – Retrieve messages after this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.

  • around (Optional[Union[abc.Snowflake, datetime.datetime]]) – Retrieve messages around this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time. When using this argument, the maximum limit is 101. Note that if the limit is an even number then this will return at most limit + 1 messages.

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

Raises:
  • Forbidden – You do not have permissions to get channel message history.

  • HTTPException – The request to get message history failed.

Yields:

Message – The message with the message data parsed.

async with typing()[source]

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

This is useful for denoting long computations in your bot.

Note

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

Example Usage:

async with channel.typing():
    # simulate something heavy
    await asyncio.sleep(10)

await channel.send('done!')
await invoke(command, /, *args, **kwargs)[source]

This function is a coroutine.

Calls a command with the arguments given.

This is useful if you want to just call the callback that a Command holds internally.

Note

This does not handle converters, checks, cooldowns, pre-invoke, or after-invoke hooks in any matter. It calls the internal callback directly as-if it was a regular function.

You must take care in passing the proper arguments when using this function.

Parameters:
  • command (Command) – The command that is going to be called.

  • *args – The arguments to use.

  • **kwargs – The keyword arguments to use.

Raises:

TypeError – The command argument to invoke is missing.

await reinvoke(*, call_hooks=False, restart=True)[source]

This function is a coroutine.

Calls the command again.

This is similar to invoke() except that it bypasses checks, cooldowns, and error handlers.

Note

If you want to bypass UserInputError derived exceptions, it is recommended to use the regular invoke() as it will work more naturally. After all, this will end up using the old arguments the user has used and will thus just fail again.

Parameters:
  • call_hooks (bool) – Whether to call the before and after invoke hooks.

  • restart (bool) – Whether to start the call chain from the very beginning or where we left off (i.e. the command that caused the error). The default is to start where we left off.

Raises:

ValueError – The context to reinvoke is not valid.

property valid[source]

Whether the invocation context is valid to be invoked with.

Type:

bool

property clean_prefix[source]

The cleaned up invoke prefix. i.e. mentions are @name instead of <@id>.

New in version 2.0.

Type:

str

property cog[source]

Returns the cog associated with this context’s command. Returns None if it does not exist.

Type:

Optional[Cog]

guild

Returns the guild associated with this context’s command. Returns None if not available.

Type:

Optional[Guild]

channel

Returns the channel associated with this context’s command. Shorthand for Message.channel.

Type:

Union[abc.Messageable]

author

Union[User, Member]: Returns the author associated with this context’s command. Shorthand for Message.author

me

Union[Member, ClientUser]: Similar to Guild.me except it may return the ClientUser in private message contexts.

property voice_client[source]

A shortcut to Guild.voice_client, if applicable.

Type:

Optional[VoiceProtocol]

await send_help(entity=<bot>)[source]

This function is a coroutine.

Shows the help command for the specified entity if given. The entity can be a command or a cog.

If no entity is given, then it’ll show help for the entire bot.

If the entity is a string, then it looks up whether it’s a Cog or a Command.

Note

Due to the way this function works, instead of returning something similar to command_not_found() this returns None on bad input or no help command.

Parameters:

entity (Optional[Union[Command, Cog, str]]) – The entity to show help for.

Returns:

The result of the help command, if any.

Return type:

Any

await reply(content=None, *, fail_if_not_exists=True, **kwargs)[source]

This function is a coroutine.

A shortcut method to abc.Messageable.send() to reply to the Message.

New in version 1.6.

Changed in version 2.3: Added fail_if_not_exists keyword argument. Defaults to True.

Changed in version 2.6: Raises TypeError or ValueError instead of InvalidArgument.

Parameters:

fail_if_not_exists (bool) –

Whether replying using the message reference should raise HTTPException if the message no longer exists or Discord could not fetch the message.

New in version 2.3.

Raises:
  • HTTPException – Sending the message failed.

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

  • TypeError – You specified both embed and embeds, or file and files, or view and components.

  • ValueError – The files or embeds list is too large.

Returns:

The message that was sent.

Return type:

Message

await fetch_message(id, /)[source]

This function is a coroutine.

Retrieves a single Message from the destination.

Parameters:

id (int) – The message ID to look for.

Raises:
  • NotFound – The specified message was not found.

  • Forbidden – You do not have the permissions required to get a message.

  • HTTPException – Retrieving the message failed.

Returns:

The message asked for.

Return type:

Message

await pins()[source]

This function is a coroutine.

Retrieves all messages that are currently pinned in the channel.

Note

Due to a limitation with the Discord API, the Message objects returned by this method do not contain complete Message.reactions data.

Raises:

HTTPException – Retrieving the pinned messages failed.

Returns:

The messages that are currently pinned.

Return type:

List[Message]

await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, suppress_embeds=False, allowed_mentions=None, reference=None, mention_author=None, view=None, components=None)[source]

This function is a coroutine.

Sends a message to the destination with the content given.

The content must be a type that can convert to a string through str(content).

At least one of content, embed/embeds, file/files, stickers, components, or view must be provided.

To upload a single file, the file parameter should be used with a single File object. To upload multiple files, the files parameter should be used with a list of File objects. Specifying both parameters will lead to an exception.

To upload a single embed, the embed parameter should be used with a single Embed object. To upload multiple embeds, the embeds parameter should be used with a list of Embed objects. Specifying both parameters will lead to an exception.

Changed in version 2.6: Raises TypeError or ValueError instead of InvalidArgument.

Parameters:
  • content (Optional[str]) – The content of the message to send.

  • tts (bool) – Whether the message should be sent using text-to-speech.

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

  • embeds (List[Embed]) –

    A list of embeds to send with the content. Must be a maximum of 10. This cannot be mixed with the embed parameter.

    New in version 2.0.

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

  • files (List[File]) – A list of files to upload. Must be a maximum of 10. This cannot be mixed with the file parameter.

  • stickers (Sequence[Union[GuildSticker, StickerItem]]) –

    A list of stickers to upload. Must be a maximum of 3.

    New in version 2.0.

  • nonce (Union[str, int]) – The nonce to use for sending this message. If the message was successfully sent, then the message will have a nonce with this value.

  • delete_after (float) – If provided, the number of seconds to wait in the background before deleting the message we just sent. If the deletion fails, then it is silently ignored.

  • allowed_mentions (AllowedMentions) –

    Controls the mentions being processed in this message. If this is passed, then the object is merged with Client.allowed_mentions. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set in Client.allowed_mentions. If no object is passed at all then the defaults given by Client.allowed_mentions are used instead.

    New in version 1.4.

  • reference (Union[Message, MessageReference, PartialMessage]) –

    A reference to the Message to which you are replying, this can be created using Message.to_reference() or passed directly as a Message. You can control whether this mentions the author of the referenced message using the AllowedMentions.replied_user attribute of allowed_mentions or by setting mention_author.

    New in version 1.6.

  • mention_author (Optional[bool]) –

    If set, overrides the AllowedMentions.replied_user attribute of allowed_mentions.

    New in version 1.6.

  • view (ui.View) –

    A Discord UI View to add to the message. This cannot be mixed with components.

    New in version 2.0.

  • components (Union[disnake.ui.ActionRow, disnake.ui.WrappedComponent, List[Union[disnake.ui.ActionRow, disnake.ui.WrappedComponent, List[disnake.ui.WrappedComponent]]]]) –

    A list of components to include in the message. This cannot be mixed with view.

    New in version 2.4.

  • suppress_embeds (bool) –

    Whether to suppress embeds for the message. This hides all embeds from the UI if set to True.

    New in version 2.5.

Raises:
Returns:

The message that was sent.

Return type:

Message

await trigger_typing()[source]

This function is a coroutine.

Triggers a typing indicator to the destination.

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

Converters
class disnake.ext.commands.Converter(*args, **kwargs)[source]

The base class of custom converters that require the Context or ApplicationCommandInteraction to be passed to be useful.

This allows you to implement converters that function similar to the special cased disnake classes.

Classes that derive from this should override the convert() method to do its conversion logic. This method must be a coroutine.

await convert(ctx, argument)[source]

This function is a coroutine.

The method to override to do conversion logic.

If an error is found while converting, it is recommended to raise a CommandError derived exception as it will properly propagate to the error handlers.

Parameters:
Raises:
  • CommandError – A generic exception occurred when converting the argument.

  • BadArgument – The converter failed to convert the argument.

class disnake.ext.commands.ObjectConverter(*args, **kwargs)[source]

Converts to a Object.

The argument must follow the valid ID or mention formats (e.g. <@80088516616269824>).

New in version 2.0.

The lookup strategy is as follows (in order):

  1. Lookup by ID.

  2. Lookup by member, role, or channel mention.

await convert(ctx, argument)[source]

This function is a coroutine.

The method to override to do conversion logic.

If an error is found while converting, it is recommended to raise a CommandError derived exception as it will properly propagate to the error handlers.

Parameters:
Raises:
  • CommandError – A generic exception occurred when converting the argument.

  • BadArgument – The converter failed to convert the argument.

class disnake.ext.commands.MemberConverter(*args, **kwargs)[source]

Converts to a Member.

All lookups are via the local guild. If in a DM context, then the lookup is done by the global cache.

The lookup strategy is as follows (in order):

  1. Lookup by ID.

  2. Lookup by mention.

  3. Lookup by name#discrim

  4. Lookup by name

  5. Lookup by nickname

Changed in version 1.5: Raise MemberNotFound instead of generic BadArgument

Changed in version 1.5.1: This converter now lazily fetches members from the gateway and HTTP APIs, optionally caching the result if MemberCacheFlags.joined is enabled.

await convert(ctx, argument)[source]

This function is a coroutine.

The method to override to do conversion logic.

If an error is found while converting, it is recommended to raise a CommandError derived exception as it will properly propagate to the error handlers.

Parameters:
Raises:
  • CommandError – A generic exception occurred when converting the argument.

  • BadArgument – The converter failed to convert the argument.

class disnake.ext.commands.UserConverter(*args, **kwargs)[source]

Converts to a User.

All lookups are via the global user cache.

The lookup strategy is as follows (in order):

  1. Lookup by ID.

  2. Lookup by mention.

  3. Lookup by name#discrim

  4. Lookup by name

Changed in version 1.5: Raise UserNotFound instead of generic BadArgument

Changed in version 1.6: This converter now lazily fetches users from the HTTP APIs if an ID is passed and it’s not available in cache.

await convert(ctx, argument)[source]

This function is a coroutine.

The method to override to do conversion logic.

If an error is found while converting, it is recommended to raise a CommandError derived exception as it will properly propagate to the error handlers.

Parameters:
Raises:
  • CommandError – A generic exception occurred when converting the argument.

  • BadArgument – The converter failed to convert the argument.

class disnake.ext.commands.MessageConverter(*args, **kwargs)[source]

Converts to a Message.

New in version 1.1.

The lookup strategy is as follows (in order):

  1. Lookup by “{channel ID}-{message ID}” (retrieved by shift-clicking on “Copy ID”)

  2. Lookup by message ID (the message must be in the context channel)

  3. Lookup by message URL

Changed in version 1.5: Raise ChannelNotFound, MessageNotFound or ChannelNotReadable instead of generic BadArgument

await convert(ctx, argument)[source]

This function is a coroutine.

The method to override to do conversion logic.

If an error is found while converting, it is recommended to raise a CommandError derived exception as it will properly propagate to the error handlers.

Parameters:
Raises:
  • CommandError – A generic exception occurred when converting the argument.

  • BadArgument – The converter failed to convert the argument.

class disnake.ext.commands.PartialMessageConverter(*args, **kwargs)[source]

Converts to a PartialMessage.

New in version 1.7.

The creation strategy is as follows (in order):

  1. By “{channel ID}-{message ID}” (retrieved by shift-clicking on “Copy ID”)

  2. By message ID (The message is assumed to be in the context channel.)

  3. By message URL

await convert(ctx, argument)[source]

This function is a coroutine.

The method to override to do conversion logic.

If an error is found while converting, it is recommended to raise a CommandError derived exception as it will properly propagate to the error handlers.

Parameters:
Raises:
  • CommandError – A generic exception occurred when converting the argument.

  • BadArgument – The converter failed to convert the argument.

class disnake.ext.commands.GuildChannelConverter(*args, **kwargs)[source]

Converts to a abc.GuildChannel.

All lookups are via the local guild. If in a DM context, then the lookup is done by the global cache.

The lookup strategy is as follows (in order):

  1. Lookup by ID.

  2. Lookup by mention.

  3. Lookup by name.

New in version 2.0.

await convert(ctx, argument)[source]

This function is a coroutine.

The method to override to do conversion logic.

If an error is found while converting, it is recommended to raise a CommandError derived exception as it will properly propagate to the error handlers.

Parameters:
Raises:
  • CommandError – A generic exception occurred when converting the argument.

  • BadArgument – The converter failed to convert the argument.

class disnake.ext.commands.TextChannelConverter(*args, **kwargs)[source]

Converts to a TextChannel.

All lookups are via the local guild. If in a DM context, then the lookup is done by the global cache.

The lookup strategy is as follows (in order):

  1. Lookup by ID.

  2. Lookup by mention.

  3. Lookup by name

Changed in version 1.5: Raise ChannelNotFound instead of generic BadArgument

await convert(ctx, argument)[source]

This function is a coroutine.

The method to override to do conversion logic.

If an error is found while converting, it is recommended to raise a CommandError derived exception as it will properly propagate to the error handlers.

Parameters:
Raises:
  • CommandError – A generic exception occurred when converting the argument.

  • BadArgument – The converter failed to convert the argument.

class disnake.ext.commands.VoiceChannelConverter(*args, **kwargs)[source]

Converts to a VoiceChannel.

All lookups are via the local guild. If in a DM context, then the lookup is done by the global cache.

The lookup strategy is as follows (in order):

  1. Lookup by ID.

  2. Lookup by mention.

  3. Lookup by name

Changed in version 1.5: Raise ChannelNotFound instead of generic BadArgument

await convert(ctx, argument)[source]

This function is a coroutine.

The method to override to do conversion logic.

If an error is found while converting, it is recommended to raise a CommandError derived exception as it will properly propagate to the error handlers.

Parameters:
Raises:
  • CommandError – A generic exception occurred when converting the argument.

  • BadArgument – The converter failed to convert the argument.

class disnake.ext.commands.StageChannelConverter(*args, **kwargs)[source]

Converts to a StageChannel.

New in version 1.7.

All lookups are via the local guild. If in a DM context, then the lookup is done by the global cache.

The lookup strategy is as follows (in order):

  1. Lookup by ID.

  2. Lookup by mention.

  3. Lookup by name

await convert(ctx, argument)[source]

This function is a coroutine.

The method to override to do conversion logic.

If an error is found while converting, it is recommended to raise a CommandError derived exception as it will properly propagate to the error handlers.

Parameters:
Raises:
  • CommandError – A generic exception occurred when converting the argument.

  • BadArgument – The converter failed to convert the argument.

class disnake.ext.commands.CategoryChannelConverter(*args, **kwargs)[source]

Converts to a CategoryChannel.

All lookups are via the local guild. If in a DM context, then the lookup is done by the global cache.

The lookup strategy is as follows (in order):

  1. Lookup by ID.

  2. Lookup by mention.

  3. Lookup by name

Changed in version 1.5: Raise ChannelNotFound instead of generic BadArgument

await convert(ctx, argument)[source]

This function is a coroutine.

The method to override to do conversion logic.

If an error is found while converting, it is recommended to raise a CommandError derived exception as it will properly propagate to the error handlers.

Parameters:
Raises:
  • CommandError – A generic exception occurred when converting the argument.

  • BadArgument – The converter failed to convert the argument.

class disnake.ext.commands.ForumChannelConverter(*args, **kwargs)[source]

Converts to a ForumChannel.

New in version 2.5.

All lookups are via the local guild. If in a DM context, then the lookup is done by the global cache.

The lookup strategy is as follows (in order):

  1. Lookup by ID.

  2. Lookup by mention.

  3. Lookup by name

await convert(ctx, argument)[source]

This function is a coroutine.

The method to override to do conversion logic.

If an error is found while converting, it is recommended to raise a CommandError derived exception as it will properly propagate to the error handlers.

Parameters:
Raises:
  • CommandError – A generic exception occurred when converting the argument.

  • BadArgument – The converter failed to convert the argument.

class disnake.ext.commands.ThreadConverter(*args, **kwargs)[source]

Coverts to a Thread.

All lookups are via the local guild.

The lookup strategy is as follows (in order):

  1. Lookup by ID.

  2. Lookup by mention.

  3. Lookup by name.

New in version 2.0.

await convert(ctx, argument)[source]

This function is a coroutine.

The method to override to do conversion logic.

If an error is found while converting, it is recommended to raise a CommandError derived exception as it will properly propagate to the error handlers.

Parameters:
Raises:
  • CommandError – A generic exception occurred when converting the argument.

  • BadArgument – The converter failed to convert the argument.

class disnake.ext.commands.ColourConverter(*args, **kwargs)[source]

Converts to a Colour.

Changed in version 1.5: Add an alias named ColorConverter

The following formats are accepted:

  • 0x<hex>

  • #<hex>

  • 0x#<hex>

  • rgb(<number>, <number>, <number>)

  • Any of the classmethod in Colour

    • The _ in the name can be optionally replaced with spaces.

Like CSS, <number> can be either 0-255 or 0-100% and <hex> can be either a 6 digit hex number or a 3 digit hex shortcut (e.g. #fff).

Changed in version 1.5: Raise BadColourArgument instead of generic BadArgument

Changed in version 1.7: Added support for rgb function and 3-digit hex shortcuts

await convert(ctx, argument)[source]

This function is a coroutine.

The method to override to do conversion logic.

If an error is found while converting, it is recommended to raise a CommandError derived exception as it will properly propagate to the error handlers.

Parameters:
Raises:
  • CommandError – A generic exception occurred when converting the argument.

  • BadArgument – The converter failed to convert the argument.

class disnake.ext.commands.RoleConverter(*args, **kwargs)[source]

Converts to a Role.

All lookups are via the local guild. If in a DM context, the converter raises NoPrivateMessage exception.

The lookup strategy is as follows (in order):

  1. Lookup by ID.

  2. Lookup by mention.

  3. Lookup by name

Changed in version 1.5: Raise RoleNotFound instead of generic BadArgument

await convert(ctx, argument)[source]

This function is a coroutine.

The method to override to do conversion logic.

If an error is found while converting, it is recommended to raise a CommandError derived exception as it will properly propagate to the error handlers.

Parameters:
Raises:
  • CommandError – A generic exception occurred when converting the argument.

  • BadArgument – The converter failed to convert the argument.

class disnake.ext.commands.GameConverter(*args, **kwargs)[source]

Converts to Game.

await convert(ctx, argument)[source]

This function is a coroutine.

The method to override to do conversion logic.

If an error is found while converting, it is recommended to raise a CommandError derived exception as it will properly propagate to the error handlers.

Parameters:
Raises:
  • CommandError – A generic exception occurred when converting the argument.

  • BadArgument – The converter failed to convert the argument.

class disnake.ext.commands.InviteConverter(*args, **kwargs)[source]

Converts to a Invite.

This is done via an HTTP request using Bot.fetch_invite().

Changed in version 1.5: Raise BadInviteArgument instead of generic BadArgument

await convert(ctx, argument)[source]

This function is a coroutine.

The method to override to do conversion logic.

If an error is found while converting, it is recommended to raise a CommandError derived exception as it will properly propagate to the error handlers.

Parameters:
Raises:
  • CommandError – A generic exception occurred when converting the argument.

  • BadArgument – The converter failed to convert the argument.

class disnake.ext.commands.GuildConverter(*args, **kwargs)[source]

Converts to a Guild.

The lookup strategy is as follows (in order):

  1. Lookup by ID.

  2. Lookup by name. (There is no disambiguation for Guilds with multiple matching names).

New in version 1.7.

await convert(ctx, argument)[source]

This function is a coroutine.

The method to override to do conversion logic.

If an error is found while converting, it is recommended to raise a CommandError derived exception as it will properly propagate to the error handlers.

Parameters:
Raises:
  • CommandError – A generic exception occurred when converting the argument.

  • BadArgument – The converter failed to convert the argument.

class disnake.ext.commands.EmojiConverter(*args, **kwargs)[source]

Converts to a Emoji.

All lookups are done for the local guild first, if available. If that lookup fails, then it checks the client’s global cache.

The lookup strategy is as follows (in order):

  1. Lookup by ID.

  2. Lookup by extracting ID from the emoji.

  3. Lookup by name

Changed in version 1.5: Raise EmojiNotFound instead of generic BadArgument

await convert(ctx, argument)[source]

This function is a coroutine.

The method to override to do conversion logic.

If an error is found while converting, it is recommended to raise a CommandError derived exception as it will properly propagate to the error handlers.

Parameters:
Raises:
  • CommandError – A generic exception occurred when converting the argument.

  • BadArgument – The converter failed to convert the argument.

class disnake.ext.commands.PartialEmojiConverter(*args, **kwargs)[source]

Converts to a PartialEmoji.

This is done by extracting the animated flag, name and ID from the emoji.

Changed in version 1.5: Raise PartialEmojiConversionFailure instead of generic BadArgument

await convert(ctx, argument)[source]

This function is a coroutine.

The method to override to do conversion logic.

If an error is found while converting, it is recommended to raise a CommandError derived exception as it will properly propagate to the error handlers.

Parameters:
Raises:
  • CommandError – A generic exception occurred when converting the argument.

  • BadArgument – The converter failed to convert the argument.

class disnake.ext.commands.GuildStickerConverter(*args, **kwargs)[source]

Converts to a GuildSticker.

All lookups are done for the local guild first, if available. If that lookup fails, then it checks the client’s global cache.

The lookup strategy is as follows (in order):

  1. Lookup by ID

  2. Lookup by name

New in version 2.0.

await convert(ctx, argument)[source]

This function is a coroutine.

The method to override to do conversion logic.

If an error is found while converting, it is recommended to raise a CommandError derived exception as it will properly propagate to the error handlers.

Parameters:
Raises:
  • CommandError – A generic exception occurred when converting the argument.

  • BadArgument – The converter failed to convert the argument.

class disnake.ext.commands.PermissionsConverter(*args, **kwargs)[source]

Converts to a Permissions.

Accepts an integer or a string of space-separated permission names (or just a single one) as input.

New in version 2.3.

await convert(ctx, argument)[source]

This function is a coroutine.

The method to override to do conversion logic.

If an error is found while converting, it is recommended to raise a CommandError derived exception as it will properly propagate to the error handlers.

Parameters:
Raises:
  • CommandError – A generic exception occurred when converting the argument.

  • BadArgument – The converter failed to convert the argument.

class disnake.ext.commands.GuildScheduledEventConverter(*args, **kwargs)[source]

Converts to a GuildScheduledEvent.

The lookup strategy is as follows (in order):

  1. Lookup by ID (in current guild)

  2. Lookup as event URL

  3. Lookup by name (in current guild; there is no disambiguation for scheduled events with multiple matching names)

New in version 2.5.

await convert(ctx, argument)[source]

This function is a coroutine.

The method to override to do conversion logic.

If an error is found while converting, it is recommended to raise a CommandError derived exception as it will properly propagate to the error handlers.

Parameters:
Raises:
  • CommandError – A generic exception occurred when converting the argument.

  • BadArgument – The converter failed to convert the argument.

class disnake.ext.commands.clean_content(*, fix_channel_mentions=False, use_nicknames=True, escape_markdown=False, remove_markdown=False)[source]

Converts the argument to mention scrubbed version of said content.

This behaves similarly to clean_content.

fix_channel_mentions

Whether to clean channel mentions.

Type:

bool

use_nicknames

Whether to use nicknames when transforming mentions.

Type:

bool

escape_markdown

Whether to also escape special markdown characters.

Type:

bool

remove_markdown

Whether to also remove special markdown characters. This option is not supported with escape_markdown

New in version 1.7.

Type:

bool

await convert(ctx, argument)[source]

This function is a coroutine.

The method to override to do conversion logic.

If an error is found while converting, it is recommended to raise a CommandError derived exception as it will properly propagate to the error handlers.

Parameters:
Raises:
  • CommandError – A generic exception occurred when converting the argument.

  • BadArgument – The converter failed to convert the argument.

class disnake.ext.commands.Greedy[source]

A special converter that greedily consumes arguments until it can’t. As a consequence of this behaviour, most input errors are silently discarded, since it is used as an indicator of when to stop parsing.

When a parser error is met the greedy converter stops converting, undoes the internal string parsing routine, and continues parsing regularly.

For example, in the following code:

@commands.command()
async def test(ctx, numbers: Greedy[int], reason: str):
    await ctx.send("numbers: {0}, reason: {1}".format(numbers, reason))

An invocation of [p]test 1 2 3 4 5 6 hello would pass numbers with [1, 2, 3, 4, 5, 6] and reason with hello.

For more information, check Special Converters.

await disnake.ext.commands.run_converters(ctx, converter, argument, param)[source]

This function is a coroutine.

Runs converters for a given converter, argument, and parameter.

This function does the same work that the library does under the hood.

New in version 2.0.

Parameters:
  • ctx (Context) – The invocation context to run the converters under.

  • converter (Any) – The converter to run, this corresponds to the annotation in the function.

  • argument (str) – The argument to convert to.

  • param (inspect.Parameter) – The parameter being converted. This is mainly for error reporting.

Raises:

CommandError – The converter failed to convert.

Returns:

The resulting conversion.

Return type:

Any

Flag Converter
class disnake.ext.commands.FlagConverter[source]

A converter that allows for a user-friendly flag syntax.

The flags are defined using PEP 526 type annotations similar to the dataclasses Python module. For more information on how this converter works, check the appropriate documentation.

iter(x)

Returns an iterator of (flag_name, flag_value) pairs. This allows it to be, for example, constructed as a dict or a list of pairs. Note that aliases are not shown.

New in version 2.0.

Parameters:
  • case_insensitive (bool) – A class parameter to toggle case insensitivity of the flag parsing. If True then flags are parsed in a case insensitive manner. Defaults to False.

  • prefix (str) – The prefix that all flags must be prefixed with. By default there is no prefix.

  • delimiter (str) – The delimiter that separates a flag’s argument from the flag’s name. By default this is :.

classmethod get_flags()[source]

Dict[str, Flag]: A mapping of flag name to flag object this converter has.

classmethod await convert(ctx, argument)[source]

This function is a coroutine.

The method that actually converters an argument to the flag mapping.

Parameters:
  • cls (Type[FlagConverter]) – The flag converter class.

  • ctx (Context) – The invocation context.

  • argument (str) – The argument to convert from.

Raises:
Returns:

The flag converter instance with all flags parsed.

Return type:

FlagConverter

class disnake.ext.commands.Flag[source]

Represents a flag parameter for FlagConverter.

The flag() function helps create these flag objects, but it is not necessary to do so. These cannot be constructed manually.

name

The name of the flag.

Type:

str

aliases

The aliases of the flag name.

Type:

List[str]

attribute

The attribute in the class that corresponds to this flag.

Type:

str

default

The default value of the flag, if available.

Type:

Any

annotation

The underlying evaluated annotation of the flag.

Type:

Any

max_args

The maximum number of arguments the flag can accept. A negative value indicates an unlimited amount of arguments.

Type:

int

override

Whether multiple given values overrides the previous value.

Type:

bool

property required[source]

Whether the flag is required.

A required flag has no default value.

Type:

bool

disnake.ext.commands.flag(*, name=..., aliases=..., default=..., max_args=..., override=...)[source]

Override default functionality and parameters of the underlying FlagConverter class attributes.

Parameters:
  • name (str) – The flag name. If not given, defaults to the attribute name.

  • aliases (List[str]) – Aliases to the flag name. If not given no aliases are set.

  • default (Any) – The default parameter. This could be either a value or a callable that takes Context as its sole parameter. If not given then it defaults to the default value given to the attribute.

  • max_args (int) – The maximum number of arguments the flag can accept. A negative value indicates an unlimited amount of arguments. The default value depends on the annotation given.

  • override (bool) – Whether multiple given values overrides the previous value. The default value depends on the annotation given.

Exceptions
exception disnake.ext.commands.CommandError(message=None, *args)[source]

The base exception type for all command related errors.

This inherits from disnake.DiscordException.

This exception and exceptions inherited from it are handled in a special way as they are caught and passed into a special event from Bot, on_command_error().

exception disnake.ext.commands.ConversionError(converter, original)[source]

Exception raised when a Converter class raises non-CommandError.

This inherits from CommandError.

converter

The converter that failed.

Type:

disnake.ext.commands.Converter

original

The original exception that was raised. You can also get this via the __cause__ attribute.

Type:

Exception

exception disnake.ext.commands.MissingRequiredArgument(param)[source]

Exception raised when parsing a command and a parameter that is required is not encountered.

This inherits from UserInputError

param

The argument that is missing.

Type:

inspect.Parameter

exception disnake.ext.commands.ArgumentParsingError(message=None, *args)[source]

An exception raised when the parser fails to parse a user’s input.

This inherits from UserInputError.

There are child classes that implement more granular parsing errors for i18n purposes.

exception disnake.ext.commands.UnexpectedQuoteError(quote)[source]

An exception raised when the parser encounters a quote mark inside a non-quoted string.

This inherits from ArgumentParsingError.

quote

The quote mark that was found inside the non-quoted string.

Type:

str

exception disnake.ext.commands.InvalidEndOfQuotedStringError(char)[source]

An exception raised when a space is expected after the closing quote in a string but a different character is found.

This inherits from ArgumentParsingError.

char

The character found instead of the expected string.

Type:

str

exception disnake.ext.commands.ExpectedClosingQuoteError(close_quote)[source]

An exception raised when a quote character is expected but not found.

This inherits from ArgumentParsingError.

close_quote

The quote character expected.

Type:

str

exception disnake.ext.commands.BadArgument(message=None, *args)[source]

Exception raised when a parsing or conversion failure is encountered on an argument to pass into a command.

This inherits from UserInputError

exception disnake.ext.commands.BadUnionArgument(param, converters, errors)[source]

Exception raised when a typing.Union converter fails for all its associated types.

This inherits from UserInputError

param

The parameter that failed being converted.

Type:

inspect.Parameter

converters

A tuple of converters attempted in conversion, in order of failure.

Type:

Tuple[Type, ...]

errors

A list of errors that were caught from failing the conversion.

Type:

List[CommandError]

exception disnake.ext.commands.BadLiteralArgument(param, literals, errors)[source]

Exception raised when a typing.Literal converter fails for all its associated values.

This inherits from UserInputError

New in version 2.0.

param

The parameter that failed being converted.

Type:

inspect.Parameter

literals

A tuple of values compared against in conversion, in order of failure.

Type:

Tuple[Any, ...]

errors

A list of errors that were caught from failing the conversion.

Type:

List[CommandError]

exception disnake.ext.commands.PrivateMessageOnly(message=None)[source]

Exception raised when an operation does not work outside of private message contexts.

This inherits from CheckFailure

exception disnake.ext.commands.NoPrivateMessage(message=None)[source]

Exception raised when an operation does not work in private message contexts.

This inherits from CheckFailure

exception disnake.ext.commands.CheckFailure(message=None, *args)[source]

Exception raised when the predicates in Command.checks have failed.

This inherits from CommandError

exception disnake.ext.commands.CheckAnyFailure(checks, errors)[source]

Exception raised when all predicates in check_any() fail.

This inherits from CheckFailure.

New in version 1.3.

errors

A list of errors that were caught during execution.

Type:

List[CheckFailure]

checks

A list of check predicates that failed.

Type:

List[Callable[[Context], bool]]

exception disnake.ext.commands.CommandNotFound(message=None, *args)[source]

Exception raised when a command is attempted to be invoked but no command under that name is found.

This is not raised for invalid subcommands, rather just the initial main command that is attempted to be invoked.

This inherits from CommandError.

exception disnake.ext.commands.DisabledCommand(message=None, *args)[source]

Exception raised when the command being invoked is disabled.

This inherits from CommandError

exception disnake.ext.commands.CommandInvokeError(e)[source]

Exception raised when the command being invoked raised an exception.

This inherits from CommandError

original

The original exception that was raised. You can also get this via the __cause__ attribute.

Type:

Exception

exception disnake.ext.commands.TooManyArguments(message=None, *args)[source]

Exception raised when the command was passed too many arguments and its Command.ignore_extra attribute was not set to True.

This inherits from UserInputError

exception disnake.ext.commands.UserInputError(message=None, *args)[source]

The base exception type for errors that involve errors regarding user input.

This inherits from CommandError.

exception disnake.ext.commands.CommandOnCooldown(cooldown, retry_after, type)[source]

Exception raised when the command being invoked is on cooldown.

This inherits from CommandError

cooldown

A class with attributes rate and per similar to the cooldown() decorator.

Type:

Cooldown

type

The type associated with the cooldown.

Type:

BucketType

retry_after

The amount of seconds to wait before you can retry again.

Type:

float

exception disnake.ext.commands.MaxConcurrencyReached(number, per)[source]

Exception raised when the command being invoked has reached its maximum concurrency.

This inherits from CommandError.

number

The maximum number of concurrent invokers allowed.

Type:

int

per

The bucket type passed to the max_concurrency() decorator.

Type:

BucketType

exception disnake.ext.commands.NotOwner(message=None, *args)[source]

Exception raised when the message author is not the owner of the bot.

This inherits from CheckFailure

exception disnake.ext.commands.ObjectNotFound(argument)[source]

Exception raised when the argument provided did not match the format of an ID or a mention.

This inherits from BadArgument

New in version 2.0.

argument

The argument supplied by the caller that was not matched

Type:

str

exception disnake.ext.commands.MessageNotFound(argument)[source]

Exception raised when the message provided was not found in the channel.

This inherits from BadArgument

New in version 1.5.

argument

The message supplied by the caller that was not found

Type:

str

exception disnake.ext.commands.MemberNotFound(argument)[source]

Exception raised when the member provided was not found in the bot’s cache.

This inherits from BadArgument

New in version 1.5.

argument

The member supplied by the caller that was not found

Type:

str

exception disnake.ext.commands.GuildNotFound(argument)[source]

Exception raised when the guild provided was not found in the bot’s cache.

This inherits from BadArgument

New in version 1.7.

argument

The guild supplied by the called that was not found

Type:

str

exception disnake.ext.commands.UserNotFound(argument)[source]

Exception raised when the user provided was not found in the bot’s cache.

This inherits from BadArgument

New in version 1.5.

argument

The user supplied by the caller that was not found

Type:

str

exception disnake.ext.commands.ChannelNotFound(argument)[source]

Exception raised when the bot can not find the channel.

This inherits from BadArgument

New in version 1.5.

argument

The channel supplied by the caller that was not found

Type:

str

exception disnake.ext.commands.ChannelNotReadable(argument)[source]

Exception raised when the bot does not have permission to read messages in the channel.

This inherits from BadArgument

New in version 1.5.

argument

The channel supplied by the caller that was not readable

Type:

Union[abc.GuildChannel, Thread]

exception disnake.ext.commands.ThreadNotFound(argument)[source]

Exception raised when the bot can not find the thread.

This inherits from BadArgument

New in version 2.0.

argument

The thread supplied by the caller that was not found

Type:

str

exception disnake.ext.commands.BadColourArgument(argument)[source]

Exception raised when the colour is not valid.

This inherits from BadArgument

New in version 1.5.

argument

The colour supplied by the caller that was not valid

Type:

str

exception disnake.ext.commands.RoleNotFound(argument)[source]

Exception raised when the bot can not find the role.

This inherits from BadArgument

New in version 1.5.

argument

The role supplied by the caller that was not found

Type:

str

exception disnake.ext.commands.BadInviteArgument(argument)[source]

Exception raised when the invite is invalid or expired.

This inherits from BadArgument

New in version 1.5.

exception disnake.ext.commands.EmojiNotFound(argument)[source]

Exception raised when the bot can not find the emoji.

This inherits from BadArgument

New in version 1.5.

argument

The emoji supplied by the caller that was not found

Type:

str

exception disnake.ext.commands.PartialEmojiConversionFailure(argument)[source]

Exception raised when the emoji provided does not match the correct format.

This inherits from BadArgument

New in version 1.5.

argument

The emoji supplied by the caller that did not match the regex

Type:

str

exception disnake.ext.commands.GuildStickerNotFound(argument)[source]

Exception raised when the bot can not find the sticker.

This inherits from BadArgument

New in version 2.0.

argument

The sticker supplied by the caller that was not found

Type:

str

exception disnake.ext.commands.GuildScheduledEventNotFound(argument)[source]

Exception raised when the bot cannot find the scheduled event.

This inherits from BadArgument

New in version 2.5.

argument

The scheduled event ID/URL/name supplied by the caller that was not found.

Type:

str

exception disnake.ext.commands.BadBoolArgument(argument)[source]

Exception raised when a boolean argument was not convertable.

This inherits from BadArgument

New in version 1.5.

argument

The boolean argument supplied by the caller that is not in the predefined list

Type:

str

exception disnake.ext.commands.LargeIntConversionFailure(argument)[source]

Exception raised when a large integer argument was not able to be converted.

This inherits from BadArgument

New in version 2.5.

argument

The argument that could not be converted to an integer.

Type:

str

exception disnake.ext.commands.MissingPermissions(missing_permissions, *args)[source]

Exception raised when the command invoker lacks permissions to run a command.

This inherits from CheckFailure

missing_permissions

The required permissions that are missing.

Type:

List[str]

exception disnake.ext.commands.BotMissingPermissions(missing_permissions, *args)[source]

Exception raised when the bot’s member lacks permissions to run a command.

This inherits from CheckFailure

missing_permissions

The required permissions that are missing.

Type:

List[str]

exception disnake.ext.commands.MissingRole(missing_role)[source]

Exception raised when the command invoker lacks a role to run a command.

This inherits from CheckFailure

New in version 1.1.

missing_role

The required role that is missing. This is the parameter passed to has_role().

Type:

Union[str, int]

exception disnake.ext.commands.BotMissingRole(missing_role)[source]

Exception raised when the bot’s member lacks a role to run a command.

This inherits from CheckFailure

New in version 1.1.

missing_role

The required role that is missing. This is the parameter passed to has_role().

Type:

Union[str, int]

exception disnake.ext.commands.MissingAnyRole(missing_roles)[source]

Exception raised when the command invoker lacks any of the roles specified to run a command.

This inherits from CheckFailure

New in version 1.1.

missing_roles

The roles that the invoker is missing. These are the parameters passed to has_any_role().

Type:

List[Union[str, int]]

exception disnake.ext.commands.BotMissingAnyRole(missing_roles)[source]

Exception raised when the bot’s member lacks any of the roles specified to run a command.

This inherits from CheckFailure

New in version 1.1.

missing_roles

The roles that the bot’s member is missing. These are the parameters passed to has_any_role().

Type:

List[Union[str, int]]

exception disnake.ext.commands.NSFWChannelRequired(channel)[source]

Exception raised when a channel does not have the required NSFW setting.

This inherits from CheckFailure.

New in version 1.1.

Parameters:

channel (Union[abc.GuildChannel, Thread]) – The channel that does not have NSFW enabled.

exception disnake.ext.commands.FlagError(message=None, *args)[source]

The base exception type for all flag parsing related errors.

This inherits from BadArgument.

New in version 2.0.

exception disnake.ext.commands.BadFlagArgument(flag)[source]

An exception raised when a flag failed to convert a value.

This inherits from FlagError

New in version 2.0.

flag

The flag that failed to convert.

Type:

Flag

exception disnake.ext.commands.MissingFlagArgument(flag)[source]

An exception raised when a flag did not get a value.

This inherits from FlagError

New in version 2.0.

flag

The flag that did not get a value.

Type:

Flag

exception disnake.ext.commands.TooManyFlags(flag, values)[source]

An exception raised when a flag has received too many values.

This inherits from FlagError.

New in version 2.0.

flag

The flag that received too many values.

Type:

Flag

values

The values that were passed.

Type:

List[str]

exception disnake.ext.commands.MissingRequiredFlag(flag)[source]

An exception raised when a required flag was not given.

This inherits from FlagError

New in version 2.0.

flag

The required flag that was not found.

Type:

Flag

exception disnake.ext.commands.ExtensionError(message=None, *args, name)[source]

Base exception for extension related errors.

This inherits from DiscordException.

name

The extension that had an error.

Type:

str

exception disnake.ext.commands.ExtensionAlreadyLoaded(name)[source]

An exception raised when an extension has already been loaded.

This inherits from ExtensionError

exception disnake.ext.commands.ExtensionNotLoaded(name)[source]

An exception raised when an extension was not loaded.

This inherits from ExtensionError

exception disnake.ext.commands.NoEntryPointError(name)[source]

An exception raised when an extension does not have a setup entry point function.

This inherits from ExtensionError

exception disnake.ext.commands.ExtensionFailed(name, original)[source]

An exception raised when an extension failed to load during execution of the module or setup entry point.

This inherits from ExtensionError

name

The extension that had the error.

Type:

str

original

The original exception that was raised. You can also get this via the __cause__ attribute.

Type:

Exception

exception disnake.ext.commands.ExtensionNotFound(name)[source]

An exception raised when an extension is not found.

This inherits from ExtensionError

Changed in version 1.3: Made the original attribute always None.

name

The extension that had the error.

Type:

str

exception disnake.ext.commands.CommandRegistrationError(name, *, alias_conflict=False)[source]

An exception raised when the command can’t be added because the name is already taken by a different command.

This inherits from disnake.ClientException

New in version 1.4.

name

The command name that had the error.

Type:

str

alias_conflict

Whether the name that conflicts is an alias of the command we try to add.

Type:

bool

Exception Hierarchy
Warnings
class disnake.ext.commands.MessageContentPrefixWarning[source]

Warning for invalid prefixes without message content.

Warning Hierarchy

Additional info

This section contains explanations of some library mechanics which may be useful to know.

App command sync

If you’re using disnake.ext.commands – Bot commands framework for application commands (slash commands, context menus) you should understand how your commands show up in Discord. If sync_commands kwarg of Bot (or a similar class) is set to True (which is the default value) the library registers / updates all commands automatically. Based on the application commands defined in your code it decides which commands should be registered, edited or deleted but there’re some edge cases you should keep in mind.

Changing test guilds

If you remove some IDs from the test_guilds kwarg of Bot (or a similar class) or from the guild_ids kwarg of slash_command (user_command, message_command) the commands in those guilds won’t be deleted instantly. Instead, they’ll be deleted as soon as one of the deprecated commands is invoked. Your bot will send a message like “This command has just been synced …”.

Hosting the bot on multiple machines

If your bot requires shard distribution across several machines, you should set sync_commands kwarg to False everywhere except 1 machine. This will prevent conflicts and race conditions. Discord API doesn’t provide users with events related to application command updates, so it’s impossible to keep the cache of multiple machines synced. Having only 1 machine with sync_commands set to True is enough because global registration of application commands doesn’t depend on sharding.

disnake.ext.tasks – asyncio.Task helpers

New in version 1.1.0.

One of the most common operations when making a bot is having a loop run in the background at a specified interval. This pattern is very common but has a lot of things you need to look out for:

  • How do I handle asyncio.CancelledError?

  • What do I do if the internet goes out?

  • What is the maximum number of seconds I can sleep anyway?

The goal of this disnake extension is to abstract all these worries away from you.

Recipes

A simple background task in a Cog:

from disnake.ext import tasks, commands

class MyCog(commands.Cog):
    def __init__(self):
        self.index = 0
        self.printer.start()

    def cog_unload(self):
        self.printer.cancel()

    @tasks.loop(seconds=5.0)
    async def printer(self):
        print(self.index)
        self.index += 1

Adding an exception to handle during reconnect:

import asyncpg
from disnake.ext import tasks, commands

class MyCog(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self.data = []
        self.batch_update.add_exception_type(asyncpg.PostgresConnectionError)
        self.batch_update.start()

    def cog_unload(self):
        self.batch_update.cancel()

    @tasks.loop(minutes=5.0)
    async def batch_update(self):
        async with self.bot.pool.acquire() as con:
            # batch update here...
            pass

Looping a certain amount of times before exiting:

from disnake.ext import tasks

@tasks.loop(seconds=5.0, count=5)
async def slow_count():
    print(slow_count.current_loop)

@slow_count.after_loop
async def after_slow_count():
    print('done!')

slow_count.start()

Waiting until the bot is ready before the loop starts:

from disnake.ext import tasks, commands

class MyCog(commands.Cog):
    def __init__(self, bot):
        self.index = 0
        self.bot = bot
        self.printer.start()

    def cog_unload(self):
        self.printer.cancel()

    @tasks.loop(seconds=5.0)
    async def printer(self):
        print(self.index)
        self.index += 1

    @printer.before_loop
    async def before_printer(self):
        print('waiting...')
        await self.bot.wait_until_ready()

Doing something during cancellation:

from disnake.ext import tasks, commands
import asyncio

class MyCog(commands.Cog):
    def __init__(self, bot):
        self.bot= bot
        self._batch = []
        self.lock = asyncio.Lock()
        self.bulker.start()

    async def do_bulk(self):
        # bulk insert data here
        ...

    @tasks.loop(seconds=10.0)
    async def bulker(self):
        async with self.lock:
            await self.do_bulk()

    @bulker.after_loop
    async def on_bulker_cancel(self):
        if self.bulker.is_being_cancelled() and len(self._batch) != 0:
            # if we're cancelled and we have some data left...
            # let's insert it to our database
            await self.do_bulk()

API Reference

class disnake.ext.tasks.Loop[source]

A background task helper that abstracts the loop and reconnection logic for you.

The main interface to create this is through loop().

@after_loop[source]

A decorator that register a coroutine to be called after the loop finished running.

The coroutine must take no arguments (except self in a class context).

Note

This coroutine is called even during cancellation. If it is desirable to tell apart whether something was cancelled or not, check to see whether is_being_cancelled() is True or not.

Parameters:

coro (coroutine) – The coroutine to register after the loop finishes.

Raises:

TypeError – The function was not a coroutine.

@before_loop[source]

A decorator that registers a coroutine to be called before the loop starts running.

This is useful if you want to wait for some bot state before the loop starts, such as disnake.Client.wait_until_ready().

The coroutine must take no arguments (except self in a class context).

Parameters:

coro (coroutine) – The coroutine to register before the loop runs.

Raises:

TypeError – The function was not a coroutine.

@error[source]

A decorator that registers a coroutine to be called if the task encounters an unhandled exception.

The coroutine must take only one argument the exception raised (except self in a class context).

By default this prints to sys.stderr however it could be overridden to have a different implementation.

New in version 1.4.

Parameters:

coro (coroutine) – The coroutine to register in the event of an unhandled exception.

Raises:

TypeError – The function was not a coroutine.

property seconds[source]

Read-only value for the number of seconds between each iteration. None if an explicit time value was passed instead.

New in version 2.0.

Type:

Optional[float]

property minutes[source]

Read-only value for the number of minutes between each iteration. None if an explicit time value was passed instead.

New in version 2.0.

Type:

Optional[float]

property hours[source]

Read-only value for the number of hours between each iteration. None if an explicit time value was passed instead.

New in version 2.0.

Type:

Optional[float]

property time[source]

Read-only list for the exact times this loop runs at. None if relative times were passed instead.

New in version 2.0.

Type:

Optional[List[datetime.time]]

property current_loop[source]

The current iteration of the loop.

Type:

int

property next_iteration[source]

When the next iteration of the loop will occur.

New in version 1.3.

Type:

Optional[datetime.datetime]

await __call__(*args, **kwargs)[source]

This function is a coroutine.

Calls the internal callback that the task holds.

New in version 1.6.

Parameters:
  • *args – The arguments to use.

  • **kwargs – The keyword arguments to use.

start(*args, **kwargs)[source]

Starts the internal task in the event loop.

Parameters:
  • *args – The arguments to use.

  • **kwargs – The keyword arguments to use.

Raises:

RuntimeError – A task has already been launched and is running.

Returns:

The task that has been created.

Return type:

asyncio.Task

stop()[source]

Gracefully stops the task from running.

Unlike cancel(), this allows the task to finish its current iteration before gracefully exiting.

Note

If the internal function raises an error that can be handled before finishing then it will retry until it succeeds.

If this is undesirable, either remove the error handling before stopping via clear_exception_types() or use cancel() instead.

New in version 1.2.

cancel()[source]

Cancels the internal task, if it is running.

restart(*args, **kwargs)[source]

A convenience method to restart the internal task.

Note

Due to the way this function works, the task is not returned like start().

Parameters:
  • *args – The arguments to use.

  • **kwargs – The keyword arguments to use.

add_exception_type(*exceptions)[source]

Adds exception types to be handled during the reconnect logic.

By default the exception types handled are those handled by disnake.Client.connect(), which includes a lot of internet disconnection errors.

This function is useful if you’re interacting with a 3rd party library that raises its own set of exceptions.

Parameters:

*exceptions (Type[BaseException]) – An argument list of exception classes to handle.

Raises:

TypeError – An exception passed is either not a class or not inherited from BaseException.

clear_exception_types()[source]

Removes all exception types that are handled.

Note

This operation obviously cannot be undone!

remove_exception_type(*exceptions)[source]

Removes exception types from being handled during the reconnect logic.

Parameters:

*exceptions (Type[BaseException]) – An argument list of exception classes to handle.

Returns:

Whether all exceptions were successfully removed.

Return type:

bool

get_task()[source]

Fetches the internal task or None if there isn’t one running.

Return type:

Optional[asyncio.Task]

is_being_cancelled()[source]

Whether the task is being cancelled.

Return type:

bool

failed()[source]

Whether the internal task has failed.

New in version 1.2.

Return type:

bool

is_running()[source]

Check if the task is currently running.

New in version 1.4.

Return type:

bool

change_interval(*, seconds=0, minutes=0, hours=0, time=...)[source]

Changes the interval for the sleep time.

New in version 1.2.

Parameters:
  • seconds (float) – The number of seconds between every iteration.

  • minutes (float) – The number of minutes between every iteration.

  • hours (float) – The number of hours between every iteration.

  • time (Union[datetime.time, Sequence[datetime.time]]) –

    The exact times to run this loop at. Either a non-empty list or a single value of datetime.time should be passed. This cannot be used in conjunction with the relative time parameters.

    New in version 2.0.

    Note

    Duplicate times will be ignored, and only run once.

Raises:
  • ValueError – An invalid value was given.

  • TypeError – An invalid value for the time parameter was passed, or the time parameter was passed in conjunction with relative time parameters.

disnake.ext.tasks.loop(cls=disnake.ext.tasks.Loop[~LF], **kwargs)[source]

A decorator that schedules a task in the background for you with optional reconnect logic. The decorator returns a Loop.

Parameters:
  • cls (Type[Loop]) –

    The loop subclass to create an instance of. If provided, the following parameters described below do not apply. Instead, this decorator will accept the same keywords as the passed cls does.

    New in version 2.6.

  • seconds (float) – The number of seconds between every iteration.

  • minutes (float) – The number of minutes between every iteration.

  • hours (float) – The number of hours between every iteration.

  • time (Union[datetime.time, Sequence[datetime.time]]) –

    The exact times to run this loop at. Either a non-empty list or a single value of datetime.time should be passed. Timezones are supported. If no timezone is given for the times, it is assumed to represent UTC time.

    This cannot be used in conjunction with the relative time parameters.

    Note

    Duplicate times will be ignored, and only run once.

    New in version 2.0.

  • count (Optional[int]) – The number of loops to do, None if it should be an infinite loop.

  • reconnect (bool) – Whether to handle errors and restart the task using an exponential back-off algorithm similar to the one used in disnake.Client.connect().

  • loop (asyncio.AbstractEventLoop) – The loop to use to register the task, if not given defaults to asyncio.get_event_loop().

Raises:
  • ValueError – An invalid value was given.

  • TypeError – The function was not a coroutine, the cls parameter was not a subclass of Loop, an invalid value for the time parameter was passed, or time parameter was passed in conjunction with relative time parameters.

Manuals

These pages go into great detail about everything the API can do.

API Reference

The following section outlines the API of disnake.

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

Clients

Client
class disnake.Client(*, asyncio_debug=False, loop=None, shard_id=None, shard_count=None, enable_debug_events=False, enable_gateway_error_handler=True, localization_provider=None, strict_localization=False, gateway_params=None, connector=None, proxy=None, proxy_auth=None, assume_unsync_clock=True, max_messages=1000, application_id=None, heartbeat_timeout=60.0, guild_ready_timeout=2.0, allowed_mentions=None, activity=None, status=None, intents=None, chunk_guilds_at_startup=None, member_cache_flags=None)[source]

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 (int) – The client’s application ID.

  • intents (Optional[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[Union[class:str, 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.

  • enable_gateway_error_handler (bool) –

    Whether to enable the disnake.on_gateway_error() event. Defaults to True.

    If this is disabled, exceptions that occur while parsing (known) gateway events won’t be handled and the pre-v2.6 behavior of letting the exception propagate up to the connect()/start()/run() call is used instead.

    New in version 2.6.

  • test_guilds (List[int]) –

    The list of IDs of the guilds where you’re going to test your application commands. Defaults to None, which means global registration of commands across all guilds.

    New in version 2.1.

  • sync_commands (bool) –

    Whether to enable automatic synchronization of application commands in your code. Defaults to True, which means that commands in API are automatically synced with the commands specified in your code.

    New in version 2.1.

  • sync_commands_debug (bool) –

    Whether to always show sync debug logs (uses INFO log level if it’s enabled, prints otherwise). If disabled, uses the default DEBUG log level which isn’t shown unless the log level is changed manually. Useful for tracking the commands being registered in the API.

    New in version 2.1.

    Changed in version 2.4: Changes the log level of corresponding messages from DEBUG to INFO or prints them, instead of controlling whether they are enabled at all.

  • localization_provider (LocalizationProtocol) –

    An implementation of LocalizationProtocol to use for localization of application commands. If not provided, the default LocalizationStore implementation is used.

    New in version 2.5.

    Changed in version 2.6: Can no longer be provided together with strict_localization, as it does not apply to the custom localization provider entered in this parameter.

  • strict_localization (bool) –

    Whether to raise an exception when localizations for a specific key couldn’t be found. This is mainly useful for testing/debugging, consider disabling this eventually as missing localized names will automatically fall back to the default/base name without it. Only applicable if the localization_provider parameter is not provided. Defaults to False.

    New in version 2.5.

    Changed in version 2.6: Can no longer be provided together with localization_provider, as this parameter is ignored for custom localization providers.

  • gateway_params (GatewayParams) –

    Allows configuring parameters used for establishing gateway connections, notably enabling/disabling compression (enabled by default). Encodings other than JSON are not supported.

    New in version 2.6.

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

asyncio_debug

Whether to enable asyncio debugging when the client starts. Defaults to False.

Type:

bool

session_start_limit

Information about the current session start limit. Only available after initiating the connection.

New in version 2.5.

Type:

Optional[SessionStartLimit]

i18n

An implementation of LocalizationProtocol used for localization of application commands.

New in version 2.5.

Type:

LocalizationProtocol

@event[source]

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.

async for ... in fetch_guilds(*, limit=100, before=None, after=None)[source]

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

  • 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 – Retrieving the guilds failed.

Yields:

Guild – The guild with the guild data parsed.

property latency[source]

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()[source]

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.

Return type:

bool

property user[source]

Represents the connected client. None if not logged in.

Type:

Optional[ClientUser]

property guilds[source]

The guilds that the connected client is a member of.

Type:

List[Guild]

property emojis[source]

The emojis that the connected client has.

Type:

List[Emoji]

property stickers[source]

The stickers that the connected client has.

New in version 2.0.

Type:

List[GuildSticker]

property cached_messages[source]

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

New in version 1.1.

Type:

Sequence[Message]

property private_channels[source]

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[source]

Represents a list of voice connections.

These are usually VoiceClient instances.

Type:

List[VoiceProtocol]

property application_id[source]

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[source]

The client’s application flags.

New in version 2.0.

Type:

ApplicationFlags

property global_application_commands[source]

The client’s global application commands.

Type:

List[Union[APIUserCommand, APIMessageCommand, APISlashCommand]

property global_slash_commands[source]

The client’s global slash commands.

Type:

List[APISlashCommand]

property global_user_commands[source]

The client’s global user commands.

Type:

List[APIUserCommand]

property global_message_commands[source]

The client’s global message commands.

Type:

List[APIMessageCommand]

get_message(id)[source]

Gets the message with the given ID from the bot’s message cache.

Parameters:

id (int) – The ID of the message to look for.

Returns:

The corresponding message.

Return type:

Optional[Message]

await get_or_fetch_user(user_id, *, strict=False)[source]

This function is a coroutine.

Tries to get the user from the cache. If fails, it tries to fetch the user from the API.

Parameters:
  • user_id (int) – The ID to search for.

  • strict (bool) – Whether to propagate exceptions from fetch_user() instead of returning None in case of failure (e.g. if the user wasn’t found). Defaults to False.

Returns:

The user with the given ID, or None if not found and strict is set to False.

Return type:

Optional[User]

await getch_user(user_id, *, strict=False)[source]

This function is a coroutine.

Tries to get the user from the cache. If fails, it tries to fetch the user from the API.

Parameters:
  • user_id (int) – The ID to search for.

  • strict (bool) – Whether to propagate exceptions from fetch_user() instead of returning None in case of failure (e.g. if the user wasn’t found). Defaults to False.

Returns:

The user with the given ID, or None if not found and strict is set to False.

Return type:

Optional[User]

is_ready()[source]

Whether the client’s internal cache is ready for use.

Return type:

bool

await on_error(event_method, *args, **kwargs)[source]

This function is a coroutine.

The default error handler provided by the client.

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

await on_gateway_error(event, data, shard_id, exc, /)[source]

This function is a coroutine.

The default gateway error handler provided by the client.

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

New in version 2.6.

Note

Unlike on_error(), the exception is available as the exc parameter and cannot be obtained through sys.exc_info().

await before_identify_hook(shard_id, *, initial=False)[source]

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)[source]

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, ignore_session_start_limit=False)[source]

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.

Changed in version 2.6: Added usage of SessionStartLimit when connecting to the API. Added the ignore_session_start_limit parameter.

Parameters:
  • reconnect (bool) – Whether reconnecting should be attempted, 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).

  • ignore_session_start_limit (bool) –

    Whether the API provided session start limit should be ignored when connecting to the API.

    New in version 2.6.

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.

  • SessionStartLimitReached – If the client doesn’t have enough connects remaining in the current 24-hour window and ignore_session_start_limit is False this will be raised rather than connecting to the gateawy and Discord resetting the token. However, if ignore_session_start_limit is True, the client will connect regardless and this exception will not be raised.

await close()[source]

This function is a coroutine.

Closes the connection to Discord.

clear()[source]

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, ignore_session_start_limit=False)[source]

This function is a coroutine.

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

Raises:

TypeError – An unexpected keyword argument was received.

run(*args, **kwargs)[source]

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()[source]

Whether the websocket connection is closed.

Return type:

bool

property activity[source]

The activity being used upon logging in.

Type:

Optional[BaseActivity]

property status[source]

The status being used upon logging on to Discord.

New in version 2.0.

Type:

Status

property allowed_mentions[source]

The allowed mention configuration.

New in version 1.4.

Type:

Optional[AllowedMentions]

property intents[source]

The intents configured for this connection.

New in version 1.5.

Type:

Intents

property users[source]

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

Type:

List[User]

get_channel(id, /)[source]

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)[source]

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, /)[source]

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 or None if not found.

Return type:

Optional[StageInstance]

get_guild(id, /)[source]

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, /)[source]

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, /)[source]

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, /)[source]

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]

for ... in get_all_channels()[source]

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()[source]

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.

get_guild_application_commands(guild_id)[source]

Returns a list of all application commands in the guild with the given ID.

Parameters:

guild_id (int) – The ID to search for.

Returns:

The list of application commands.

Return type:

List[Union[APIUserCommand, APIMessageCommand, APISlashCommand]]

get_guild_slash_commands(guild_id)[source]

Returns a list of all slash commands in the guild with the given ID.

Parameters:

guild_id (int) – The ID to search for.

Returns:

The list of slash commands.

Return type:

List[APISlashCommand]

get_guild_user_commands(guild_id)[source]

Returns a list of all user commands in the guild with the given ID.

Parameters:

guild_id (int) – The ID to search for.

Returns:

The list of user commands.

Return type:

List[APIUserCommand]

get_guild_message_commands(guild_id)[source]

Returns a list of all message commands in the guild with the given ID.

Parameters:

guild_id (int) – The ID to search for.

Returns:

The list of message commands.

Return type:

List[APIMessageCommand]

get_global_command(id)[source]

Returns a global application command with the given ID.

Parameters:

id (int) – The ID to search for.

Returns:

The application command.

Return type:

Optional[Union[APIUserCommand, APIMessageCommand, APISlashCommand]]

get_guild_command(guild_id, id)[source]

Returns a guild application command with the given guild ID and application command ID.

Parameters:
  • guild_id (int) – The guild ID to search for.

  • id (int) – The command ID to search for.

Returns:

The application command.

Return type:

Optional[Union[APIUserCommand, APIMessageCommand, APISlashCommand]]

get_global_command_named(name, cmd_type=None)[source]

Returns a global application command matching the given name.

Parameters:
  • name (str) – The name to look for.

  • cmd_type (ApplicationCommandType) – The type to look for. By default, no types are checked.

Returns:

The application command.

Return type:

Optional[Union[APIUserCommand, APIMessageCommand, APISlashCommand]]

get_guild_command_named(guild_id, name, cmd_type=None)[source]

Returns a guild application command matching the given name.

Parameters:
  • guild_id (int) – The guild ID to search for.

  • name (str) – The command name to search for.

  • cmd_type (ApplicationCommandType) – The type to look for. By default, no types are checked.

Returns:

The application command.

Return type:

Optional[Union[APIUserCommand, APIMessageCommand, APISlashCommand]]

await wait_until_ready()[source]

This function is a coroutine.

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

await wait_until_first_connect()[source]

This function is a coroutine.

Waits until the first connect.

wait_for(event, *, check=None, timeout=None)[source]

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)[source]

This function is a coroutine.

Changes the client’s presence.

Changed in version 2.6: Raises TypeError instead of InvalidArgument.

Example

game = disnake.Game("with the API")
await client.change_presence(status=disnake.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:

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

await fetch_template(code)[source]

This function is a coroutine.

Retrieves 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:
Returns:

The template from the URL/code.

Return type:

Template

await fetch_guild(guild_id, /)[source]

This function is a coroutine.

Retrieves a Guild from the given ID.

Note

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

Note

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

Parameters:

guild_id (int) – The ID of the guild to retrieve.

Raises:
Returns:

The guild from the given ID.

Return type:

Guild

await fetch_guild_preview(guild_id, /)[source]

This function is a coroutine.

Retrieves a GuildPreview from the given ID. Your bot does not have to be in this guild.

Note

This method may fetch any guild that has DISCOVERABLE in Guild.features, but this information can not be known ahead of time.

This will work for any guild that you are in.

Parameters:

guild_id (int) – The ID of the guild to to retrieve a preview object.

Raises:

NotFound – Retrieving the guild preview failed.

Returns:

The guild preview from the given ID.

Return type:

GuildPreview

await create_guild(*, name, icon=..., code=...)[source]

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.5: Removed the region parameter.

Changed in version 2.6: Raises ValueError instead of InvalidArgument.

Parameters:
Raises:
Returns:

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

Return type:

Guild

await fetch_stage_instance(channel_id, /)[source]

This function is a coroutine.

Retrieves a StageInstance with the given ID.

Note

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

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 – Retrieving the stage instance failed.

Returns:

The stage instance from the given ID.

Return type:

StageInstance

await fetch_invite(url, *, with_counts=True, with_expiration=True, guild_scheduled_event_id=None)[source]

This function is a coroutine.

Retrieves 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:
  • url (Union[Invite, str]) – The Discord invite ID or URL (must be a discord.gg URL).

  • with_counts (bool) – Whether to include count information in the invite. This fills the Invite.approximate_member_count and Invite.approximate_presence_count fields.

  • with_expiration (bool) –

    Whether to include the expiration date of the invite. This fills the Invite.expires_at field.

    New in version 2.0.

  • guild_scheduled_event_id (int) –

    The ID of the scheduled event to include in the invite. If not provided, defaults to the event parameter in the URL if it exists, or the ID of the scheduled event contained in the provided invite object.

    New in version 2.3.

Raises:
Returns:

The invite from the URL/ID.

Return type:

Invite

await delete_invite(invite)[source]

This function is a coroutine.

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

You must have 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_voice_regions(guild_id=None)[source]

Retrieves a list of VoiceRegions.

Retrieves voice regions for the user, or a guild if provided.

New in version 2.5.

Parameters:

guild_id (Optional[int]) – The guild to get regions for, if provided.

Raises:
  • HTTPException – Retrieving voice regions failed.

  • NotFound – The provided guild_id could not be found.

await fetch_widget(guild_id, /)[source]

This function is a coroutine.

Retrieves a Widget for the given guild ID.

Note

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

Parameters:

guild_id (int) – The ID of the guild.

Raises:
Returns:

The guild’s widget.

Return type:

Widget

await application_info()[source]

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, /)[source]

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 disnake.Intents.members and member cache enabled, consider get_user() instead.

Parameters:

user_id (int) – The ID of the user to retrieve.

Raises:
Returns:

The user you requested.

Return type:

User

await fetch_channel(channel_id, /)[source]

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.

Parameters:

channel_id (int) – The ID of the channel to retrieve.

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, /)[source]

This function is a coroutine.

Retrieves a Webhook with the given ID.

Parameters:

webhook_id (int) – The ID of the webhook to retrieve.

Raises:
Returns:

The webhook you requested.

Return type:

Webhook

await fetch_sticker(sticker_id, /)[source]

This function is a coroutine.

Retrieves a Sticker with the given ID.

New in version 2.0.

Parameters:

sticker_id (int) – The ID of the sticker to retrieve.

Raises:
Returns:

The sticker you requested.

Return type:

Union[StandardSticker, GuildSticker]

await fetch_premium_sticker_packs()[source]

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)[source]

This function is a coroutine.

Creates a DMChannel with the given 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)[source]

Registers a View for persistent listening.

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.

Parameters:
  • view (disnake.ui.View) – The view to register for dispatching.

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

Raises:
  • TypeError – A view was not passed.

  • ValueError – The view is not persistent. A persistent view has no timeout and all their components have an explicitly provided custom_id.

property persistent_views[source]

A sequence of persistent views added to the client.

New in version 2.0.

Type:

Sequence[View]

await fetch_global_commands(*, with_localizations=True)[source]

This function is a coroutine.

Retrieves a list of global application commands.

New in version 2.1.

Parameters:

with_localizations (bool) –

Whether to include localizations in the response. Defaults to True.

New in version 2.5.

Returns:

A list of application commands.

Return type:

List[Union[APIUserCommand, APIMessageCommand, APISlashCommand]]

await fetch_global_command(command_id)[source]

This function is a coroutine.

Retrieves a global application command.

New in version 2.1.

Parameters:

command_id (int) – The ID of the command to retrieve.

Returns:

The requested application command.

Return type:

Union[APIUserCommand, APIMessageCommand, APISlashCommand]

await create_global_command(application_command)[source]

This function is a coroutine.

Creates a global application command.

New in version 2.1.

Parameters:

application_command (ApplicationCommand) – An object representing the application command to create.

Returns:

The application command that was created.

Return type:

Union[APIUserCommand, APIMessageCommand, APISlashCommand]

await edit_global_command(command_id, new_command)[source]

This function is a coroutine.

Edits a global application command.

New in version 2.1.

Parameters:
  • command_id (int) – The ID of the application command to edit.

  • new_command (ApplicationCommand) – An object representing the edited application command.

Returns:

The edited application command.

Return type:

Union[APIUserCommand, APIMessageCommand, APISlashCommand]

await delete_global_command(command_id)[source]

This function is a coroutine.

Deletes a global application command.

New in version 2.1.

Parameters:

command_id (int) – The ID of the application command to delete.

await bulk_overwrite_global_commands(application_commands)[source]

This function is a coroutine.

Overwrites several global application commands in one API request.

New in version 2.1.

Parameters:

application_commands (List[ApplicationCommand]) – A list of application commands to insert instead of the existing commands.

Returns:

A list of registered application commands.

Return type:

List[Union[APIUserCommand, APIMessageCommand, APISlashCommand]]

await fetch_guild_commands(guild_id, *, with_localizations=True)[source]

This function is a coroutine.

Retrieves a list of guild application commands.

New in version 2.1.

Parameters:
  • guild_id (int) – The ID of the guild to fetch commands from.

  • with_localizations (bool) –

    Whether to include localizations in the response. Defaults to True.

    New in version 2.5.

Returns:

A list of application commands.

Return type:

List[Union[APIUserCommand, APIMessageCommand, APISlashCommand]]

await fetch_guild_command(guild_id, command_id)[source]

This function is a coroutine.

Retrieves a guild application command.

New in version 2.1.

Parameters:
  • guild_id (int) – The ID of the guild to fetch command from.

  • command_id (int) – The ID of the application command to retrieve.

Returns:

The requested application command.

Return type:

Union[APIUserCommand, APIMessageCommand, APISlashCommand]

await create_guild_command(guild_id, application_command)[source]

This function is a coroutine.

Creates a guild application command.

New in version 2.1.

Parameters:
  • guild_id (int) – The ID of the guild where the application command should be created.

  • application_command (ApplicationCommand) – The application command.

Returns:

The newly created application command.

Return type:

Union[APIUserCommand, APIMessageCommand, APISlashCommand]

await edit_guild_command(guild_id, command_id, new_command)[source]

This function is a coroutine.

Edits a guild application command.

New in version 2.1.

Parameters:
  • guild_id (int) – The ID of the guild where the application command should be edited.

  • command_id (int) – The ID of the application command to edit.

  • new_command (ApplicationCommand) – An object representing the edited application command.

Returns:

The newly edited application command.

Return type:

Union[APIUserCommand, APIMessageCommand, APISlashCommand]

await delete_guild_command(guild_id, command_id)[source]

This function is a coroutine.

Deletes a guild application command.

New in version 2.1.

Parameters:
  • guild_id (int) – The ID of the guild where the applcation command should be deleted.

  • command_id (int) – The ID of the application command to delete.

await bulk_overwrite_guild_commands(guild_id, application_commands)[source]

This function is a coroutine.

Overwrites several guild application commands in one API request.

New in version 2.1.

Parameters:
  • guild_id (int) – The ID of the guild where the application commands should be overwritten.

  • application_commands (List[ApplicationCommand]) – A list of application commands to insert instead of the existing commands.

Returns:

A list of registered application commands.

Return type:

List[Union[APIUserCommand, APIMessageCommand, APISlashCommand]]

await bulk_fetch_command_permissions(guild_id)[source]

This function is a coroutine.

Retrieves a list of GuildApplicationCommandPermissions configured for the guild with the given ID.

New in version 2.1.

Parameters:

guild_id (int) – The ID of the guild to inspect.

await fetch_command_permissions(guild_id, command_id)[source]

This function is a coroutine.

Retrieves GuildApplicationCommandPermissions for a specific application command in the guild with the given ID.

New in version 2.1.

Parameters:
  • guild_id (int) – The ID of the guild to inspect.

  • command_id (int) –

    The ID of the application command, or the application ID to fetch application-wide permissions.

    Changed in version 2.5: Can now also fetch application-wide permissions.

Returns:

The permissions configured for the specified application command.

Return type:

GuildApplicationCommandPermissions

AutoShardedClient
class disnake.AutoShardedClient(*args, shard_ids=None, **kwargs)[source]

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[source]

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[source]

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)[source]

Gets the shard information of a given shard ID, or None if not found.

Return type:

Optional[ShardInfo]

property shards[source]

Returns a mapping of shard IDs to their respective info object.

Type:

Mapping[int, ShardInfo]

await connect(*, reconnect=True, ignore_session_start_limit=False)[source]

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.

Changed in version 2.6: Added usage of SessionStartLimit when connecting to the API. Added the ignore_session_start_limit parameter.

Parameters:
  • reconnect (bool) – Whether reconnecting should be attempted, 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).

  • ignore_session_start_limit (bool) –

    Whether the API provided session start limit should be ignored when connecting to the API.

    New in version 2.6.

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.

  • SessionStartLimitReached – If the client doesn’t have enough connects remaining in the current 24-hour window and ignore_session_start_limit is False this will be raised rather than connecting to the gateawy and Discord resetting the token. However, if ignore_session_start_limit is True, the client will connect regardless and this exception will not be raised.

await close()[source]

This function is a coroutine.

Closes the connection to Discord.

await change_presence(*, activity=None, status=None, shard_id=None)[source]

This function is a coroutine.

Changes the client’s presence.

Example:

game = disnake.Game("with the API")
await client.change_presence(status=disnake.Status.idle, activity=game)

Changed in version 2.0: Removed the afk keyword-only parameter.

Changed in version 2.6: Raises TypeError instead of InvalidArgument.

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:

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

is_ws_ratelimited()[source]

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.

Return type:

bool

Application Info

AppInfo
class disnake.AppInfo[source]

Represents the application info for the bot provided by Discord.

id

The application’s ID.

Type:

int

name

The application’s name.

Type:

str

owner

The application’s owner.

Type:

User

team

The application’s team.

New in version 1.3.

Type:

Optional[Team]

description

The application’s 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

guild_id

If this application is a game sold on Discord, this field will be the guild to which it has been linked to.

New in version 1.3.

Type:

Optional[int]

primary_sku_id

If this application is a game sold on Discord, this field will be the ID of the “Game SKU” that is created, if it exists.

New in version 1.3.

Type:

Optional[int]

slug

If this application is a game sold on Discord, this field will be the URL slug that links to the store page.

New in version 1.3.

Type:

Optional[str]

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]

flags

The application’s public flags.

New in version 2.3.

Type:

Optional[ApplicationFlags]

tags

The application’s tags.

New in version 2.5.

Type:

Optional[List[str]]

install_params

The installation parameters for this application.

New in version 2.5.

Type:

Optional[InstallParams]

custom_install_url

The custom installation url for this application.

New in version 2.5.

Type:

Optional[str]

property icon[source]

Retrieves the application’s icon asset, if any.

Type:

Optional[Asset]

property cover_image[source]

Retrieves the cover image on a store embed, if any.

This is only available if the application is a game sold on Discord.

Type:

Optional[Asset]

property guild[source]

If this application is a game sold on Discord, this field will be the guild to which it has been linked

New in version 1.3.

Type:

Optional[Guild]

property summary[source]

If this application is a game sold on Discord, this field will be the summary field for the store page of its primary SKU.

New in version 1.3.

Deprecated since version 2.5: This field is deprecated by discord and is now always blank. Consider using description instead.

Type:

str

PartialAppInfo
class disnake.PartialAppInfo[source]

Represents a partial AppInfo given by create_invite().

New in version 2.0.

id

The application’s ID.

Type:

int

name

The application’s name.

Type:

str

description

The application’s 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[source]

Retrieves the application’s icon asset, if any.

Type:

Optional[Asset]

property summary[source]

If this application is a game sold on Discord, this field will be the summary field for the store page of its primary SKU.

Deprecated since version 2.5: This field is deprecated by discord and is now always blank. Consider using description instead.

Type:

str

Team
class disnake.Team[source]

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[source]

Retrieves the team’s icon asset, if any.

Type:

Optional[Asset]

property owner[source]

The team’s owner.

Type:

Optional[TeamMember]

TeamMember
class disnake.TeamMember[source]

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[source]

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

InstallParams
Attributes
Methods
class disnake.InstallParams[source]

Represents the installation parameters for the application, provided by Discord.

New in version 2.5.

scopes

The scopes requested by the application.

Type:

List[str]

permissions

The permissions requested for the bot role.

Type:

Permissions

to_url()[source]

Return a string that can be used to add this application to a server.

Returns:

The invite url.

Return type:

str

Event Reference

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

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

import disnake

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

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

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

Warning

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

Client

This section documents events related to Client and its connectivity to Discord.

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

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

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

disnake.on_gateway_error(event, data, shard_id, exc)

When a (known) gateway event cannot be parsed, a traceback is printed to stderr and the exception is ignored by default. This should generally not happen and is usually either a library issue, or caused by a breaking API change.

To change this behaviour, for example to completely stop the bot, this event can be overridden.

This can also be disabled completely by passing enable_gateway_error_handler=False to the client on initialization, restoring the pre-v2.6 behavior.

New in version 2.6.

Note

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

Note

This will not be dispatched for exceptions that occur while parsing READY and RESUMED event payloads, as exceptions in these events are considered fatal.

Parameters:
  • event (str) – The name of the gateway event that was the cause of the exception, for example MESSAGE_CREATE.

  • data (Any) – The raw event payload.

  • shard_id (Optional[int]) – The ID of the shard the exception occurred in, if applicable.

  • exc (Exception) – The exception that was raised.

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

disnake.on_resumed()

Called when the client has resumed a session.

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

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

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

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

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

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

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

Channels/Threads

This section documents events related to Discord channels and threads.

disnake.on_guild_channel_delete(channel)
disnake.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.

disnake.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:
disnake.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[abc.GuildChannel, 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.

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

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

disnake.on_thread_create(thread)

Called whenever a thread is created.

Note that you can get the guild from Thread.guild.

This requires Intents.guilds to be enabled.

Note

This only works for threads created in channels the bot already has access to, and only for public threads unless the bot has the manage_threads permission.

New in version 2.5.

Parameters:

thread (Thread) – The thread that got created.

disnake.on_thread_join(thread)

Called whenever the bot joins a thread or gets access to a thread (for example, by gaining access to the parent channel).

Note that you can get the guild from Thread.guild.

This requires Intents.guilds to be enabled.

Note

This event will not be called for threads created by the bot or threads created on one of the bot’s messages.

New in version 2.0.

Changed in version 2.5: This is no longer being called when a thread is created, see on_thread_create() instead.

Parameters:

thread (Thread) – The thread that got joined.

disnake.on_thread_member_join(member)
disnake.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.

On removal events, if the member being removed is not found in the internal cache, then this event will not be called. Consider using on_raw_thread_member_remove() instead.

This requires Intents.members to be enabled.

New in version 2.0.

Parameters:

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

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

disnake.on_thread_update(before, after)

Called when a thread is updated. If the thread is not found in the internal thread cache, then this event will not be called. Consider using on_raw_thread_update() which will be called regardless of the cache.

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.

disnake.on_thread_delete(thread)

Called when a thread is deleted. If the thread is not found in the internal thread cache, then this event will not be called. Consider using on_raw_thread_delete() instead.

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.

disnake.on_raw_thread_member_remove(payload)

Called when a ThreadMember leaves Thread. Unlike on_thread_member_remove(), this is called regardless of the thread member cache.

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

This requires Intents.members to be enabled.

New in version 2.5.

Parameters:

payload (RawThreadMemberRemoveEvent) – The raw event payload data.

disnake.on_raw_thread_update(after)

Called whenever a thread is updated. Unlike on_thread_update(), this is called regardless of the state of the internal thread cache.

This requires Intents.guilds to be enabled.

New in version 2.5.

Parameters:

thread (Thread) – The updated thread.

disnake.on_raw_thread_delete(payload)

Called whenever a thread is deleted. Unlike on_thread_delete(), this is called regardless of the state of the internal thread cache.

Note that you can get the guild from Thread.guild.

This requires Intents.guilds to be enabled.

New in version 2.5.

Parameters:

payload (RawThreadDeleteEvent) – The raw event payload data.

disnake.on_webhooks_update(channel)

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

This requires Intents.webhooks to be enabled.

Parameters:

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

Guilds

This section documents events related to Discord guilds.

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

disnake.on_guild_remove(guild)

Called when a Guild is removed from the Client.

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

  • The client got banned.

  • The client got kicked.

  • The client left the guild.

  • The client or the guild owner deleted the guild.

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

This requires Intents.guilds to be enabled.

Parameters:

guild (Guild) – The guild that got removed.

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

disnake.on_guild_available(guild)
disnake.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.

Application Commands
disnake.on_application_command_permissions_update(permissions)

Called when the permissions of an application command or the application-wide command permissions are updated.

Note that this will also be called when permissions of other applications change, not just this application’s permissions.

New in version 2.5.

Parameters:

permissions (GuildApplicationCommandPermissions) – The updated permission object.

AutoMod
disnake.on_automod_action_execution(execution)

Called when an auto moderation action is executed due to a rule triggering for a particular event. You must have the manage_guild permission to receive this.

The guild this action has taken place in can be accessed using AutoModActionExecution.guild.

This requires Intents.automod_execution to be enabled.

In addition, Intents.message_content must be enabled to receive non-empty values for AutoModActionExecution.content and AutoModActionExecution.matched_content.

Note

This event will fire once per executed AutoModAction, which means it will run multiple times when a rule is triggered, if that rule has multiple actions defined.

New in version 2.6.

Parameters:

execution (AutoModActionExecution) – The auto moderation action execution data.

disnake.on_automod_rule_create(rule)

Called when an AutoModRule is created. You must have the manage_guild permission to receive this.

This requires Intents.automod_configuration to be enabled.

New in version 2.6.

Parameters:

rule (AutoModRule) – The auto moderation rule that was created.

disnake.on_automod_rule_update(rule)

Called when an AutoModRule is updated. You must have the manage_guild permission to receive this.

This requires Intents.automod_configuration to be enabled.

New in version 2.6.

Parameters:

rule (AutoModRule) – The auto moderation rule that was updated.

disnake.on_automod_rule_delete(rule)

Called when an AutoModRule is deleted. You must have the manage_guild permission to receive this.

This requires Intents.automod_configuration to be enabled.

New in version 2.6.

Parameters:

rule (AutoModRule) – The auto moderation rule that was deleted.

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

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

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

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

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

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

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

Members
disnake.on_member_join(member)
disnake.on_member_remove(member)

Called when a Member leaves or joins a Guild. If on_member_remove() is being used then consider using on_raw_member_remove() which will be called regardless of the cache.

This requires Intents.members to be enabled.

Parameters:

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

disnake.on_member_update(before, after)

Called when a Member updates their profile. Consider using on_raw_member_update() which will be called regardless of the cache.

This is called when one or more of the following things change, but is not limited to:

  • avatar (guild-specific)

  • current_timeout

  • nickname

  • pending

  • premium_since

  • roles

This requires Intents.members to be enabled.

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

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

disnake.on_raw_member_remove(payload)

Called when a member leaves a Guild. Unlike on_member_remove(), this is called regardless of the member cache.

New in version 2.6.

Parameters:

payload (RawGuildMemberRemoveEvent) – The raw event payload data.

disnake.on_raw_member_update(member)

Called when a member updates their profile. Unlike on_member_update(), this is called regardless of the member cache.

New in version 2.6.

Parameters:

member (Member) – The member that was updated.

disnake.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 on whether the user was in the guild at the time of removal.

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

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

disnake.on_user_update(before, after)

Called when a User is updated.

This is called when one or more of the following things change, but is not limited to:

  • avatar

  • discriminator

  • name

  • public_flags

This requires Intents.members to be enabled.

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

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

Scheduled Events
disnake.on_guild_scheduled_event_create(event)
disnake.on_guild_scheduled_event_delete(event)

Called when a guild scheduled event is created or deleted.

This requires Intents.guild_scheduled_events to be enabled.

New in version 2.3.

Parameters:

event (GuildScheduledEvent) – The guild scheduled event that was created or deleted.

disnake.on_guild_scheduled_event_update(before, after)

Called when a guild scheduled event is updated. The guild must have existed in the Client.guilds cache.

This requires Intents.guild_scheduled_events to be enabled.

New in version 2.3.

Parameters:
disnake.on_guild_scheduled_event_subscribe(event, user)
disnake.on_guild_scheduled_event_unsubscribe(event, user)

Called when a user subscribes to or unsubscribes from a guild scheduled event.

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

New in version 2.3.

Parameters:
  • event (GuildScheduledEvent) – The guild scheduled event that the user subscribed to or unsubscribed from.

  • user (Union[Member, User]) – The user who subscribed to or unsubscribed from the event.

disnake.on_raw_guild_scheduled_event_subscribe(payload)
disnake.on_raw_guild_scheduled_event_unsubscribe(payload)

Called when a user subscribes to or unsubscribes from a guild scheduled event. Unlike on_guild_scheduled_event_subscribe() and on_guild_scheduled_event_unsubscribe(), this is called regardless of the guild scheduled event cache.

Parameters:

payload (RawGuildScheduledEventUserActionEvent) – The raw event payload data.

Stage Instances
disnake.on_stage_instance_create(stage_instance)
disnake.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.

disnake.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:
Stickers
disnake.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.

Roles
disnake.on_guild_role_create(role)
disnake.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.

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

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

Interactions

This section documents events related to application commands and other interactions.

disnake.on_application_command(interaction)

Called when an application command is invoked.

Warning

This is a low level function that is not generally meant to be used. Consider using Bot or InteractionBot instead.

Warning

If you decide to override this event and are using Bot or related types, make sure to call Bot.process_application_commands to ensure that the application commands are processed.

New in version 2.0.

Parameters:

interaction (ApplicationCommandInteraction) – The interaction object.

disnake.on_application_command_autocomplete(interaction)

Called when an application command autocomplete is called.

Warning

This is a low level function that is not generally meant to be used. Consider using Bot or InteractionBot instead.

Warning

If you decide to override this event and are using Bot or related types, make sure to call Bot.process_app_command_autocompletion to ensure that the application command autocompletion is processed.

New in version 2.0.

Parameters:

interaction (ApplicationCommandInteraction) – The interaction object.

disnake.on_button_click(interaction)

Called when a button is clicked.

New in version 2.0.

Parameters:

interaction (MessageInteraction) – The interaction object.

disnake.on_dropdown(interaction)

Called when a select menu is clicked.

New in version 2.0.

Parameters:

interaction (MessageInteraction) – The interaction object.

disnake.on_interaction(interaction)

Called when an interaction happened.

This currently happens due to application command invocations or components being used.

Warning

This is a low level function that is not generally meant to be used.

New in version 2.0.

Parameters:

interaction (Interaction) – The interaction object.

disnake.on_message_interaction(interaction)

Called when a message interaction happened.

This currently happens due to components being used.

New in version 2.0.

Parameters:

interaction (MessageInteraction) – The interaction object.

disnake.on_modal_submit(interaction)

Called when a modal is submitted.

New in version 2.4.

Parameters:

interaction (ModalInteraction) – The interaction object.

Messages

This section documents events related to Discord chat messages.

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

Note

Not all messages will have content. This is a Discord limitation. See the docs of Intents.message_content for more information.

Parameters:

message (Message) – The current message.

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

Note

Not all messages will have content. This is a Discord limitation. See the docs of Intents.message_content for more information.

Parameters:

message (Message) – The deleted message.

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

Note

Not all messages will have content. This is a Discord limitation. See the docs of Intents.message_content for more information.

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.

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

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

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

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

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

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

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

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

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

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

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

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

disnake.on_typing(channel, user, when)

Called when someone begins typing a message.

The channel parameter can be a abc.Messageable instance, or a ForumChannel. If channel is an abc.Messageable instance, it could be a TextChannel, VoiceChannel, GroupChannel, or DMChannel.

Changed in version 2.5: channel may be a type ForumChannel

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

If the channel is a DMChannel and the user is not found in the internal user/member cache, then this event will not be called. Consider using on_raw_typing() instead.

This requires Intents.typing and Intents.guilds 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, if the bot didn’t explicitly open the DM channel in the same session (through User.create_dm(), Client.create_dm(), or indirectly by sending a message to the user). Consider using on_raw_typing() if you need this and do not otherwise want to enable the members intent.

Parameters:
disnake.on_raw_typing(data)

Called when someone begins typing a message.

This is similar to on_typing() except that it is called regardless of whether Intents.members and Intents.guilds are enabled.

Parameters:

data (RawTypingEvent) – The raw event payload data.

Utility Functions

disnake.utils.find(predicate, seq)[source]

A helper to return the first element found in the sequence that meets the predicate. For example:

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

disnake.utils.get(iterable, **attrs)[source]

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 = disnake.utils.get(message.guild.members, name='Foo')

Multiple attribute matching:

channel = disnake.utils.get(guild.voice_channels, name='Foo', bitrate=64000)

Nested attribute matching:

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

disnake.utils.snowflake_time(id)[source]
Parameters:

id (int) – The snowflake ID.

Returns:

An aware datetime in UTC representing the creation time of the snowflake.

Return type:

datetime.datetime

disnake.utils.oauth_url(client_id, *, permissions=..., guild=..., redirect_uri=..., scopes=..., disable_guild_select=False)[source]

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

disnake.utils.remove_markdown(text, *, ignore_links=True)[source]

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

disnake.utils.escape_markdown(text, *, as_needed=False, ignore_links=True)[source]

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

disnake.utils.escape_mentions(text)[source]

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

disnake.utils.resolve_invite(invite, *, with_params=False)[source]

Resolves an invite from a Invite, URL or code.

Parameters:
  • invite (Union[Invite, str]) – The invite to resolve.

  • with_params (bool) –

    Whether to also return the query parameters of the invite, if it’s a url.

    New in version 2.3.

Returns:

The invite code if with_params is False, otherwise a tuple containing the invite code and the url’s query parameters, if applicable.

Return type:

Union[str, Tuple[str, Dict[str, str]]]

disnake.utils.resolve_template(code)[source]

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 disnake.utils.sleep_until(when, result=None)[source]

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.

disnake.utils.utcnow()[source]

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

disnake.utils.format_dt(dt, /, style='f')[source]

A helper function to format a datetime.datetime, int or float 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 (Union[datetime.datetime, int, float]) – The datetime to format. If this is a naive datetime, it is assumed to be local time.

  • style (str) – The style to format the datetime with. Defaults to f

Returns:

The formatted string.

Return type:

str

disnake.utils.as_chunks(iterator, max_size)[source]

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]

for ... in disnake.utils.search_directory(path)[source]

Walk through a directory and yield all modules.

Parameters:

path (str) – The path to search for modules

Yields:

str – The name of the found module. (usable in load_extension)

disnake.utils.as_valid_locale(locale)[source]

Converts the provided locale name to a name that is valid for use with the API, for example by returning en-US for en_US. Returns None for invalid names.

New in version 2.5.

Parameters:

locale (str) – The input locale name.

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 disnake.ChannelType[source]

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 student hub channel.

New in version 2.1.

forum

A channel of only threads.

New in version 2.5.

class disnake.MessageType[source]

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.

application_command

The system message denoting that an application (or “slash”) command was executed.

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.

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.

context_menu_command

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

New in version 2.3.

auto_moderation_action

The system message denoting that an auto moderation action was executed.

New in version 2.5.

class disnake.UserFlags[source]

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.

http_interactions_bot

The user is a bot that only uses HTTP interactions.

New in version 2.3.

spammer

The user is marked as a spammer.

New in version 2.3.

class disnake.ActivityType[source]

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 disnake.PartyType[source]

Represents the type of a voice channel activity/application.

poker

The “Poker Night” activity.

betrayal

The “Betrayal.io” activity.

fishing

The “Fishington.io” activity.

chess

The “Chess In The Park” activity.

letter_tile

The “Letter Tile” activity.

word_snack

The “Word Snacks” activity.

doodle_crew

The “Doodle Crew” activity.

checkers

The “Checkers In The Park” activity.

New in version 2.3.

spellcast

The “SpellCast” activity.

New in version 2.3.

watch_together

The “Watch Together” activity, a Youtube application.

New in version 2.3.

sketch_heads

The “Sketch Heads” activity.

New in version 2.4.

ocho

The “Ocho” activity.

New in version 2.4.

class disnake.ApplicationCommandType[source]

Represents the type of an application command.

New in version 2.1.

chat_input

Represents a slash command.

user

Represents a user command from the context menu.

message

Represents a message command from the context menu.

class disnake.ApplicationCommandPermissionType[source]

Represents the type of a permission of an application command.

New in version 2.5.

role

Represents a permission that affects roles.

user

Represents a permission that affects users.

channel

Represents a permission that affects channels.

class disnake.InteractionType[source]

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 an application command interaction.

component

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

application_command_autocomplete

Represents an application command autocomplete interaction.

modal_submit

Represents a modal submit interaction.

class disnake.InteractionResponseType[source]

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

application_command_autocomplete_result

Responds to the autocomplete interaction with suggested choices.

See also InteractionResponse.autocomplete()

modal

Responds to the interaction by displaying a modal.

See also InteractionResponse.send_modal()

class disnake.ComponentType[source]

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

text_input

Represents a text input component.

class disnake.OptionType[source]

Represents the type of an option.

New in version 2.1.

sub_command

Represents a sub command of the main command or group.

sub_command_group

Represents a sub command group of the main command.

string

Represents a string option.

integer

Represents an integer option.

boolean

Represents a boolean option.

user

Represents a user option.

channel

Represents a channel option.

role

Represents a role option.

mentionable

Represents a role + user option.

number

Represents a float option.

attachment

Represents an attachment option.

New in version 2.4.

class disnake.ButtonStyle[source]

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 disnake.TextInputStyle[source]

Represents a style of the text input component.

New in version 2.4.

short

Represents a single-line text input component.

paragraph

Represents a multi-line text input component.

single_line

An alias for short.

multi_line

An alias for paragraph.

long

An alias for paragraph.

class disnake.VerificationLevel[source]

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 disnake.NotificationLevel[source]

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 disnake.ContentFilter[source]

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 disnake.Status[source]

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.

streaming

The member is live streaming to Twitch.

New in version 2.3.

class disnake.AuditLogAction[source]

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:

Changed in version 2.6: type for this action is now an int.

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:

Changed in version 2.6: type for this action is now an int.

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:

Changed in version 2.6: type for this action is now an int.

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

  • They were timed out

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 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 Webhook or Object with the webhook ID.

Possible attributes for AuditLogDiff:

Changed in version 2.6: Added application_id.

Changed in version 2.6: type for this action is now a WebhookType.

Changed in version 2.6: Added support for Webhook instead of plain Objects.

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 Webhook or Object with the webhook ID.

Possible attributes for AuditLogDiff:

Changed in version 2.6: Added support for Webhook instead of plain Objects.

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:

Changed in version 2.6: Added application_id.

Changed in version 2.6: type for this action is now a WebhookType.

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 PartialIntegration or Object with the integration ID of the integration which was created.

Possible attributes for AuditLogDiff:

New in version 1.3.

Changed in version 2.6: Added support for PartialIntegration instead of plain Objects.

integration_update

A guild integration was updated.

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

New in version 1.3.

Changed in version 2.6: Added support for PartialIntegration instead of plain Objects.

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.

Possible attributes for AuditLogDiff:

New in version 1.3.

guild_scheduled_event_create

A guild scheduled event was created.

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

Possible attributes for AuditLogDiff:

New in version 2.3.

guild_scheduled_event_update

A guild scheduled event was updated.

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

Possible attributes for AuditLogDiff:

New in version 2.3.

guild_scheduled_event_delete

A guild scheduled event was deleted.

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

Possible attributes for AuditLogDiff:

New in version 2.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.

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

  • channel: The StageChannel or Object with the channel ID where the stage instance was started.

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.

See stage_instance_create for more information on how the extra field is set.

Possible attributes for AuditLogDiff:

New in version 2.0.

stage_instance_delete

A stage instance was ended.

See stage_instance_create for more information on how the extra field is set.

Possible attributes for AuditLogDiff:

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

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 Object with the ID of the sticker which was deleted.

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 Object with the ID of the thread which was deleted.

Possible attributes for AuditLogDiff:

New in version 2.0.

application_command_permission_update

The permissions of an application command were updated.

When this is the action, the type of target is the ApplicationCommand, PartialIntegration, or Object with the ID of the command whose permissions were updated or the application ID if these are application-wide permissions.

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

Possible attributes for AuditLogDiff:

New in version 2.5.

Changed in version 2.6: Added support for PartialIntegration, and added integration to extra.

automod_rule_create

An auto moderation rule was created.

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

Possible attributes for AuditLogDiff:

New in version 2.6.

automod_rule_update

An auto moderation rule was updated.

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

Possible attributes for AuditLogDiff:

New in version 2.6.

automod_rule_delete

An auto moderation rule was deleted.

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

Possible attributes for AuditLogDiff:

New in version 2.6.

automod_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 who had their message blocked.

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

  • channel: A GuildChannel, Thread or Object with the channel ID where the message got blocked.

  • rule_name: A str with the name of the rule that matched.

  • rule_trigger_type: An AutoModTriggerType value with the trigger type of the rule.

automod_send_alert_message

An alert message was sent by an auto moderation rule.

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

See automod_block_message for more information on how the extra field is set.

automod_timeout

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

See automod_block_message for more information on how the extra field is set.

class disnake.AuditLogActionCategory[source]

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 disnake.TeamMembershipState[source]

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 disnake.WebhookType[source]

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 disnake.ExpireBehaviour[source]

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 disnake.DefaultAvatar[source]

Represents the default avatar of a Discord User

blurple

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

grey

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

gray

An alias for grey.

green

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

orange

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

red

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

class disnake.StickerType[source]

Represents the type of sticker.

New in version 2.0.

standard

Represents a standard sticker that all Nitro users can use.

guild

Represents a custom sticker created in a guild.

class disnake.StickerFormatType[source]

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.

class disnake.InviteTarget[source]

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 disnake.VideoQualityMode[source]

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 disnake.StagePrivacyLevel[source]

Represents a stage instance’s privacy level.

New in version 2.0.

public

The stage instance can be joined by external users.

Deprecated since version 2.5: Public stages are no longer supported by discord.

closed

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

guild_only

Alias for closed

class disnake.NSFWLevel[source]

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 disnake.GuildScheduledEventEntityType[source]

Represents the type of a guild scheduled event entity.

New in version 2.3.

stage_instance

The guild scheduled event will take place in a stage channel.

voice

The guild scheduled event will take place in a voice channel.

external

The guild scheduled event will take place in a custom location.

class disnake.GuildScheduledEventStatus[source]

Represents the status of a guild scheduled event.

New in version 2.3.

scheduled

Represents a scheduled event.

active

Represents an active event.

completed

Represents a completed event.

canceled

Represents a canceled event.

cancelled

An alias for canceled.

New in version 2.6.

class disnake.GuildScheduledEventPrivacyLevel[source]

Represents the privacy level of a guild scheduled event.

New in version 2.3.

guild_only

The guild scheduled event is only for a specific guild.

class disnake.ThreadArchiveDuration[source]

Represents the automatic archive duration of a thread in minutes.

New in version 2.3.

hour

The thread will archive after an hour of inactivity.

day

The thread will archive after a day of inactivity.

three_days

The thread will archive after three days of inactivity.

week

The thread will archive after a week of inactivity.

class disnake.WidgetStyle[source]

Represents the supported widget image styles.

New in version 2.5.

shield

A shield style image with a Discord icon and the online member count.

banner1

A large image with guild icon, name and online member count and a footer.

banner2

A small image with guild icon, name and online member count.

banner3

A large image with guild icon, name and online member count and a footer, with a “Chat Now” label on the right.

banner4

A large image with a large Discord logo, guild icon, name and online member count, with a “Join My Server” label at the bottom.

class disnake.Locale[source]

Represents supported locales by Discord.

New in version 2.5.

bg

The bg (Bulgarian) locale.

cs

The cs (Czech) locale.

da

The da (Danish) locale.

de

The de (German) locale.

el

The el (Greek) locale.

en_GB

The en_GB (English, UK) locale.

en_US

The en_US (English, US) locale.

es_ES

The es_ES (Spanish) locale.

fi

The fi (Finnish) locale.

fr

The fr (French) locale.

hi

The hi (Hindi) locale.

hr

The hr (Croatian) locale.

it

The it (Italian) locale.

ja

The ja (Japanese) locale.

ko

The ko (Korean) locale.

lt

The lt (Lithuanian) locale.

hu

The hu (Hungarian) locale.

nl

The nl (Dutch) locale.

no

The no (Norwegian) locale.

pl

The pl (Polish) locale.

pt_BR

The pt_BR (Portuguese) locale.

ro

The ro (Romanian) locale.

ru

The ru (Russian) locale.

sv_SE

The sv_SE (Swedish) locale.

th

The th (Thai) locale.

tr

The tr (Turkish) locale.

uk

The uk (Ukrainian) locale.

vi

The vi (Vietnamese) locale.

zh_CN

The zh_CN (Chinese, China) locale.

zh_TW

The zh_TW (Chinese, Taiwan) locale.

class disnake.AutoModActionType[source]

Represents the type of action an auto moderation rule will take upon execution.

New in version 2.6.

block_message

The rule will prevent matching messages from being posted.

send_alert_message

The rule will send an alert to a specified channel.

timeout

The rule will timeout the user that sent the message.

Note

This action type is only available for rules with trigger type keyword or mention_spam, and moderate_members permissions are required to use it.

class disnake.AutoModEventType[source]

Represents the type of event/context an auto moderation rule will be checked in.

New in version 2.6.

message_send

The rule will apply when a member sends or edits a message in the guild.

class disnake.AutoModTriggerType[source]

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

New in version 2.6.

keyword

The rule will filter messages based on a custom keyword list.

This trigger type requires additional metadata.

The rule will filter messages containing malicious links.

spam

The rule will filter messages suspected of being spam.

keyword_preset

The rule will filter messages based on predefined lists containing commonly flagged words.

This trigger type requires additional metadata.

mention_spam

The rule will filter messages based on the number of member/role mentions they contain.

This trigger type requires additional metadata.

class disnake.ThreadSortOrder[source]

Represents the sort order of threads in ForumChannels.

New in version 2.6.

latest_activity

Sort forum threads by activity.

creation_date

Sort forum threads by creation date/time (from newest to oldest).

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 disnake.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. In order to accomplish this goal, it must make use of a couple of data classes that aid in this goal.

AuditLogEntry
class disnake.AuditLogEntry(*, data, guild, application_commands, automod_rules, guild_scheduled_events, integrations, threads, users, webhooks)[source]

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

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

reason

The reason this action was done.

Type:

Optional[str]

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 disnake.AuditLogChanges[source]

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 disnake.AuditLogDiff[source]

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 or role’s icon.

See also Guild.icon or Role.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:

str

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[abc.GuildChannel, Object]

verification_level

The guild’s verification level.

See also Guild.verification_level.

Type:

VerificationLevel

premium_progress_bar_enabled

Whether the guild’s premium progress bar is enabled.

See also Guild.premium_progress_bar_enabled.

Type:

bool

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

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

Type:

str

preferred_locale

The guild’s preferred locale.

Type:

Locale

position

The position of a Role or abc.GuildChannel.

Type:

int

type

The type of channel/thread, sticker, webhook, integration (str), or permission overwrite (int).

Type:

Union[ChannelType, StickerType, WebhookType, str, int]

topic

The topic of a TextChannel, StageChannel, StageInstance or ForumChannel.

See also TextChannel.topic, StageChannel.topic, StageInstance.topic or ForumChannel.topic.

Type:

str

bitrate

The bitrate of a VoiceChannel or StageChannel.

See also VoiceChannel.bitrate or StageChannel.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[Union[Member, User, Role, Object], PermissionOverwrite]]

privacy_level

The privacy level of the stage instance or guild scheduled event.

Type:

Union[StagePrivacyLevel, GuildScheduledEventPrivacyLevel]

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 or creating another thread in the channel.

See also TextChannel.slowmode_delay, VoiceChannel.slowmode_delay, ForumChannel.slowmode_delay or Thread.slowmode_delay.

Type:

int

default_thread_slowmode_delay

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

See also ForumChannel.default_thread_slowmode_delay.

Type:

int

rtc_region

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

See also VoiceChannel.rtc_region or StageChannel.rtc_region.

Type:

str

video_quality_mode

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

See also VoiceChannel.video_quality_mode or StageChannel.video_quality_mode.

Type:

VideoQualityMode

user_limit

The voice channel’s user limit.

See also VoiceChannel.user_limit.

Type:

int

nsfw

Whether the channel is marked as “not safe for work”.

See also TextChannel.nsfw, VoiceChannel.nsfw or ForumChannel.nsfw.

Type:

bool

format_type

The format type of a sticker being changed.

See also GuildSticker.format

Type:

StickerFormatType

emoji

The name of the sticker’s or role’s emoji being changed.

See also GuildSticker.emoji or Role.emoji.

Type:

str

description

The description of a guild, sticker or a guild scheduled event being changed.

See also Guild.description, GuildSticker.description, GuildScheduledEvent.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

invitable

Whether non-moderators can add other non-moderators to the thread.

Type:

bool

timeout

The datetime when the timeout expires, if any.

Type:

datetime.datetime

entity_type

The entity type of a guild scheduled event being changed.

Type:

GuildScheduledEventEntityType

location

The location of a guild scheduled event being changed.

Type:

str

status

The status of a guild scheduled event being changed.

Type:

GuildScheduledEventStatus

image

The cover image of a guild scheduled event being changed.

Type:

Asset

command_permissions

A mapping of target ID to guild permissions of an application command.

Note that only changed permission entries are included, not necessarily all of the command’s permissions.

Type:

Dict[int, ApplicationCommandPermissions]

application_id

The ID of the application that created a webhook.

Type:

int

flags

The channel’s flags.

See also abc.GuildChannel.flags or Thread.flags.

Type:

ChannelFlags

system_channel_flags

The guild’s system channel settings.

See also Guild.system_channel_flags.

Type:

SystemChannelFlags

enabled

Whether something was enabled or disabled.

Type:

bool

trigger_type

The trigger type of an auto moderation rule being changed.

Type:

AutoModTriggerType

event_type

The event type of an auto moderation rule being changed.

Type:

AutoModEventType

actions

The list of actions of an auto moderation rule being changed.

Type:

List[AutoModAction]

trigger_metadata

The additional 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 being 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 being set.

Type:

List[Union[abc.GuildChannel, Object]]

applied_tags

The tags applied to a thread in a forum channel being changed.

If a tag is not found, then it is an Object with the ID being set.

Type:

List[Union[ForumTag, Object]]

available_tags

The available tags for threads in a forum channel being changed.

Type:

List[ForumTag]

default_reaction

The default emoji shown for reacting to threads in a forum channel being changed.

Due to a Discord limitation, this will have an empty name if it is a custom PartialEmoji.

Type:

Optional[Union[Emoji, PartialEmoji]]

default_sort_order

The default sort order of threads in a forum channel being changed.

Type:

Optional[ThreadSortOrder]

Webhook Support

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

Webhook
class disnake.Webhook[source]

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(), TextChannel.webhooks(), and VoiceChannel.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 disnake 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 webhook’s type.

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

Type:

Optional[int]

channel_id

The channel ID this webhook belongs to.

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]

application_id

The ID of the application associated with this webhook, if it was created by an application.

New in version 2.6.

Type:

Optional[int]

property url[source]

Returns the webhook’s url.

Type:

str

classmethod partial(id, token, *, session, bot_token=None)[source]

Creates a partial Webhook.

Parameters:
  • id (int) – The webhook’s ID.

  • token (str) – The webhook’s authentication token.

  • 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)[source]

Creates a partial Webhook from a webhook URL.

Changed in version 2.6: Raises ValueError instead of InvalidArgument.

Parameters:
  • url (str) – The webhook’s URL.

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

ValueError – 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)[source]

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.

Changed in version 2.6: Raises WebhookTokenMissing instead of InvalidArgument.

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)[source]

This function is a coroutine.

Deletes this Webhook.

Changed in version 2.6: Raises WebhookTokenMissing instead of InvalidArgument.

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:
await edit(*, reason=None, name=..., avatar=..., channel=None, prefer_auth=True)[source]

This function is a coroutine.

Edits this Webhook.

Changed in version 2.6: Raises WebhookTokenMissing instead of InvalidArgument.

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

  • avatar (Optional[Union[bytes, Asset, Emoji, PartialEmoji, StickerItem, Sticker]]) –

    The webhook’s new default avatar.

    Changed in version 2.5: Now accepts various resource types in addition to bytes.

  • channel (Optional[abc.Snowflake]) –

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

    New in version 2.0.

  • prefer_auth (bool) –

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

    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.

Raises:
  • HTTPException – Editing the webhook failed.

  • NotFound – This webhook does not exist or the avatar asset couldn’t be found.

  • TypeError – The avatar asset is a lottie sticker (see Sticker.read()).

  • WebhookTokenMissing – This webhook does not have a token associated with it or it tried editing a channel without authentication.

Returns:

The newly edited webhook.

Return type:

Webhook

property avatar[source]

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[source]

The channel this webhook belongs to.

If this is a partial webhook, then this will always return None.

Webhooks in ForumChannels can not send messages directly, they can only create new threads (see thread_name for Webhook.send) and interact with existing threads.

Type:

Optional[Union[TextChannel, VoiceChannel, ForumChannel]]

property created_at[source]

Returns the webhook’s creation time in UTC.

Type:

datetime.datetime

property guild[source]

The guild this webhook belongs to.

If this is a partial webhook, then this will always return None.

Type:

Optional[Guild]

is_authenticated()[source]

Whether the webhook is authenticated with a bot token.

New in version 2.0.

Return type:

bool

is_partial()[source]

Whether the webhook is a “partial” webhook.

New in version 2.0.

Return type:

bool

await send(content=..., *, username=..., avatar_url=..., tts=False, ephemeral=False, suppress_embeds=False, file=..., files=..., embed=..., embeds=..., allowed_mentions=..., view=..., components=..., thread=..., thread_name=None, wait=False, delete_after=...)[source]

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.6: Raises WebhookTokenMissing instead of InvalidArgument.

Parameters:
  • content (Optional[str]) – The content of the message to send.

  • 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) – Whether the message should be sent using text-to-speech.

  • ephemeral (bool) –

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

    New in version 2.0.

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

  • files (List[File]) – A list of files to upload. Must be a maximum of 10. This cannot be mixed with the file parameter.

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

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

  • allowed_mentions (AllowedMentions) –

    Controls the mentions being processed in this message. If this is passed, then the object is merged with Client.allowed_mentions, if applicable. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set in Client.allowed_mentions. If no object is passed at all then the defaults given by Client.allowed_mentions are used instead.

    New in version 1.4.

  • view (disnake.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. This cannot be mixed with components.

    New in version 2.0.

  • components (Union[disnake.ui.ActionRow, disnake.ui.WrappedComponent, List[Union[disnake.ui.ActionRow, disnake.ui.WrappedComponent, List[disnake.ui.WrappedComponent]]]]) –

    A list of components to include in the message. This cannot be mixed with view.

    New in version 2.4.

  • thread (Snowflake) –

    The thread to send this webhook to.

    New in version 2.0.

  • thread_name (str) –

    If in a forum channel, and thread is not specified, the name of the newly created thread.

    Note

    If this is set, the returned message’s channel (assuming wait=True), representing the created thread, may be a PartialMessageable.

    New in version 2.6.

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

  • delete_after (float) –

    If provided, the number of seconds to wait in the background before deleting the message we just sent. If the deletion fails, then it is silently ignored.

    New in version 2.1.

  • suppress_embeds (bool) –

    Whether to suppress embeds for the message. This hides all embeds from the UI if set to True.

    New in version 2.5.

Raises:
  • HTTPException – Sending the message failed.

  • NotFound – This webhook was not found.

  • Forbidden – The authorization token for the webhook is incorrect.

  • TypeError – Raised by any of the following: You specified both embed and embeds or file and files. ephemeral was passed with the improper webhook type. There was no state attached with this webhook when giving it a view. Both thread and thread_name were provided.

  • WebhookTokenMissing – There was no token associated with this webhook.

  • ValueError – The length of embeds was invalid.

Returns:

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

Return type:

Optional[WebhookMessage]

await fetch_message(id)[source]

This function is a coroutine.

Retrieves a single WebhookMessage owned by this webhook.

New in version 2.0.

Changed in version 2.6: Raises WebhookTokenMissing instead of InvalidArgument.

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.

  • WebhookTokenMissing – There was no token associated with this webhook.

Returns:

The message asked for.

Return type:

WebhookMessage

await edit_message(message_id, *, content=..., embed=..., embeds=..., file=..., files=..., attachments=..., view=..., components=..., allowed_mentions=None)[source]

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.

Note

If the original message has embeds with images that were created from local files (using the file parameter with Embed.set_image() or Embed.set_thumbnail()), those images will be removed if the message’s attachments are edited in any way (i.e. by setting file/files/attachments, or adding an embed with local files).

New in version 1.6.

Changed in version 2.0: The edit is no longer in-place, instead the newly edited message is returned.

Changed in version 2.6: Raises WebhookTokenMissing instead of InvalidArgument.

Parameters:
  • message_id (int) – The ID of the message to edit.

  • content (Optional[str]) – The content to edit the message with, or None to clear it.

  • embed (Optional[Embed]) – The new embed to replace the original with. This cannot be mixed with the embeds parameter. Could be None to remove the embed.

  • embeds (List[Embed]) – The new embeds to replace the original with. Must be a maximum of 10. This cannot be mixed with the embed parameter. To remove all embeds [] should be passed.

  • file (File) –

    The file to upload. This cannot be mixed with the files parameter. Files will be appended to the message, see the attachments parameter to remove/replace existing files.

    New in version 2.0.

  • files (List[File]) –

    A list of files to upload. This cannot be mixed with the file parameter. Files will be appended to the message, see the attachments parameter to remove/replace existing files.

    New in version 2.0.

  • attachments (Optional[List[Attachment]]) –

    A list of attachments to keep in the message. If [] or None is passed then all existing attachments are removed. Keeps existing attachments if not provided.

    New in version 2.2.

    Changed in version 2.5: Supports passing None to clear attachments.

  • 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(). This cannot be mixed with components.

    New in version 2.0.

  • components (Union[disnake.ui.ActionRow, disnake.ui.WrappedComponent, List[Union[disnake.ui.ActionRow, disnake.ui.WrappedComponent, List[disnake.ui.WrappedComponent]]]]) –

    A list of components to update this message with. This cannot be mixed with view.

    New in version 2.4.

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

Raises:
  • HTTPException – Editing the message failed.

  • Forbidden – Edited a message that is not yours.

  • TypeError – You specified both embed and embeds or file and files or there is no associated state when sending a view.

  • WebhookTokenMissing – There was no token associated with this webhook.

  • ValueError – The length of embeds was invalid

Returns:

The newly edited webhook message.

Return type:

WebhookMessage

await delete_message(message_id, /)[source]

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.

Changed in version 2.6: Raises WebhookTokenMissing instead of InvalidArgument.

Parameters:

message_id (int) – The ID of the message to delete.

Raises:
WebhookMessage
Methods
class disnake.WebhookMessage[source]

Represents a message sent from your webhook.

This allows you to edit or delete a message sent by your webhook.

This inherits from disnake.Message with changes to edit() and delete() to work.

New in version 1.6.

await edit(content=..., embed=..., embeds=..., file=..., files=..., attachments=..., view=..., components=..., allowed_mentions=None)[source]

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.

Note

If the original message has embeds with images that were created from local files (using the file parameter with Embed.set_image() or Embed.set_thumbnail()), those images will be removed if the message’s attachments are edited in any way (i.e. by setting file/files/attachments, or adding an embed with local files).

Parameters:
  • content (Optional[str]) – The content to edit the message with, or None to clear it.

  • embed (Optional[Embed]) – The new embed to replace the original with. This cannot be mixed with the embeds parameter. Could be None to remove the embed.

  • embeds (List[Embed]) – The new embeds to replace the original with. Must be a maximum of 10. This cannot be mixed with the embed parameter. To remove all embeds [] should be passed.

  • file (File) –

    The file to upload. This cannot be mixed with the files parameter. Files will be appended to the message, see the attachments parameter to remove/replace existing files.

    New in version 2.0.

  • files (List[File]) –

    A list of files to upload. This cannot be mixed with the file parameter. Files will be appended to the message, see the attachments parameter to remove/replace existing files.

    New in version 2.0.

  • attachments (Optional[List[Attachment]]) –

    A list of attachments to keep in the message. If [] or None is passed then all existing attachments are removed. Keeps existing attachments if not provided.

    New in version 2.2.

    Changed in version 2.5: Supports passing None to clear attachments.

  • view (Optional[View]) –

    The view to update this message with. This cannot be mixed with components. If None is passed then the view is removed.

    New in version 2.0.

  • components (Optional[Union[disnake.ui.ActionRow, disnake.ui.WrappedComponent, List[Union[disnake.ui.ActionRow, disnake.ui.WrappedComponent, List[disnake.ui.WrappedComponent]]]]]) –

    A list of components to update the message with. This cannot be mixed with view. If None is passed then the components are removed.

    New in version 2.4.

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

Raises:
Returns:

The newly edited message.

Return type:

WebhookMessage

await delete(*, delay=None)[source]

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 disnake.SyncWebhook[source]

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 webhook’s type.

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

Type:

Optional[int]

channel_id

The channel ID this webhook belongs to.

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]

application_id

The ID of the application associated with this webhook, if it was created by an application.

New in version 2.6.

Type:

Optional[int]

property url[source]

Returns the webhook’s url.

Type:

str

classmethod partial(id, token, *, session=..., bot_token=None)[source]

Creates a partial Webhook.

Parameters:
  • id (int) – The webhook’s ID.

  • token (str) – The webhook’s authentication token.

  • 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)[source]

Creates a partial Webhook from a webhook URL.

Changed in version 2.6: Raises ValueError instead of InvalidArgument.

Parameters:
  • url (str) – The webhook’s URL.

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

ValueError – 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)[source]

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.

Changed in version 2.6: Raises WebhookTokenMissing instead of InvalidArgument.

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)[source]

Deletes this Webhook.

Changed in version 2.6: Raises WebhookTokenMissing instead of InvalidArgument.

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.

Raises:
edit(*, reason=None, name=..., avatar=..., channel=None, prefer_auth=True)[source]

Edits this Webhook.

Changed in version 2.6: Raises WebhookTokenMissing instead of InvalidArgument.

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

  • avatar (Optional[bytes]) – A bytes-like object representing the webhook’s new default avatar.

  • channel (Optional[abc.Snowflake]) – The webhook’s new channel. This requires an authenticated webhook.

  • prefer_auth (bool) – Whether to use the bot token over the webhook token if available. Defaults to True.

  • reason (Optional[str]) –

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

    New in version 1.4.

Raises:
  • HTTPException – Editing the webhook failed.

  • NotFound – This webhook does not exist.

  • WebhookTokenMissing – This webhook does not have a token associated with it or it tried editing a channel without authentication.

Returns:

The newly edited webhook.

Return type:

SyncWebhook

send(content=..., *, username=..., avatar_url=..., tts=False, file=..., files=..., embed=..., embeds=..., suppress_embeds=..., allowed_mentions=..., thread=..., thread_name=None, wait=False)[source]

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.6: Raises WebhookTokenMissing instead of InvalidArgument.

Parameters:
  • content (Optional[str]) – The content of the message to send.

  • 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) – Whether the message should be sent using text-to-speech.

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

  • files (List[File]) – A list of files to upload. Must be a maximum of 10. This cannot be mixed with the file parameter.

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

  • embeds (List[Embed]) – A list of embeds to send with the content. Must be a 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.

  • thread (Snowflake) –

    The thread to send this message to.

    New in version 2.0.

  • thread_name (str) –

    If in a forum channel, and thread is not specified, the name of the newly created thread.

    New in version 2.6.

  • suppress_embeds (bool) –

    Whether to suppress embeds for the message. This hides all embeds from the UI if set to True.

    New in version 2.5.

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

Raises:
  • HTTPException – Sending the message failed.

  • NotFound – This webhook was not found.

  • Forbidden – The authorization token for the webhook is incorrect.

  • TypeError – You specified both embed and embeds or file and files, or both thread and thread_name were provided.

  • ValueError – The length of embeds was invalid

  • WebhookTokenMissing – There was no token associated with this webhook.

Returns:

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

Return type:

Optional[SyncWebhookMessage]

fetch_message(id, /)[source]

Retrieves a single SyncWebhookMessage owned by this webhook.

New in version 2.0.

Changed in version 2.6: Raises WebhookTokenMissing instead of InvalidArgument.

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.

  • WebhookTokenMissing – There was no token associated with this webhook.

Returns:

The message asked for.

Return type:

SyncWebhookMessage

property avatar[source]

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[source]

The channel this webhook belongs to.

If this is a partial webhook, then this will always return None.

Webhooks in ForumChannels can not send messages directly, they can only create new threads (see thread_name for Webhook.send) and interact with existing threads.

Type:

Optional[Union[TextChannel, VoiceChannel, ForumChannel]]

property created_at[source]

Returns the webhook’s creation time in UTC.

Type:

datetime.datetime

edit_message(message_id, *, content=..., embed=..., embeds=..., file=..., files=..., attachments=..., allowed_mentions=None)[source]

Edits a message owned by this webhook.

This is a lower level interface to WebhookMessage.edit() in case you only have an ID.

Note

If the original message has embeds with images that were created from local files (using the file parameter with Embed.set_image() or Embed.set_thumbnail()), those images will be removed if the message’s attachments are edited in any way (i.e. by setting file/files/attachments, or adding an embed with local files).

New in version 1.6.

Changed in version 2.6: Raises WebhookTokenMissing instead of InvalidArgument.

Parameters:
  • message_id (int) – The ID of the message to edit.

  • content (Optional[str]) – The content to edit the message with, or None to clear it.

  • embed (Optional[Embed]) – The new embed to replace the original with. This cannot be mixed with the embeds parameter. Could be None to remove the embed.

  • embeds (List[Embed]) – The new embeds to replace the original with. Must be a maximum of 10. This cannot be mixed with the embed parameter. To remove all embeds [] should be passed.

  • file (File) – The file to upload. This cannot be mixed with the files parameter. Files will be appended to the message, see the attachments parameter to remove/replace existing files.

  • files (List[File]) – A list of files to upload. This cannot be mixed with the file parameter. Files will be appended to the message, see the attachments parameter to remove/replace existing files.

  • attachments (Optional[List[Attachment]]) –

    A list of attachments to keep in the message. If [] or None is passed then all existing attachments are removed. Keeps existing attachments if not provided.

    New in version 2.2.

    Changed in version 2.5: Supports passing None to clear attachments.

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

Raises:
property guild[source]

The guild this webhook belongs to.

If this is a partial webhook, then this will always return None.

Type:

Optional[Guild]

is_authenticated()[source]

Whether the webhook is authenticated with a bot token.

New in version 2.0.

Return type:

bool

is_partial()[source]

Whether the webhook is a “partial” webhook.

New in version 2.0.

Return type:

bool

delete_message(message_id, /)[source]

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.

Changed in version 2.6: Raises WebhookTokenMissing instead of InvalidArgument.

Parameters:

message_id (int) – The ID of the message to delete.

Raises:
SyncWebhookMessage
Methods
class disnake.SyncWebhookMessage[source]

Represents a message sent from your webhook.

This allows you to edit or delete a message sent by your webhook.

This inherits from disnake.Message with changes to edit() and delete() to work.

New in version 2.0.

edit(content=..., embed=..., embeds=..., file=..., files=..., attachments=..., allowed_mentions=None)[source]

Edits the message.

Note

If the original message has embeds with images that were created from local files (using the file parameter with Embed.set_image() or Embed.set_thumbnail()), those images will be removed if the message’s attachments are edited in any way (i.e. by setting file/files/attachments, or adding an embed with local files).

Changed in version 2.6: Raises WebhookTokenMissing instead of InvalidArgument.

Parameters:
  • content (Optional[str]) – The content to edit the message with or None to clear it.

  • embed (Optional[Embed]) – The new embed to replace the original with. This cannot be mixed with the embeds parameter. Could be None to remove the embed.

  • embeds (List[Embed]) – The new embeds to replace the original with. Must be a maximum of 10. This cannot be mixed with the embed parameter. To remove all embeds [] should be passed.

  • file (File) – The file to upload. This cannot be mixed with the files parameter. Files will be appended to the message, see the attachments parameter to remove/replace existing files.

  • files (List[File]) – A list of files to upload. This cannot be mixed with the file parameter. Files will be appended to the message, see the attachments parameter to remove/replace existing files.

  • attachments (Optional[List[Attachment]]) –

    A list of attachments to keep in the message. If [] or None is passed then all existing attachments are removed. Keeps existing attachments if not provided.

    New in version 2.2.

    Changed in version 2.5: Supports passing None to clear attachments.

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

Raises:
Returns:

The newly edited message.

Return type:

SyncWebhookMessage

delete(*, delay=None)[source]

Deletes the message.

Changed in version 2.6: Raises WebhookTokenMissing instead of InvalidArgument.

Parameters:

delay (Optional[float]) – If provided, the number of seconds to wait before deleting the message. This blocks the thread.

Raises:

Abstract Base Classes

An abstract base class (also known as an abc) is a class that models can inherit to get their behaviour. Abstract base classes should not be instantiated. They are mainly there for usage with isinstance() and issubclass().

This library has a module related to abstract base classes, in which all the ABCs are subclasses of typing.Protocol.

Snowflake
Attributes
class disnake.abc.Snowflake[source]

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

Almost all Discord models meet this abstract base class.

If you want to create a snowflake on your own, consider using Object.

id

The model’s unique ID.

Type:

int

User
class disnake.abc.User[source]

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

The following classes implement this ABC:

This ABC must also implement Snowflake.

name

The user’s username.

Type:

str

discriminator

The user’s discriminator.

Type:

str

avatar

The avatar asset the user has.

Type:

Asset

bot

Whether the user is a bot account.

Type:

bool

property display_name[source]

Returns the user’s display name.

Type:

str

property mention[source]

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

Type:

str

PrivateChannel
Attributes
class disnake.abc.PrivateChannel[source]

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

The following classes implement this ABC:

This ABC must also implement Snowflake.

me

The user representing yourself.

Type:

ClientUser

GuildChannel
class disnake.abc.GuildChannel[source]

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

The following classes implement this ABC:

This ABC must also implement abc.Snowflake.

name

The channel name.

Type:

str

guild

The guild the channel belongs to.

Type:

Guild

position

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

Type:

int

property changed_roles[source]

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

Type:

List[Role]

property mention[source]

The string that allows you to mention the channel.

Type:

str

property created_at[source]

Returns the channel’s creation time in UTC.

Type:

datetime.datetime

overwrites_for(obj)[source]

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

Parameters:

obj (Union[Role, abc.User]) – The role or user denoting whose overwrite to get.

Returns:

The permission overwrites for this object.

Return type:

PermissionOverwrite

property overwrites[source]

Returns all of the channel’s overwrites.

This is returned as a dictionary where the key contains the target which can be either a Role or a Member and the value is the overwrite as a PermissionOverwrite.

Returns:

The channel’s permission overwrites.

Return type:

Dict[Union[Role, Member], PermissionOverwrite]

property category[source]

The category this channel belongs to.

If there is no category then this is None.

Type:

Optional[CategoryChannel]

property permissions_synced[source]

Whether or not the permissions for this channel are synced with the category it belongs to.

If there is no category then this is False.

New in version 1.3.

Type:

bool

property flags[source]

The channel flags for this channel.

New in version 2.6.

Type:

ChannelFlags

property jump_url[source]

A URL that can be used to jump to this channel.

New in version 2.4.

Note

This exists for all guild channels but may not be usable by the client for all guild channel types.

permissions_for(obj, /, *, ignore_timeout=...)[source]

Handles permission resolution for the Member or Role.

This function takes into consideration the following cases:

  • Guild owner

  • Guild roles

  • Channel overrides

  • Member overrides

  • Timeouts

If a Role is passed, then it checks the permissions someone with that role would have, which is essentially:

  • The default role permissions

  • The permissions of the role used as a parameter

  • The default role permission overwrites

  • The permission overwrites of the role used as a parameter

Changed in version 2.0: The object passed in can now be a role object.

Parameters:
  • obj (Union[Member, Role]) – The object to resolve permissions for. This could be either a member or a role. If it’s a role then member overwrites are not computed.

  • ignore_timeout (bool) –

    Whether or not to ignore the user’s timeout. Defaults to False.

    New in version 2.4.

    Note

    This only applies to Member objects.

    Changed in version 2.6: The default was changed to False.

Raises:

TypeErrorignore_timeout is only supported for Member objects.

Returns:

The resolved permissions for the member or role.

Return type:

Permissions

await delete(*, reason=None)[source]

This function is a coroutine.

Deletes the channel.

You must have Permissions.manage_channels permission to do this.

Parameters:

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

Raises:
  • Forbidden – You do not have proper permissions to delete the channel.

  • NotFound – The channel was not found or was already deleted.

  • HTTPException – Deleting the channel failed.

await set_permissions(target, *, overwrite=..., reason=None, **permissions)[source]

This function is a coroutine.

Sets the channel specific permission overwrites for a target in the channel.

The target parameter should either be a Member or a Role that belongs to guild.

The overwrite parameter, if given, must either be None or PermissionOverwrite. For convenience, you can pass in keyword arguments denoting Permissions attributes. If this is done, then you cannot mix the keyword arguments with the overwrite parameter.

If the overwrite parameter is None, then the permission overwrites are deleted.

You must have Permissions.manage_roles permission to do this.

Note

This method replaces the old overwrites with the ones given.

Changed in version 2.6: Raises TypeError instead of InvalidArgument.

Examples

Setting allow and deny:

await message.channel.set_permissions(message.author, view_channel=True,
                                                      send_messages=False)

Deleting overwrites

await channel.set_permissions(member, overwrite=None)

Using PermissionOverwrite

overwrite = disnake.PermissionOverwrite()
overwrite.send_messages = False
overwrite.view_channel = True
await channel.set_permissions(member, overwrite=overwrite)
Parameters:
  • target (Union[Member, Role]) – The member or role to overwrite permissions for.

  • overwrite (Optional[PermissionOverwrite]) – The permissions to allow and deny to the target, or None to delete the overwrite.

  • **permissions – A keyword argument list of permissions to set for ease of use. Cannot be mixed with overwrite.

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

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

  • HTTPException – Editing channel specific permissions failed.

  • NotFound – The role or member being edited is not part of the guild.

  • TypeErroroverwrite is invalid, the target type was not Role or Member, both keyword arguments and overwrite were provided, or invalid permissions were provided as keyword arguments.

await clone(*, name=None, reason=None)[source]

This function is a coroutine.

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

You must have Permissions.manage_channels permission to do this.

New in version 1.1.

Parameters:
  • name (Optional[str]) – The name of the new channel. If not provided, defaults to this channel name.

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

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

  • HTTPException – Creating the channel failed.

Returns:

The channel that was created.

Return type:

abc.GuildChannel

await move(**kwargs)[source]

This function is a coroutine.

A rich interface to help move a channel relative to other channels.

If exact position movement is required, edit should be used instead.

You must have Permissions.manage_channels permission to do this.

Note

Voice channels will always be sorted below text channels. This is a Discord limitation.

New in version 1.7.

Changed in version 2.6: Raises TypeError or ValueError instead of InvalidArgument.

Parameters:
  • beginning (bool) – Whether to move the channel to the beginning of the channel list (or category if given). This is mutually exclusive with end, before, and after.

  • end (bool) – Whether to move the channel to the end of the channel list (or category if given). This is mutually exclusive with beginning, before, and after.

  • before (abc.Snowflake) – The channel that should be before our current channel. This is mutually exclusive with beginning, end, and after.

  • after (abc.Snowflake) – The channel that should be after our current channel. This is mutually exclusive with beginning, end, and before.

  • offset (int) – The number of channels to offset the move by. For example, an offset of 2 with beginning=True would move it 2 after the beginning. A positive number moves it below while a negative number moves it above. Note that this number is relative and computed after the beginning, end, before, and after parameters.

  • category (Optional[abc.Snowflake]) – The category to move this channel under. If None is given then it moves it out of the category. This parameter is ignored if moving a category channel.

  • sync_permissions (bool) – Whether to sync the permissions with the category (if given).

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

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

  • HTTPException – Moving the channel failed.

  • TypeError – A bad mix of arguments were passed.

  • ValueError – An invalid position was given.

await create_invite(*, reason=None, max_age=0, max_uses=0, temporary=False, unique=True, target_type=None, target_user=None, target_application=None, guild_scheduled_event=None)[source]

This function is a coroutine.

Creates an instant invite from a text or voice channel.

You must have Permissions.create_instant_invite permission to do this.

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

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

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

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

  • target_type (Optional[InviteTarget]) –

    The type of target for the voice channel invite, if any.

    New in version 2.0.

  • target_user (Optional[User]) –

    The user whose stream to display for this invite, required if target_type is TargetType.stream. The user must be streaming in the channel.

    New in version 2.0.

  • target_application (Optional[PartyType]) –

    The ID of the embedded application for the invite, required if target_type is TargetType.embedded_application.

    New in version 2.0.

  • guild_scheduled_event (Optional[GuildScheduledEvent]) –

    The guild scheduled event to include with the invite.

    New in version 2.3.

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

Raises:
  • HTTPException – Invite creation failed.

  • NotFound – The channel that was passed is a category or an invalid channel.

Returns:

The newly created invite.

Return type:

Invite

await invites()[source]

This function is a coroutine.

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

You must have Permissions.manage_channels permission to use this.

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

  • HTTPException – An error occurred while fetching the information.

Returns:

The list of invites that are currently active.

Return type:

List[Invite]

Messageable
Methods
class disnake.abc.Messageable[source]

An ABC that details the common operations on a model that can send messages.

The following classes implement this ABC:

async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)[source]

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

You must have Permissions.read_message_history permission to use this.

Examples

Usage

counter = 0
async for message in channel.history(limit=200):
    if message.author == client.user:
        counter += 1

Flattening into a list:

messages = await channel.history(limit=123).flatten()
# messages is now a list of Message...

All parameters are optional.

Parameters:
  • limit (Optional[int]) – The number of messages to retrieve. If None, retrieves every message in the channel. Note, however, that this would make it a slow operation.

  • before (Optional[Union[abc.Snowflake, datetime.datetime]]) – Retrieve messages before this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.

  • after (Optional[Union[abc.Snowflake, datetime.datetime]]) – Retrieve messages after this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.

  • around (Optional[Union[abc.Snowflake, datetime.datetime]]) – Retrieve messages around this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time. When using this argument, the maximum limit is 101. Note that if the limit is an even number then this will return at most limit + 1 messages.

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

Raises:
  • Forbidden – You do not have permissions to get channel message history.

  • HTTPException – The request to get message history failed.

Yields:

Message – The message with the message data parsed.

async with typing()[source]

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

This is useful for denoting long computations in your bot.

Note

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

Example Usage:

async with channel.typing():
    # simulate something heavy
    await asyncio.sleep(10)

await channel.send('done!')
await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, suppress_embeds=False, allowed_mentions=None, reference=None, mention_author=None, view=None, components=None)[source]

This function is a coroutine.

Sends a message to the destination with the content given.

The content must be a type that can convert to a string through str(content).

At least one of content, embed/embeds, file/files, stickers, components, or view must be provided.

To upload a single file, the file parameter should be used with a single File object. To upload multiple files, the files parameter should be used with a list of File objects. Specifying both parameters will lead to an exception.

To upload a single embed, the embed parameter should be used with a single Embed object. To upload multiple embeds, the embeds parameter should be used with a list of Embed objects. Specifying both parameters will lead to an exception.

Changed in version 2.6: Raises TypeError or ValueError instead of InvalidArgument.

Parameters:
  • content (Optional[str]) – The content of the message to send.

  • tts (bool) – Whether the message should be sent using text-to-speech.

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

  • embeds (List[Embed]) –

    A list of embeds to send with the content. Must be a maximum of 10. This cannot be mixed with the embed parameter.

    New in version 2.0.

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

  • files (List[File]) – A list of files to upload. Must be a maximum of 10. This cannot be mixed with the file parameter.

  • stickers (Sequence[Union[GuildSticker, StickerItem]]) –

    A list of stickers to upload. Must be a maximum of 3.

    New in version 2.0.

  • nonce (Union[str, int]) – The nonce to use for sending this message. If the message was successfully sent, then the message will have a nonce with this value.

  • delete_after (float) – If provided, the number of seconds to wait in the background before deleting the message we just sent. If the deletion fails, then it is silently ignored.

  • allowed_mentions (AllowedMentions) –

    Controls the mentions being processed in this message. If this is passed, then the object is merged with Client.allowed_mentions. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set in Client.allowed_mentions. If no object is passed at all then the defaults given by Client.allowed_mentions are used instead.

    New in version 1.4.

  • reference (Union[Message, MessageReference, PartialMessage]) –

    A reference to the Message to which you are replying, this can be created using Message.to_reference() or passed directly as a Message. You can control whether this mentions the author of the referenced message using the AllowedMentions.replied_user attribute of allowed_mentions or by setting mention_author.

    New in version 1.6.

  • mention_author (Optional[bool]) –

    If set, overrides the AllowedMentions.replied_user attribute of allowed_mentions.

    New in version 1.6.

  • view (ui.View) –

    A Discord UI View to add to the message. This cannot be mixed with components.

    New in version 2.0.

  • components (Union[disnake.ui.ActionRow, disnake.ui.WrappedComponent, List[Union[disnake.ui.ActionRow, disnake.ui.WrappedComponent, List[disnake.ui.WrappedComponent]]]]) –

    A list of components to include in the message. This cannot be mixed with view.

    New in version 2.4.

  • suppress_embeds (bool) –

    Whether to suppress embeds for the message. This hides all embeds from the UI if set to True.

    New in version 2.5.

Raises:
Returns:

The message that was sent.

Return type:

Message

await trigger_typing()[source]

This function is a coroutine.

Triggers a typing indicator to the destination.

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

await fetch_message(id, /)[source]

This function is a coroutine.

Retrieves a single Message from the destination.

Parameters:

id (int) – The message ID to look for.

Raises:
  • NotFound – The specified message was not found.

  • Forbidden – You do not have the permissions required to get a message.

  • HTTPException – Retrieving the message failed.

Returns:

The message asked for.

Return type:

Message

await pins()[source]

This function is a coroutine.

Retrieves all messages that are currently pinned in the channel.

Note

Due to a limitation with the Discord API, the Message objects returned by this method do not contain complete Message.reactions data.

Raises:

HTTPException – Retrieving the pinned messages failed.

Returns:

The messages that are currently pinned.

Return type:

List[Message]

Connectable
class disnake.abc.Connectable[source]

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

The following classes implement this ABC:

Note

This ABC is not decorated with typing.runtime_checkable(), so will fail isinstance()/issubclass() checks.

Discord Models

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

Danger

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

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

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

Note

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

ClientUser
class disnake.ClientUser[source]

Represents your Discord user.

x == y

Checks if two users are equal.

x != y

Checks if two users are not equal.

hash(x)

Return the user’s hash.

str(x)

Returns the user’s name with discriminator.

name

The user’s username.

Type:

str

id

The user’s unique ID.

Type:

int

discriminator

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

Type:

str

bot

Specifies if the user is a bot account.

Type:

bool

system

Specifies if the user is a system user (i.e. represents Discord officially).

New in version 1.3.

Type:

bool

verified

Specifies if the user’s email is verified.

Type:

bool

locale

The IETF language tag used to identify the language the user is using.

Changed in version 2.5: Changed to Locale instead of str.

Type:

Optional[Locale]

mfa_enabled

Specifies if the user has MFA turned on and working.

Type:

bool

await edit(*, username=..., avatar=...)[source]

This function is a coroutine.

Edits the current profile of the client.

Note

To upload an avatar, a resource (see below) or a bytes-like object must be passed in that represents the image being uploaded.

The only image formats supported for uploading are JPG and PNG.

Changed in version 2.0: The edit is no longer in-place, instead the newly edited client user is returned.

Changed in version 2.6: Raises ValueError instead of InvalidArgument.

Parameters:
Raises:
Returns:

The newly edited client user.

Return type:

ClientUser

property accent_color[source]

Returns the user’s accent color, if applicable.

There is an alias for this named accent_colour.

New in version 2.0.

Note

This information is only available via Client.fetch_user().

Type:

Optional[Colour]

property accent_colour[source]

Returns the user’s accent colour, if applicable.

There is an alias for this named accent_color.

New in version 2.0.

Note

This information is only available via Client.fetch_user().

Type:

Optional[Colour]

property avatar[source]

Returns an Asset for the avatar the user has.

If the user does not have a traditional avatar, None is returned. If you want the avatar that a user has displayed, consider display_avatar.

Type:

Optional[Asset]

property banner[source]

Returns the user’s banner asset, if available.

New in version 2.0.

Note

This information is only available via Client.fetch_user().

Type:

Optional[Asset]

property color[source]

A property that returns a color denoting the rendered color for the user. This always returns Colour.default().

There is an alias for this named colour.

Type:

Colour

property colour[source]

A property that returns a colour denoting the rendered colour for the user. This always returns Colour.default().

There is an alias for this named color.

Type:

Colour

property created_at[source]

Returns the user’s creation time in UTC.

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

Type:

datetime.datetime

property default_avatar[source]

Returns the default avatar for a given user. This is calculated by the user’s discriminator.

Type:

Asset

property display_avatar[source]

Returns the user’s display avatar.

For regular users this is just their default avatar or uploaded avatar.

New in version 2.0.

Type:

Asset

property display_name[source]

Returns the user’s display name.

For regular users this is just their username, but if they have a guild specific nickname then that is returned instead.

Type:

str

property mention[source]

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

Type:

str

mentioned_in(message)[source]

Checks if the user is mentioned in the specified message.

Parameters:

message (Message) – The message to check.

Returns:

Indicates if the user is mentioned in the message.

Return type:

bool

property public_flags[source]

The publicly available flags the user has.

Type:

PublicUserFlags

User
class disnake.User[source]

Represents a Discord user.

x == y

Checks if two users are equal.

x != y

Checks if two users are not equal.

hash(x)

Return the user’s hash.

str(x)

Returns the user’s name with discriminator.

name

The user’s username.

Type:

str

id

The user’s unique ID.

Type:

int

discriminator

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

Type:

str

bot

Specifies if the user is a bot account.

Type:

bool

system

Specifies if the user is a system user (i.e. represents Discord officially).

Type:

bool

async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)[source]

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

You must have Permissions.read_message_history permission to use this.

Examples

Usage

counter = 0
async for message in channel.history(limit=200):
    if message.author == client.user:
        counter += 1

Flattening into a list:

messages = await channel.history(limit=123).flatten()
# messages is now a list of Message...

All parameters are optional.

Parameters:
  • limit (Optional[int]) – The number of messages to retrieve. If None, retrieves every message in the channel. Note, however, that this would make it a slow operation.

  • before (Optional[Union[abc.Snowflake, datetime.datetime]]) – Retrieve messages before this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.

  • after (Optional[Union[abc.Snowflake, datetime.datetime]]) – Retrieve messages after this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.

  • around (Optional[Union[abc.Snowflake, datetime.datetime]]) – Retrieve messages around this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time. When using this argument, the maximum limit is 101. Note that if the limit is an even number then this will return at most limit + 1 messages.

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

Raises:
  • Forbidden – You do not have permissions to get channel message history.

  • HTTPException – The request to get message history failed.

Yields:

Message – The message with the message data parsed.

async with typing()[source]

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

This is useful for denoting long computations in your bot.

Note

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

Example Usage:

async with channel.typing():
    # simulate something heavy
    await asyncio.sleep(10)

await channel.send('done!')
property dm_channel[source]

Returns the channel associated with this user if it exists.

If this returns None, you can create a DM channel by calling the create_dm() coroutine function.

Type:

Optional[DMChannel]

property mutual_guilds[source]

The guilds that the user shares with the client.

Note

This will only return mutual guilds within the client’s internal cache.

New in version 1.7.

Type:

List[Guild]

property accent_color[source]

Returns the user’s accent color, if applicable.

There is an alias for this named accent_colour.

New in version 2.0.

Note

This information is only available via Client.fetch_user().

Type:

Optional[Colour]

property accent_colour[source]

Returns the user’s accent colour, if applicable.

There is an alias for this named accent_color.

New in version 2.0.

Note

This information is only available via Client.fetch_user().

Type:

Optional[Colour]

property avatar[source]

Returns an Asset for the avatar the user has.

If the user does not have a traditional avatar, None is returned. If you want the avatar that a user has displayed, consider display_avatar.

Type:

Optional[Asset]

property banner[source]

Returns the user’s banner asset, if available.

New in version 2.0.

Note

This information is only available via Client.fetch_user().

Type:

Optional[Asset]

property color[source]

A property that returns a color denoting the rendered color for the user. This always returns Colour.default().

There is an alias for this named colour.

Type:

Colour

property colour[source]

A property that returns a colour denoting the rendered colour for the user. This always returns Colour.default().

There is an alias for this named color.

Type:

Colour

await create_dm()[source]

This function is a coroutine.

Creates a DMChannel with this user.

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

Returns:

The channel that was created.

Return type:

DMChannel

property created_at[source]

Returns the user’s creation time in UTC.

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

Type:

datetime.datetime

property default_avatar[source]

Returns the default avatar for a given user. This is calculated by the user’s discriminator.

Type:

Asset

property display_avatar[source]

Returns the user’s display avatar.

For regular users this is just their default avatar or uploaded avatar.

New in version 2.0.

Type:

Asset

property display_name[source]

Returns the user’s display name.

For regular users this is just their username, but if they have a guild specific nickname then that is returned instead.

Type:

str

await fetch_message(id, /)[source]

This function is a coroutine.

Retrieves a single Message from the destination.

Parameters:

id (int) – The message ID to look for.

Raises:
  • NotFound – The specified message was not found.

  • Forbidden – You do not have the permissions required to get a message.

  • HTTPException – Retrieving the message failed.

Returns:

The message asked for.

Return type:

Message

property mention[source]

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

Type:

str

mentioned_in(message)[source]

Checks if the user is mentioned in the specified message.

Parameters:

message (Message) – The message to check.

Returns:

Indicates if the user is mentioned in the message.

Return type:

bool

await pins()[source]

This function is a coroutine.

Retrieves all messages that are currently pinned in the channel.

Note

Due to a limitation with the Discord API, the Message objects returned by this method do not contain complete Message.reactions data.

Raises:

HTTPException – Retrieving the pinned messages failed.

Returns:

The messages that are currently pinned.

Return type:

List[Message]

property public_flags[source]

The publicly available flags the user has.

Type:

PublicUserFlags

await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, suppress_embeds=False, allowed_mentions=None, reference=None, mention_author=None, view=None, components=None)[source]

This function is a coroutine.

Sends a message to the destination with the content given.

The content must be a type that can convert to a string through str(content).

At least one of content, embed/embeds, file/files, stickers, components, or view must be provided.

To upload a single file, the file parameter should be used with a single File object. To upload multiple files, the files parameter should be used with a list of File objects. Specifying both parameters will lead to an exception.

To upload a single embed, the embed parameter should be used with a single Embed object. To upload multiple embeds, the embeds parameter should be used with a list of Embed objects. Specifying both parameters will lead to an exception.

Changed in version 2.6: Raises TypeError or ValueError instead of InvalidArgument.

Parameters:
  • content (Optional[str]) – The content of the message to send.

  • tts (bool) – Whether the message should be sent using text-to-speech.

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

  • embeds (List[Embed]) –

    A list of embeds to send with the content. Must be a maximum of 10. This cannot be mixed with the embed parameter.

    New in version 2.0.

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

  • files (List[File]) – A list of files to upload. Must be a maximum of 10. This cannot be mixed with the file parameter.

  • stickers (Sequence[Union[GuildSticker, StickerItem]]) –

    A list of stickers to upload. Must be a maximum of 3.

    New in version 2.0.

  • nonce (Union[str, int]) – The nonce to use for sending this message. If the message was successfully sent, then the message will have a nonce with this value.

  • delete_after (float) – If provided, the number of seconds to wait in the background before deleting the message we just sent. If the deletion fails, then it is silently ignored.

  • allowed_mentions (AllowedMentions) –

    Controls the mentions being processed in this message. If this is passed, then the object is merged with Client.allowed_mentions. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set in Client.allowed_mentions. If no object is passed at all then the defaults given by Client.allowed_mentions are used instead.

    New in version 1.4.

  • reference (Union[Message, MessageReference, PartialMessage]) –

    A reference to the Message to which you are replying, this can be created using Message.to_reference() or passed directly as a Message. You can control whether this mentions the author of the referenced message using the AllowedMentions.replied_user attribute of allowed_mentions or by setting mention_author.

    New in version 1.6.

  • mention_author (Optional[bool]) –

    If set, overrides the AllowedMentions.replied_user attribute of allowed_mentions.

    New in version 1.6.

  • view (ui.View) –

    A Discord UI View to add to the message. This cannot be mixed with components.

    New in version 2.0.

  • components (Union[disnake.ui.ActionRow, disnake.ui.WrappedComponent, List[Union[disnake.ui.ActionRow, disnake.ui.WrappedComponent, List[disnake.ui.WrappedComponent]]]]) –

    A list of components to include in the message. This cannot be mixed with view.

    New in version 2.4.

  • suppress_embeds (bool) –

    Whether to suppress embeds for the message. This hides all embeds from the UI if set to True.

    New in version 2.5.

Raises:
Returns:

The message that was sent.

Return type:

Message

await trigger_typing()[source]

This function is a coroutine.

Triggers a typing indicator to the destination.

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

Attachment
class disnake.Attachment[source]

Represents an attachment from Discord.

str(x)

Returns the URL of the attachment.

x == y

Checks if the attachment is equal to another attachment.

x != y

Checks if the attachment is not equal to another attachment.

hash(x)

Returns the hash of the attachment.

Changed in version 1.7: Attachment can now be casted to str and is hashable.

id

The attachment’s ID.

Type:

int

size

The attachment’s size in bytes.

Type:

int

height

The attachment’s height, in pixels. Only applicable to images and videos.

Type:

Optional[int]

width

The attachment’s width, in pixels. Only applicable to images and videos.

Type:

Optional[int]

filename

The attachment’s filename.

Type:

str

url

The attachment URL. If the message this attachment was attached to is deleted, then this will 404.

Type:

str

proxy_url

The proxy URL. This is a cached version of the url in the case of images. When the message is deleted, this URL might be valid for a few minutes or not valid at all.

Type:

str

content_type

The attachment’s media type

New in version 1.7.

Type:

Optional[str]

ephemeral

Whether the attachment is ephemeral.

New in version 2.1.

Type:

bool

description

The attachment’s description

New in version 2.3.

Type:

str

is_spoiler()[source]

Whether this attachment contains a spoiler.

Return type:

bool

await save(fp, *, seek_begin=True, use_cached=False)[source]

This function is a coroutine.

Saves this attachment into a file-like object.

Parameters:
  • fp (Union[io.BufferedIOBase, os.PathLike]) – The file-like object to save this attachment to or the filename to use. If a filename is passed then a file is created with that filename and used instead.

  • seek_begin (bool) – Whether to seek to the beginning of the file after saving is successfully done.

  • use_cached (bool) – Whether to use proxy_url rather than url when downloading the attachment. This will allow attachments to be saved after deletion more often, compared to the regular URL which is generally deleted right after the message is deleted. Note that this can still fail to download deleted attachments if too much time has passed and it does not work on some types of attachments.

Raises:
Returns:

The number of bytes written.

Return type:

int

await read(*, use_cached=False)[source]

This function is a coroutine.

Retrieves the content of this attachment as a bytes object.

New in version 1.1.

Parameters:

use_cached (bool) – Whether to use proxy_url rather than url when downloading the attachment. This will allow attachments to be saved after deletion more often, compared to the regular URL which is generally deleted right after the message is deleted. Note that this can still fail to download deleted attachments if too much time has passed and it does not work on some types of attachments.

Raises:
  • HTTPException – Downloading the attachment failed.

  • Forbidden – You do not have permissions to access this attachment

  • NotFound – The attachment was deleted.

Returns:

The contents of the attachment.

Return type:

bytes

await to_file(*, use_cached=False, spoiler=False, description=...)[source]

This function is a coroutine.

Converts the attachment into a File suitable for sending via abc.Messageable.send().

New in version 1.3.

Parameters:
  • use_cached (bool) –

    Whether to use proxy_url rather than url when downloading the attachment. This will allow attachments to be saved after deletion more often, compared to the regular URL which is generally deleted right after the message is deleted. Note that this can still fail to download deleted attachments if too much time has passed and it does not work on some types of attachments.

    New in version 1.4.

  • spoiler (bool) –

    Whether the file is a spoiler.

    New in version 1.4.

  • description (Optional[str]) –

    The file’s description. Copies this attachment’s description by default, set to None to remove.

    New in version 2.3.

Raises:
  • HTTPException – Downloading the attachment failed.

  • Forbidden – You do not have permissions to access this attachment

  • NotFound – The attachment was deleted.

Returns:

The attachment as a file suitable for sending.

Return type:

File

Asset
Attributes
class disnake.Asset[source]

Represents a CDN asset on Discord.

str(x)

Returns the URL of the CDN asset.

len(x)

Returns the length of the CDN asset’s URL.

x == y

Checks if the asset is equal to another asset.

x != y

Checks if the asset is not equal to another asset.

hash(x)

Returns the hash of the asset.

property url[source]

Returns the underlying URL of the asset.

Type:

str

property key[source]

Returns the identifying key of the asset.

Type:

str

is_animated()[source]

Whether the asset is animated.

Return type:

bool

replace(*, size=..., format=..., static_format=...)[source]

Returns a new asset with the passed components replaced.

Changed in version 2.6: Raises ValueError instead of InvalidArgument.

Parameters:
  • size (int) – The new size of the asset.

  • format (str) – The new format to change it to. Must be either ‘webp’, ‘jpeg’, ‘jpg’, ‘png’, or ‘gif’ if it’s animated.

  • static_format (str) – The new format to change it to if the asset isn’t animated. Must be either ‘webp’, ‘jpeg’, ‘jpg’, or ‘png’.

Raises:

ValueError – An invalid size or format was passed.

Returns:

The newly updated asset.

Return type:

Asset

with_size(size, /)[source]

Returns a new asset with the specified size.

Changed in version 2.6: Raises ValueError instead of InvalidArgument.

Parameters:

size (int) – The new size of the asset.

Raises:

ValueError – The asset had an invalid size.

Returns:

The newly updated asset.

Return type:

Asset

with_format(format, /)[source]

Returns a new asset with the specified format.

Changed in version 2.6: Raises ValueError instead of InvalidArgument.

Parameters:

format (str) – The new format of the asset.

Raises:

ValueError – The asset had an invalid format.

Returns:

The newly updated asset.

Return type:

Asset

with_static_format(format, /)[source]

Returns a new asset with the specified static format.

This only changes the format if the underlying asset is not animated. Otherwise, the asset is not changed.

Changed in version 2.6: Raises ValueError instead of InvalidArgument.

Parameters:

format (str) – The new static format of the asset.

Raises:

ValueError – The asset had an invalid format.

Returns:

The newly updated asset.

Return type:

Asset

await read()[source]

This function is a coroutine.

Retrieves the content of this asset as a bytes object.

Raises:
Returns:

The content of the asset.

Return type:

bytes

await save(fp, *, seek_begin=True)[source]

This function is a coroutine.

Saves this asset into a file-like object.

Parameters:
  • fp (Union[io.BufferedIOBase, os.PathLike]) – The file-like object to save this asset to or the filename to use. If a filename is passed then a file is created with that filename and used instead.

  • seek_begin (bool) – Whether to seek to the beginning of the file after saving is successfully done.

Raises:
Returns:

The number of bytes written.

Return type:

int

await to_file(*, spoiler=False, filename=None, description=None)[source]

This function is a coroutine.

Converts the asset into a File suitable for sending via abc.Messageable.send().

New in version 2.5.

Changed in version 2.6: Raises TypeError instead of InvalidArgument.

Parameters:
  • spoiler (bool) – Whether the file is a spoiler.

  • filename (Optional[str]) – The filename to display when uploading to Discord. If this is not given, it defaults to the name of the asset’s URL.

  • description (Optional[str]) – The file’s description.

Raises:
Returns:

The asset as a file suitable for sending.

Return type:

File

Message
class disnake.Message[source]

Represents a message from Discord.

x == y

Checks if two messages are equal.

x != y

Checks if two messages are not equal.

hash(x)

Returns the message’s hash.

tts

Specifies if the message was done with text-to-speech. This can only be accurately received in on_message() due to a Discord limitation.

Type:

bool

type

The type of message. In most cases this should not be checked, but it is helpful in cases where it might be a system message for system_content.

Type:

MessageType

author

A Member that sent the message. If channel is a private channel or the user has the left the guild, then it is a User instead.

Type:

Union[Member, abc.User]

content

The actual contents of the message.

Type:

str

nonce

The value used by the Discord guild and the client to verify that the message is successfully sent. This is not stored long term within Discord’s servers and is only used ephemerally.

Type:

Optional[Union[str, int]]

embeds

A list of embeds the message has.

Type:

List[Embed]

channel

The channel that the message was sent from. Could be a DMChannel or GroupChannel if it’s a private message.

Type:

Union[TextChannel, VoiceChannel, Thread, DMChannel, GroupChannel, PartialMessageable]

position

A number that indicates the approximate position of a message in a Thread. This is a number that starts at 0. e.g. the first message is position 0. This is None if the message was not sent in a Thread, or if it was sent before July 1, 2022.

New in version 2.6.

Type:

Optional[int]

reference

The message that this message references. This is only applicable to messages of type MessageType.pins_add, crossposted messages created by a followed channel integration, or message replies.

New in version 1.5.

Type:

Optional[MessageReference]

interaction

The interaction that this message references. This exists only when the message is a response to an interaction without an existing message.

New in version 2.1.

Type:

Optional[InteractionReference]

mention_everyone

Specifies if the message mentions everyone.

Note

This does not check if the @everyone or the @here text is in the message itself. Rather this boolean indicates if either the @everyone or the @here text is in the message and it did end up mentioning.

Type:

bool

mentions

A list of Member that were mentioned. If the message is in a private message then the list will be of User instead. For messages that are not of type MessageType.default, this array can be used to aid in system messages. For more information, see system_content.

Warning

The order of the mentions list is not in any particular order so you should not rely on it. This is a Discord limitation, not one with the library.

Type:

List[abc.User]

role_mentions

A list of Role that were mentioned. If the message is in a private message then the list is always empty.

Type:

List[Role]

id

The message ID.

Type:

int

application_id

If this message was sent from an interaction, or is an application owned webhook, then this is the ID of the application.

New in version 2.5.

Type:

Optional[int]

webhook_id

If this message was sent by a webhook, then this is the webhook ID’s that sent this message.

Type:

Optional[int]

attachments

A list of attachments given to a message.

Type:

List[Attachment]

pinned

Specifies if the message is currently pinned.

Type:

bool

flags

Extra features of the message.

New in version 1.3.

Type:

MessageFlags

reactions

Reactions to a message. Reactions can be either custom emoji or standard unicode emoji.

Type:

List[Reaction]

activity

The activity associated with this message. Sent with Rich-Presence related messages that for example, request joining, spectating, or listening to or with another member.

It is a dictionary with the following optional keys:

  • type: An integer denoting the type of message activity being requested.

  • party_id: The party ID associated with the party.

Type:

Optional[dict]

application

The rich presence enabled application associated with this message.

It is a dictionary with the following keys:

  • id: A string representing the application’s ID.

  • name: A string representing the application’s name.

  • description: A string representing the application’s description.

  • icon: A string representing the icon ID of the application.

  • cover_image: A string representing the embed’s image asset ID.

Type:

Optional[dict]

stickers

A list of sticker items given to the message.

New in version 1.6.

Type:

List[StickerItem]

components

A list of components in the message.

New in version 2.0.

Type:

List[Component]

guild

The guild that the message belongs to, if applicable.

Type:

Optional[Guild]

raw_mentions

A property that returns an array of user IDs matched with the syntax of <@user_id> in the message content.

This allows you to receive the user IDs of mentioned users even in a private message context.

Type:

List[int]

raw_channel_mentions

A property that returns an array of channel IDs matched with the syntax of <#channel_id> in the message content.

Type:

List[int]

raw_role_mentions

A property that returns an array of role IDs matched with the syntax of <@&role_id> in the message content.

Type:

List[int]

channel_mentions

A list of abc.GuildChannel that were mentioned. If the message is in a private message then the list is always empty.

Type:

List[abc.GuildChannel]

clean_content

A property that returns the content in a “cleaned up” manner. This basically means that mentions are transformed into the way the client shows it. e.g. <#id> will transform into #name.

This will also transform @everyone and @here mentions into non-mentions.

Note

This does not affect markdown. If you want to escape or remove markdown then use utils.escape_markdown() or utils.remove_markdown() respectively, along with this function.

Type:

str

property created_at[source]

The message’s creation time in UTC.

Type:

datetime.datetime

property edited_at[source]

An aware UTC datetime object containing the edited time of the message.

Type:

Optional[datetime.datetime]

property jump_url[source]

Returns a URL that allows the client to jump to this message.

Type:

str

property thread[source]

The thread started from this message. None if no thread has been started.

New in version 2.4.

Type:

Optional[Thread]

is_system()[source]

Whether the message is a system message.

A system message is a message that is constructed entirely by the Discord API in response to something.

New in version 1.3.

Return type:

bool

system_content

A property that returns the content that is rendered regardless of the Message.type.

In the case of MessageType.default and MessageType.reply, this just returns the regular Message.content. Otherwise this returns an English message denoting the contents of the system message.

Type:

str

await delete(*, delay=None)[source]

This function is a coroutine.

Deletes the message.

Your own messages could be deleted without any proper permissions. However to delete other people’s messages, you need the manage_messages permission.

Changed in version 1.1: Added the new delay keyword-only parameter.

Parameters:

delay (Optional[float]) – If provided, the number of seconds to wait in the background before deleting the message. If the deletion fails then it is silently ignored.

Raises:
  • Forbidden – You do not have proper permissions to delete the message.

  • NotFound – The message was deleted already

  • HTTPException – Deleting the message failed.

await edit(content=..., *, embed=..., embeds=..., file=..., files=..., attachments=..., suppress=..., suppress_embeds=..., allowed_mentions=..., view=..., components=..., delete_after=None)[source]

This function is a coroutine.

Edits the message.

The content must be able to be transformed into a string via str(content).

Note

If the original message has embeds with images that were created from local files (using the file parameter with Embed.set_image() or Embed.set_thumbnail()), those images will be removed if the message’s attachments are edited in any way (i.e. by setting file/files/attachments, or adding an embed with local files).

Changed in version 1.3: The suppress keyword-only parameter was added.

Changed in version 2.5: The suppress keyword-only parameter was deprecated in favor of suppress_embeds.

Changed in version 2.6: Raises TypeError instead of InvalidArgument.

Parameters:
  • content (Optional[str]) – The new content to replace the message with. Could be None to remove the content.

  • embed (Optional[Embed]) – The new embed to replace the original with. This cannot be mixed with the embeds parameter. Could be None to remove the embed.

  • embeds (List[Embed]) –

    The new embeds to replace the original with. Must be a maximum of 10. This cannot be mixed with the embed parameter. To remove all embeds [] should be passed.

    New in version 2.0.

  • file (File) –

    The file to upload. This cannot be mixed with the files parameter. Files will be appended to the message, see the attachments parameter to remove/replace existing files.

    New in version 2.1.

  • files (List[File]) –

    A list of files to upload. This cannot be mixed with the file parameter. Files will be appended to the message, see the attachments parameter to remove/replace existing files.

    New in version 2.1.

  • attachments (Optional[List[Attachment]]) –

    A list of attachments to keep in the message. If [] or None is passed then all existing attachments are removed. Keeps existing attachments if not provided.

    Changed in version 2.5: Supports passing None to clear attachments.

  • suppress_embeds (bool) – Whether to suppress embeds for the message. This removes all the embeds if set to True. If set to False this brings the embeds back if they were suppressed. Using this parameter requires manage_messages.

  • delete_after (Optional[float]) – If provided, the number of seconds to wait in the background before deleting the message we just edited. If the deletion fails, then it is silently ignored.

  • allowed_mentions (Optional[AllowedMentions]) –

    Controls the mentions being processed in this message. If this is passed, then the object is merged with Client.allowed_mentions. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set in Client.allowed_mentions. If no object is passed at all then the defaults given by Client.allowed_mentions are used instead.

    New in version 1.4.

  • view (Optional[View]) –

    The updated view to update this message with. This cannot be mixed with components. If None is passed then the view is removed.

    New in version 2.0.

  • components (Union[disnake.ui.ActionRow, disnake.ui.WrappedComponent, List[Union[disnake.ui.ActionRow, disnake.ui.WrappedComponent, List[disnake.ui.WrappedComponent]]]]) –

    The updated components to update this message with. This cannot be mixed with view. If None is passed then the components are removed.

    New in version 2.4.

Raises:
  • HTTPException – Editing the message failed.

  • Forbidden – Tried to suppress embeds on a message without permissions or edited a message’s content or embed that isn’t yours.

  • TypeError – You specified both embed and embeds, or file and files, or view and components.

Returns:

The message that was edited.

Return type:

Message

await publish()[source]

This function is a coroutine.

Publishes this message to your announcement channel.

You must have the send_messages permission to do this.

If the message is not your own then the manage_messages permission is also needed.

Raises:
  • Forbidden – You do not have the proper permissions to publish this message.

  • HTTPException – Publishing the message failed.

await pin(*, reason=None)[source]

This function is a coroutine.

Pins the message.

You must have the manage_messages permission to do this in a non-private channel context.

Parameters:

reason (Optional[str]) –

The reason for pinning the message. Shows up on the audit log.

New in version 1.4.

Raises:
  • Forbidden – You do not have permissions to pin the message.

  • NotFound – The message or channel was not found or deleted.

  • HTTPException – Pinning the message failed, probably due to the channel having more than 50 pinned messages.

await unpin(*, reason=None)[source]

This function is a coroutine.

Unpins the message.

You must have the manage_messages permission to do this in a non-private channel context.

Parameters:

reason (Optional[str]) –

The reason for unpinning the message. Shows up on the audit log.

New in version 1.4.

Raises:
  • Forbidden – You do not have permissions to unpin the message.

  • NotFound – The message or channel was not found or deleted.

  • HTTPException – Unpinning the message failed.

await add_reaction(emoji)[source]

This function is a coroutine.

Adds a reaction to the message.

The emoji may be a unicode emoji or a custom guild Emoji.

You must have the read_message_history permission to use this. If nobody else has reacted to the message using this emoji, the add_reactions permission is required.

Changed in version 2.6: Raises TypeError instead of InvalidArgument.

Parameters:

emoji (Union[Emoji, Reaction, PartialEmoji, str]) – The emoji to react with.

Raises:
  • HTTPException – Adding the reaction failed.

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

  • NotFound – The emoji you specified was not found.

  • TypeError – The emoji parameter is invalid.

await remove_reaction(emoji, member)[source]

This function is a coroutine.

Removes a reaction by the member from the message.

The emoji may be a unicode emoji or a custom guild Emoji.

If the reaction is not your own (i.e. member parameter is not you) then the manage_messages permission is needed.

The member parameter must represent a member and meet the abc.Snowflake abc.

Changed in version 2.6: Raises TypeError instead of InvalidArgument.

Parameters:
Raises:
  • HTTPException – Removing the reaction failed.

  • Forbidden – You do not have the proper permissions to remove the reaction.

  • NotFound – The member or emoji you specified was not found.

  • TypeError – The emoji parameter is invalid.

await clear_reaction(emoji)[source]

This function is a coroutine.

Clears a specific reaction from the message.

The emoji may be a unicode emoji or a custom guild Emoji.

You need the manage_messages permission to use this.

New in version 1.3.

Changed in version 2.6: Raises TypeError instead of InvalidArgument.

Parameters:

emoji (Union[Emoji, Reaction, PartialEmoji, str]) – The emoji to clear.

Raises:
  • HTTPException – Clearing the reaction failed.

  • Forbidden – You do not have the proper permissions to clear the reaction.

  • NotFound – The emoji you specified was not found.

  • TypeError – The emoji parameter is invalid.

await clear_reactions()[source]

This function is a coroutine.

Removes all the reactions from the message.

You need the manage_messages permission to use this.

Raises:
  • HTTPException – Removing the reactions failed.

  • Forbidden – You do not have the proper permissions to remove all the reactions.

await create_thread(*, name, auto_archive_duration=None, slowmode_delay=None, reason=None)[source]

This function is a coroutine.

Creates a public thread from this message.

You must have create_public_threads in order to create a public thread from a message.

The channel this message belongs in must be a TextChannel.

New in version 2.0.

Changed in version 2.6: Raises TypeError instead of InvalidArgument.

Parameters:
  • name (str) – The name of the thread.

  • auto_archive_duration (Union[int, ThreadArchiveDuration]) – The duration in minutes before a thread is automatically archived for inactivity. If not provided, the channel’s default auto archive duration is used. Must be one of 60, 1440, 4320, or 10080.

  • slowmode_delay (Optional[int]) –

    Specifies the slowmode rate limit for users in this thread, in seconds. A value of 0 disables slowmode. The maximum value possible is 21600. If set to None or not provided, slowmode is inherited from the parent channel.

    New in version 2.3.

  • reason (Optional[str]) –

    The reason for creating the thread. Shows up on the audit log.

    New in version 2.5.

Raises:
  • Forbidden – You do not have permissions to create a thread.

  • HTTPException – Creating the thread failed.

  • TypeError – This message does not have guild info attached.

Returns:

The created thread.

Return type:

Thread

await reply(content=None, *, fail_if_not_exists=True, **kwargs)[source]

This function is a coroutine.

A shortcut method to abc.Messageable.send() to reply to the Message.

New in version 1.6.

Changed in version 2.3: Added fail_if_not_exists keyword argument. Defaults to True.

Changed in version 2.6: Raises TypeError or ValueError instead of InvalidArgument.

Parameters:

fail_if_not_exists (bool) –

Whether replying using the message reference should raise HTTPException if the message no longer exists or Discord could not fetch the message.

New in version 2.3.

Raises:
  • HTTPException – Sending the message failed.

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

  • TypeError – You specified both embed and embeds, or file and files, or view and components.

  • ValueError – The files or embeds list is too large.

Returns:

The message that was sent.

Return type:

Message

to_reference(*, fail_if_not_exists=True)[source]

Creates a MessageReference from the current message.

New in version 1.6.

Parameters:

fail_if_not_exists (bool) –

Whether replying using the message reference should raise HTTPException if the message no longer exists or Discord could not fetch the message.

New in version 1.7.

Returns:

The reference to this message.

Return type:

MessageReference

APISlashCommand
class disnake.APISlashCommand[source]

A slash command returned by the API.

New in version 2.4.

name

The slash command’s name.

Type:

str

name_localizations

Localizations for name.

New in version 2.5.

Type:

LocalizationValue

description

The slash command’s description.

Type:

str

description_localizations

Localizations for description.

New in version 2.5.

Type:

LocalizationValue

dm_permission

Whether this command can be used in DMs.

New in version 2.5.

Type:

bool

id

The slash command’s ID.

Type:

int

options

The list of options the slash command has.

Type:

List[Option]

application_id

The application ID this command belongs to.

Type:

int

guild_id

The ID of the guild this slash command is enabled in, or None if it’s global.

Type:

Optional[int]

version

Autoincrementing version identifier updated during substantial record changes.

Type:

int

add_option(name, description=None, type=None, required=False, choices=None, options=None, channel_types=None, autocomplete=False, min_value=None, max_value=None, min_length=None, max_length=None)[source]

Adds an option to the current list of options, parameters are the same as for Option

property default_member_permissions[source]

The default required member permissions for this command. A member must have all these permissions to be able to invoke the command in a guild.

This is a default value, the set of users/roles that may invoke this command can be overridden by moderators on a guild-specific basis, disregarding this setting.

If None is returned, it means everyone can use the command by default. If an empty Permissions object is returned (that is, all permissions set to False), this means no one can use the command.

New in version 2.5.

Type:

Optional[Permissions]

APIUserCommand
class disnake.APIUserCommand[source]

A user context menu command returned by the API.

New in version 2.4.

name

The user command’s name.

Type:

str

name_localizations

Localizations for name.

New in version 2.5.

Type:

LocalizationValue

dm_permission

Whether this command can be used in DMs.

New in version 2.5.

Type:

bool

id

The user command’s ID.

Type:

int

application_id

The application ID this command belongs to.

Type:

int

guild_id

The ID of the guild this user command is enabled in, or None if it’s global.

Type:

Optional[int]

version

Autoincrementing version identifier updated during substantial record changes.

Type:

int

property default_member_permissions[source]

The default required member permissions for this command. A member must have all these permissions to be able to invoke the command in a guild.

This is a default value, the set of users/roles that may invoke this command can be overridden by moderators on a guild-specific basis, disregarding this setting.

If None is returned, it means everyone can use the command by default. If an empty Permissions object is returned (that is, all permissions set to False), this means no one can use the command.

New in version 2.5.

Type:

Optional[Permissions]

APIMessageCommand
class disnake.APIMessageCommand[source]

A message context menu command returned by the API.

New in version 2.4.

name

The message command’s name.

Type:

str

name_localizations

Localizations for name.

New in version 2.5.

Type:

LocalizationValue

dm_permission

Whether this command can be used in DMs.

New in version 2.5.

Type:

bool

id

The message command’s ID.

Type:

int

application_id

The application ID this command belongs to.

Type:

int

guild_id

The ID of the guild this message command is enabled in, or None if it’s global.

Type:

Optional[int]

version

Autoincrementing version identifier updated during substantial record changes.

Type:

int

property default_member_permissions[source]

The default required member permissions for this command. A member must have all these permissions to be able to invoke the command in a guild.

This is a default value, the set of users/roles that may invoke this command can be overridden by moderators on a guild-specific basis, disregarding this setting.

If None is returned, it means everyone can use the command by default. If an empty Permissions object is returned (that is, all permissions set to False), this means no one can use the command.

New in version 2.5.

Type:

Optional[Permissions]

ApplicationCommandPermissions
Attributes
class disnake.ApplicationCommandPermissions[source]

Represents application command permissions for a role, user, or channel.

id

The ID of the role, user, or channel.

Type:

int

type

The type of the target.

Type:

ApplicationCommandPermissionType

permission

Whether to allow or deny the access to the application command.

Type:

bool

is_everyone()[source]

Whether this permission object is affecting the @everyone role.

New in version 2.5.

Return type:

bool

is_all_channels()[source]

Whether this permission object is affecting all channels.

New in version 2.5.

Return type:

bool

GuildApplicationCommandPermissions
class disnake.GuildApplicationCommandPermissions[source]

Represents application command permissions in a guild.

Changed in version 2.5: Can now also represent application-wide permissions that apply to every command by default.

id

The application command’s ID, or the application ID if these are application-wide permissions.

Type:

int

application_id

The application ID this command belongs to.

Type:

int

guild_id

The ID of the guild where these permissions are applied.

Type:

int

permissions

A list of ApplicationCommandPermissions.

Type:

List[ApplicationCommandPermissions]

Component
Attributes
class disnake.Component[source]

Represents a Discord Bot UI Kit Component.

Currently, the only components supported by Discord are:

This class is abstract and cannot be instantiated.

New in version 2.0.

type

The type of component.

Type:

ComponentType

ActionRow
Attributes
class disnake.ActionRow[source]

Represents an action row.

This is a component that holds up to 5 children components in a row.

This inherits from Component.

New in version 2.0.

type

The type of component.

Type:

ComponentType

children

The children components that this holds, if any.

Type:

List[Union[Button, SelectMenu, TextInput]]

Button
class disnake.Button[source]

Represents a button from the Discord Bot UI Kit.

This inherits from Component.

Note

The user constructible and usable type to create a button is disnake.ui.Button not this one.

New in version 2.0.

style

The style of the button.

Type:

ButtonStyle

custom_id

The ID of the button that gets received during an interaction. If this button is for a URL, it does not have a custom ID.

Type:

Optional[str]

url

The URL this button sends you to.

Type:

Optional[str]

disabled

Whether the button is disabled or not.

Type:

bool

label

The label of the button, if any.

Type:

Optional[str]

emoji

The emoji of the button, if available.

Type:

Optional[PartialEmoji]

SelectMenu
class disnake.SelectMenu[source]

Represents a select menu from the Discord Bot UI Kit.

A select menu is functionally the same as a dropdown, however on mobile it renders a bit differently.

Note

The user constructible and usable type to create a select menu is disnake.ui.Select not this one.

New in version 2.0.

custom_id

The ID of the select menu that gets received during an interaction.

Type:

Optional[str]

placeholder

The placeholder text that is shown if nothing is selected, if any.

Type:

Optional[str]

min_values

The minimum number of items that must be chosen for this select menu. Defaults to 1 and must be between 1 and 25.

Type:

int

max_values

The maximum number of items that must be chosen for this select menu. Defaults to 1 and must be between 1 and 25.

Type:

int

options

A list of options that can be selected in this select menu.

Type:

List[SelectOption]

disabled

Whether the select menu is disabled or not.

Type:

bool

TextInput
class disnake.TextInput[source]

Represents a text input from the Discord Bot UI Kit.

New in version 2.4.

Note

The user constructible and usable type to create a text input is disnake.ui.TextInput, not this one.

style

The style of the text input.

Type:

TextInputStyle

label

The label of the text input.

Type:

Optional[str]

custom_id

The ID of the text input that gets received during an interaction.

Type:

str

placeholder

The placeholder text that is shown if nothing is entered.

Type:

Optional[str]

value

The pre-filled text of the text input.

Type:

Optional[str]

required

Whether the text input is required. Defaults to True.

Type:

bool

min_length

The minimum length of the text input.

Type:

Optional[int]

max_length

The maximum length of the text input.

Type:

Optional[int]

DeletedReferencedMessage
Attributes
class disnake.DeletedReferencedMessage[source]

A special sentinel type that denotes whether the resolved message referenced message had since been deleted.

The purpose of this class is to separate referenced messages that could not be fetched and those that were previously fetched but have since been deleted.

New in version 1.6.

property id[source]

The message ID of the deleted referenced message.

Type:

int

property channel_id[source]

The channel ID of the deleted referenced message.

Type:

int

property guild_id[source]

The guild ID of the deleted referenced message.

Type:

Optional[int]

Reaction
Attributes
Methods
class disnake.Reaction[source]

Represents a reaction to a message.

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

x == y

Checks if two reactions are equal. This works by checking if the emoji is the same. So two messages with the same reaction will be considered “equal”.

x != y

Checks if two reactions are not equal.

hash(x)

Returns the reaction’s hash.

str(x)

Returns the string form of the reaction’s emoji.

emoji

The reaction emoji. May be a custom emoji, or a unicode emoji.

Type:

Union[Emoji, PartialEmoji, str]

count

Number of times this reaction was made

Type:

int

me

If the user sent this reaction.

Type:

bool

message

The message this reaction belongs to.

Type:

Message

async for ... in users(*, limit=None, after=None)[source]

Returns an AsyncIterator representing the users that have reacted to the message.

The after parameter must represent a member and meet the abc.Snowflake abc.

Examples

Usage

# We do not actually recommend doing this.
async for user in reaction.users():
    await channel.send(f'{user} has reacted with {reaction.emoji}!')

Flattening into a list:

users = await reaction.users().flatten()
# users is now a list of User...
winner = random.choice(users)
await channel.send(f'{winner} has won the raffle.')
Parameters:
  • limit (Optional[int]) – The maximum number of results to return. If not provided, returns all the users who reacted to the message.

  • after (Optional[abc.Snowflake]) – For pagination, reactions are sorted by member.

Raises:

HTTPException – Getting the users for the reaction failed.

Yields:

Union[User, Member] – The member (if retrievable) or the user that has reacted to this message. The case where it can be a Member is in a guild message context. Sometimes it can be a User if the member has left the guild.

is_custom_emoji()[source]

Whether the emoji is a custom emoji.

Return type:

bool

await remove(user)[source]

This function is a coroutine.

Removes the reaction by the provided User from the message.

If the reaction is not your own (i.e. user parameter is not you) then the manage_messages permission is needed.

The user parameter must represent a user or member and meet the abc.Snowflake abc.

Parameters:

user (abc.Snowflake) – The user or member from which to remove the reaction.

Raises:
  • HTTPException – Removing the reaction failed.

  • Forbidden – You do not have the proper permissions to remove the reaction.

  • NotFound – The user you specified, or the reaction’s message was not found.

await clear()[source]

This function is a coroutine.

Clears this reaction from the message.

You need the manage_messages permission to use this.

New in version 1.3.

Changed in version 2.6: Raises TypeError instead of InvalidArgument.

Raises:
  • HTTPException – Clearing the reaction failed.

  • Forbidden – You do not have the proper permissions to clear the reaction.

  • NotFound – The emoji you specified was not found.

  • TypeError – The emoji parameter is invalid.

Guild
class disnake.Guild[source]

Represents a Discord guild.

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

x == y

Checks if two guilds are equal.

x != y

Checks if two guilds are not equal.

hash(x)

Returns the guild’s hash.

str(x)

Returns the guild’s name.

name

The guild’s name.

Type:

str

emojis

All emojis that the guild owns.

Type:

Tuple[Emoji, …]

stickers

All stickers that the guild owns.

New in version 2.0.

Type:

Tuple[GuildSticker, …]

afk_timeout

The timeout to get sent to the AFK channel.

Type:

int

afk_channel

The channel that denotes the AFK channel. None if it doesn’t exist.

Type:

Optional[VoiceChannel]

id

The guild’s ID.

Type:

int

owner_id

The guild owner’s ID. Use Guild.owner if you need a Member object instead.

Type:

int

unavailable

Whether the guild is unavailable. If this is True then the reliability of other attributes outside of Guild.id is slim and they might all be None. It is best to not do anything with the guild if it is unavailable.

Check on_guild_unavailable() and on_guild_available() events.

Type:

bool

max_presences

The maximum amount of presences for the guild.

Type:

Optional[int]

max_members

The maximum amount of members for the guild.

Note

This attribute is only available via Client.fetch_guild().

Type:

Optional[int]

max_video_channel_users

The maximum amount of users in a video channel.

New in version 1.4.

Type:

Optional[int]

description

The guild’s description.

Type:

Optional[str]

mfa_level

Indicates the guild’s two-factor authentication level. If this value is 0 then the guild does not require 2FA for their administrative members to take moderation actions. If the value is 1, then 2FA is required.

Type:

int

verification_level

The guild’s verification level.

Type:

VerificationLevel

explicit_content_filter

The guild’s explicit content filter.

Type:

ContentFilter

default_notifications

The guild’s notification settings.

Type:

NotificationLevel

features

A list of features that the guild has. The features that a guild can have are subject to arbitrary change by Discord.

A partial list of features is below:

  • ANIMATED_BANNER: Guild can upload an animated banner.

  • ANIMATED_ICON: Guild can upload an animated icon.

  • AUTO_MODERATION: Guild has set up auto moderation rules.

  • BANNER: Guild can upload and use a banner. (i.e. banner)

  • COMMUNITY: Guild is a community server.

  • DISCOVERABLE: Guild shows up in Server Discovery.

  • ENABLED_DISCOVERABLE_BEFORE: Guild had Server Discovery enabled at least once.

  • FEATURABLE: Guild is able to be featured in Server Discovery.

  • HAS_DIRECTORY_ENTRY: Guild is listed in a student hub.

  • HUB: Guild is a student hub.

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

  • INVITES_DISABLED: Guild has paused invites, preventing new users from joining.

  • LINKED_TO_HUB: Guild is linked to a student hub.

  • MEMBER_VERIFICATION_GATE_ENABLED: Guild has Membership Screening enabled.

  • MONETIZATION_ENABLED: Guild has enabled monetization.

  • MORE_EMOJI: Guild has increased custom emoji slots.

  • MORE_STICKERS: Guild has increased custom sticker slots.

  • NEWS: Guild can create news channels.

  • NEW_THREAD_PERMISSIONS: Guild is using the new thread permission system.

  • PARTNERED: Guild is a partnered server.

  • PREVIEW_ENABLED: Guild can be viewed before being accepted via Membership Screening.

  • PRIVATE_THREADS: Guild has access to create private threads.

  • ROLE_ICONS: Guild has access to role icons.

  • SEVEN_DAY_THREAD_ARCHIVE: Guild has access to the seven day archive time for threads (no longer has any effect).

  • TEXT_IN_VOICE_ENABLED: Guild has text in voice channels enabled (no longer has any effect).

  • THREE_DAY_THREAD_ARCHIVE: Guild has access to the three day archive time for threads (no longer has any effect).

  • THREADS_ENABLED: Guild has access to threads (no longer has any effect).

  • TICKETED_EVENTS_ENABLED: Guild has enabled ticketed events (no longer has any effect).

  • VANITY_URL: Guild can have a vanity invite URL (e.g. discord.gg/disnake).

  • VERIFIED: Guild is a verified server.

  • VIP_REGIONS: Guild has VIP voice regions.

  • WELCOME_SCREEN_ENABLED: Guild has enabled the welcome screen.

Type:

List[str]

premium_progress_bar_enabled

Whether the server boost progress bar is enabled.

Type:

bool

premium_tier

The premium tier for this guild. Corresponds to “Nitro Server” in the official UI. The number goes from 0 to 3 inclusive.

Type:

int

premium_subscription_count

The number of “boosts” this guild currently has.

Type:

int

preferred_locale

The preferred locale for the guild. Used when filtering Server Discovery results to a specific language.

Changed in version 2.5: Changed to Locale instead of str.

Type:

Locale

nsfw_level

The guild’s NSFW level.

New in version 2.0.

Type:

NSFWLevel

approximate_member_count

The approximate number of members in the guild. Only available for manually fetched guilds.

New in version 2.3.

Type:

Optional[int]

approximate_presence_count

The approximate number of members currently active in the guild. This includes idle, dnd, online, and invisible members. Offline members are excluded. Only available for manually fetched guilds.

New in version 2.3.

Type:

Optional[int]

widget_enabled

Whether the widget is enabled.

New in version 2.5.

Note

This value is unreliable and will only be set after the guild was updated at least once. Avoid using this and use widget_settings() instead.

Type:

Optional[bool]

widget_channel_id

The widget channel ID, if set.

New in version 2.5.

Note

This value is unreliable and will only be set after the guild was updated at least once. Avoid using this and use widget_settings() instead.

Type:

Optional[int]

vanity_url_code

The vanity invite code for this guild, if set.

To get a full Invite object, see Guild.vanity_invite.

New in version 2.5.

Type:

Optional[str]

async for ... in fetch_members(*, limit=1000, after=None)[source]

Retrieves an AsyncIterator that enables receiving the guild’s members. In order to use this, Intents.members() must be enabled.

Note

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

New in version 1.3.

All parameters are optional.

Parameters:
  • limit (Optional[int]) – The number of members to retrieve. Defaults to 1000. Pass None to fetch all members. Note that this is potentially slow.

  • after (Optional[Union[abc.Snowflake, datetime.datetime]]) – Retrieve members after this date or object. If a 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:
Yields:

Member – The member with the member data parsed.

Examples

Usage

async for member in guild.fetch_members(limit=150):
    print(member.name)

Flattening into a list

members = await guild.fetch_members(limit=150).flatten()
# members is now a list of Member...
async for ... in audit_logs(*, limit=100, before=None, after=None, user=None, action=None)[source]

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

You must have view_audit_log permission to use this.

Entries are always returned in order from newest to oldest, regardless of the before and after parameters.

Examples

Getting the first 100 entries:

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

Getting entries for a specific action:

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

Getting entries made by a specific user:

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

  • before (Union[abc.Snowflake, datetime.datetime]) – Retrieve entries before this date or entry. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.

  • after (Union[abc.Snowflake, datetime.datetime]) – Retrieve entries after this date or entry. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.

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

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

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

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

Yields:

AuditLogEntry – The audit log entry.

get_command(application_command_id, /)[source]

Gets a cached application command matching the specified ID.

Parameters:

application_command_id (int) – The application command ID to search for.

Returns:

The application command if found, or None otherwise.

Return type:

Optional[Union[APIUserCommand, APIMessageCommand, APISlashCommand]]

get_command_named(name, /)[source]

Gets a cached application command matching the specified name.

Parameters:

name (str) – The application command name to search for.

Returns:

The application command if found, or None otherwise.

Return type:

Optional[Union[APIUserCommand, APIMessageCommand, APISlashCommand]]

property channels[source]

A list of channels that belong to this guild.

Type:

List[abc.GuildChannel]

property threads[source]

A list of threads that you have permission to view.

New in version 2.0.

Type:

List[Thread]

property large[source]

Whether the guild is a ‘large’ guild.

A large guild is defined as having more than large_threshold count members, which for this library is set to the maximum of 250.

Type:

bool

property voice_channels[source]

A list of voice channels that belong to this guild.

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

Type:

List[VoiceChannel]

property stage_channels[source]

A list of stage channels that belong to this guild.

New in version 1.7.

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

Type:

List[StageChannel]

property forum_channels[source]

A list of forum channels that belong to this guild.

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

New in version 2.5.

Type:

List[ForumChannel]

property me[source]

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

Type:

Member

property voice_client[source]

Returns the VoiceProtocol associated with this guild, if any.

Type:

Optional[VoiceProtocol]

property text_channels[source]

A list of text channels that belong to this guild.

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

Type:

List[TextChannel]

property categories[source]

A list of categories that belong to this guild.

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

Type:

List[CategoryChannel]

by_category()[source]

Returns every CategoryChannel and their associated channels.

These channels and categories are sorted in the official Discord UI order.

If the channels do not have a category, then the first element of the tuple is None.

Returns:

The categories and their associated channels.

Return type:

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

get_channel_or_thread(channel_id, /)[source]

Returns a channel or thread with the given ID.

New in version 2.0.

Parameters:

channel_id (int) – The ID to search for.

Returns:

The returned channel or thread or None if not found.

Return type:

Optional[Union[Thread, abc.GuildChannel]]

get_channel(channel_id, /)[source]

Returns a channel with the given ID.

Note

This does not search for threads.

Parameters:

channel_id (int) – The ID to search for.

Returns:

The returned channel or None if not found.

Return type:

Optional[abc.GuildChannel]

get_thread(thread_id, /)[source]

Returns a thread with the given ID.

New in version 2.0.

Parameters:

thread_id (int) – The ID to search for.

Returns:

The returned thread or None if not found.

Return type:

Optional[Thread]

property system_channel[source]

Returns the guild’s channel used for system messages.

If no channel is set, then this returns None.

Type:

Optional[TextChannel]

property system_channel_flags[source]

Returns the guild’s system channel settings.

Type:

SystemChannelFlags

property rules_channel[source]

Return’s the guild’s channel used for the rules. The guild must be a Community guild.

If no channel is set, then this returns None.

New in version 1.3.

Type:

Optional[TextChannel]

property public_updates_channel[source]

Return’s the guild’s channel where admins and moderators of the guild receive notices from Discord. The guild must be a Community guild.

If no channel is set, then this returns None.

New in version 1.4.

Type:

Optional[TextChannel]

property emoji_limit[source]

The maximum number of emoji slots this guild has.

Type:

int

property sticker_limit[source]

The maximum number of sticker slots this guild has.

New in version 2.0.

Type:

int

property bitrate_limit[source]

The maximum bitrate for voice channels this guild can have. For stage channels, the maximum bitrate is 64000.

Type:

float

property filesize_limit[source]

The maximum number of bytes files can have when uploaded to this guild.

Type:

int

property members[source]

A list of members that belong to this guild.

Type:

List[Member]

get_member(user_id, /)[source]

Returns a member with the given ID.

Parameters:

user_id (int) – The ID to search for.

Returns:

The member or None if not found.

Return type:

Optional[Member]

property premium_subscribers[source]

A list of members who have “boosted” this guild.

Type:

List[Member]

property roles[source]

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

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

Type:

List[Role]

get_role(role_id, /)[source]

Returns a role with the given ID.

Parameters:

role_id (int) – The ID to search for.

Returns:

The role or None if not found.

Return type:

Optional[Role]

property default_role[source]

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

Type:

Role

property premium_subscriber_role[source]

Gets the premium subscriber role, AKA “boost” role, in this guild, if any.

New in version 1.6.

Type:

Optional[Role]

property self_role[source]

Gets the role associated with this client’s user, if any.

New in version 1.6.

Type:

Optional[Role]

property stage_instances[source]

Returns a list of the guild’s stage instances that are currently running.

New in version 2.0.

Type:

List[StageInstance]

get_stage_instance(stage_instance_id, /)[source]

Returns a stage instance with the given ID.

New in version 2.0.

Parameters:

stage_instance_id (int) – The ID to search for.

Returns:

The stage instance or None if not found.

Return type:

Optional[StageInstance]

property scheduled_events[source]

Returns a list of existing guild scheduled events.

New in version 2.3.

Type:

List[GuildScheduledEvent]

get_scheduled_event(event_id, /)[source]

Returns a guild scheduled event with the given ID.

New in version 2.3.

Parameters:

event_id (int) – The ID to search for.

Returns:

The guild scheduled event or None if not found.

Return type:

Optional[GuildScheduledEvent]

property owner[source]

Returns the member that owns the guild.

Type:

Optional[Member]

property icon[source]

Returns the guild’s icon asset, if available.

Type:

Optional[Asset]

property banner[source]

Returns the guild’s banner asset, if available.

Type:

Optional[Asset]

property splash[source]

Returns the guild’s invite splash asset, if available.

Type:

Optional[Asset]

property discovery_splash[source]

Returns the guild’s discovery splash asset, if available.

Type:

Optional[Asset]

property member_count[source]

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

Warning

Due to a Discord limitation, in order for this attribute to remain up-to-date and accurate, it requires Intents.members to be specified.

Type:

int

property region[source]

The region the guild belongs on.

Deprecated since version 2.5: VoiceRegion is no longer set on the guild, and is set on the individual voice channels instead. See VoiceChannel.rtc_region and StageChannel.rtc_region instead.

Changed in version 2.5: No longer a VoiceRegion instance.

Type:

Optional[str]

property chunked[source]

Whether the guild is “chunked”.

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

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

Type:

bool

property shard_id[source]

Returns the shard ID for this guild if applicable.

Type:

int

property created_at[source]

Returns the guild’s creation time in UTC.

Type:

datetime.datetime

get_member_named(name, /)[source]

Returns the first member found that matches the name provided.

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

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

If no member is found, None is returned.

Parameters:

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

Returns:

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

Return type:

Optional[Member]

await create_text_channel(name, *, reason=None, category=None, position=..., topic=..., slowmode_delay=..., default_auto_archive_duration=..., nsfw=..., news=..., overwrites=...)[source]

This function is a coroutine.

Creates a TextChannel for the guild.

You need manage_channels permission to create the channel.

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

Note

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

Changed in version 2.6: Raises TypeError instead of InvalidArgument.

Examples

Creating a basic channel:

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

Creating a “secret” channel:

overwrites = {
    guild.default_role: disnake.PermissionOverwrite(view_channel=False),
    guild.me: disnake.PermissionOverwrite(view_channel=True)
}

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

  • overwrites (Dict[Union[Role, Member], PermissionOverwrite]) – A dict of target (either a role or a member) to PermissionOverwrite to apply upon creation of a channel. Useful for creating secret channels.

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

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

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

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

  • default_auto_archive_duration (Union[int, ThreadArchiveDuration]) –

    The default auto archive duration in minutes for threads created in this channel. Must be one of 60, 1440, 4320, or 10080.

    New in version 2.5.

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

  • news (bool) –

    Whether to make a news channel. News channels are text channels that can be followed. This is only available to guilds that contain NEWS in Guild.features.

    New in version 2.5.

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

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

  • HTTPException – Creating the channel failed.

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

Returns:

The channel that was just created.

Return type:

TextChannel

await create_voice_channel(name, *, reason=None, category=None, position=..., bitrate=..., user_limit=..., rtc_region=..., video_quality_mode=..., nsfw=..., slowmode_delay=..., overwrites=...)[source]

This function is a coroutine.

This is similar to create_text_channel() except makes a VoiceChannel instead.

Changed in version 2.6: Raises TypeError instead of InvalidArgument.

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

  • overwrites (Dict[Union[Role, Member], PermissionOverwrite]) – A dict of target (either a role or a member) to PermissionOverwrite to apply upon creation of a channel. Useful for creating secret channels.

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

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

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

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

  • rtc_region (Optional[Union[str, VoiceRegion]]) –

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

    New in version 1.7.

  • video_quality_mode (VideoQualityMode) –

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

    New in version 2.0.

  • nsfw (bool) –

    Whether to mark the channel as NSFW or not.

    New in version 2.5.

  • slowmode_delay (int) –

    Specifies the slowmode rate limit for users in this channel, in seconds. A value of 0 disables slowmode. The maximum value possible is 21600. If not provided, slowmode is disabled.

    New in version 2.6.

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

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

  • HTTPException – Creating the channel failed.

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

Returns:

The channel that was just created.

Return type:

VoiceChannel

await create_stage_channel(name, *, topic=..., position=..., bitrate=..., overwrites=..., category=None, rtc_region=..., reason=None)[source]

This function is a coroutine.

This is similar to create_text_channel() except makes a StageChannel instead.

New in version 1.7.

Changed in version 2.6: Raises TypeError instead of InvalidArgument.

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

  • topic (Optional[str]) –

    The channel’s topic.

    Changed in version 2.5: This is no longer required to be provided.

  • overwrites (Dict[Union[Role, Member], PermissionOverwrite]) – A dict of target (either a role or a member) to PermissionOverwrite to apply upon creation of a channel. Useful for creating secret channels.

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

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

  • bitrate (int) –

    The channel’s preferred audio bitrate in bits per second.

    New in version 2.6.

  • rtc_region (Optional[Union[str, VoiceRegion]]) –

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

    New in version 2.5.

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

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

  • HTTPException – Creating the channel failed.

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

Returns:

The channel that was just created.

Return type:

StageChannel

await create_forum_channel(name, *, topic=None, category=None, position=..., slowmode_delay=..., default_thread_slowmode_delay=..., default_auto_archive_duration=None, nsfw=..., overwrites=..., available_tags=None, default_reaction=None, default_sort_order=None, reason=None)[source]

This function is a coroutine.

This is similar to create_text_channel() except makes a ForumChannel instead.

New in version 2.5.

Changed in version 2.6: Raises TypeError instead of InvalidArgument.

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

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

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

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

  • slowmode_delay (int) – Specifies the slowmode rate limit at which users can create threads in this channel, in seconds. A value of 0 disables slowmode. The maximum value possible is 21600. If not provided, slowmode is disabled.

  • default_thread_slowmode_delay (int) –

    Specifies the slowmode rate limit at which users can send messages in newly created threads in this channel, in seconds. A value of 0 disables slowmode by default. The maximum value possible is 21600. If not provided, slowmode is disabled.

    New in version 2.6.

  • default_auto_archive_duration (Union[int, ThreadArchiveDuration]) – The default auto archive duration in minutes for threads created in this channel. Must be one of 60, 1440, 4320, or 10080.

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

  • overwrites (Dict[Union[Role, Member], PermissionOverwrite]) – A dict of target (either a role or a member) to PermissionOverwrite to apply upon creation of a channel. Useful for creating secret channels.

  • available_tags (Optional[Sequence[ForumTag]]) –

    The tags available for threads in this channel.

    New in version 2.6.

  • default_reaction (Optional[Union[str, Emoji, PartialEmoji]]) –

    The default emoji shown for reacting to threads.

    New in version 2.6.

  • default_sort_order (Optional[ThreadSortOrder]) –

    The default sort order of threads in this channel.

    New in version 2.6.

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

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

  • HTTPException – Creating the channel failed.

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

Returns:

The channel that was just created.

Return type:

ForumChannel

await create_category(name, *, overwrites=..., reason=None, position=...)[source]

This function is a coroutine.

Same as create_text_channel() except makes a CategoryChannel instead.

Note

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

Changed in version 2.6: Raises TypeError instead of InvalidArgument.

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

  • overwrites (Dict[Union[Role, Member], PermissionOverwrite]) – A dict of target (either a role or a member) to PermissionOverwrite which can be synced to channels.

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

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

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

  • HTTPException – Creating the channel failed.

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

Returns:

The channel that was just created.

Return type:

CategoryChannel

await create_category_channel(name, *, overwrites=..., reason=None, position=...)[source]

This function is a coroutine.

Same as create_text_channel() except makes a CategoryChannel instead.

Note

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

Changed in version 2.6: Raises TypeError instead of InvalidArgument.

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

  • overwrites (Dict[Union[Role, Member], PermissionOverwrite]) – A dict of target (either a role or a member) to PermissionOverwrite which can be synced to channels.

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

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

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

  • HTTPException – Creating the channel failed.

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

Returns:

The channel that was just created.

Return type:

CategoryChannel

await leave()[source]

This function is a coroutine.

Leaves the guild.

Note

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

Raises:

HTTPException – Leaving the guild failed.

await delete()[source]

This function is a coroutine.

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

Raises:
await edit(*, reason=..., name=..., description=..., icon=..., banner=..., splash=..., discovery_splash=..., community=..., invites_disabled=..., afk_channel=..., owner=..., afk_timeout=..., default_notifications=..., verification_level=..., explicit_content_filter=..., vanity_code=..., system_channel=..., system_channel_flags=..., preferred_locale=..., rules_channel=..., public_updates_channel=..., premium_progress_bar_enabled=...)[source]

This function is a coroutine.

Edits the guild.

You must have manage_guild permission to use this.

Changed in version 1.4: The rules_channel and public_updates_channel keyword-only parameters were added.

Changed in version 2.0: The discovery_splash and community keyword-only parameters were added.

Changed in version 2.0: The newly updated guild is returned.

Changed in version 2.5: Removed the region parameter. Use VoiceChannel.edit() or StageChannel.edit() with rtc_region instead.

Changed in version 2.6: Raises TypeError or ValueError instead of InvalidArgument.

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

  • description (Optional[str]) – The new description of the guild. Could be None for no description. This is only available to guilds that contain COMMUNITY in Guild.features.

  • icon (Optional[Union[bytes, Asset, Emoji, PartialEmoji, StickerItem, Sticker]]) –

    The new guild icon. Only PNG/JPG is supported. GIF is only available to guilds that contain ANIMATED_ICON in Guild.features. Could be None to denote removal of the icon.

    Changed in version 2.5: Now accepts various resource types in addition to bytes.

  • banner (Optional[Union[bytes, Asset, Emoji, PartialEmoji, StickerItem, Sticker]]) –

    The new guild banner. GIF is only available to guilds that contain ANIMATED_BANNER in Guild.features. Could be None to denote removal of the banner. This is only available to guilds that contain BANNER in Guild.features.

    Changed in version 2.5: Now accepts various resource types in addition to bytes.

  • splash (Optional[Union[bytes, Asset, Emoji, PartialEmoji, StickerItem, Sticker]]) –

    The new guild invite splash. Only PNG/JPG is supported. Could be None to denote removing the splash. This is only available to guilds that contain INVITE_SPLASH in Guild.features.

    Changed in version 2.5: Now accepts various resource types in addition to bytes.

  • discovery_splash (Optional[Union[bytes, Asset, Emoji, PartialEmoji, StickerItem, Sticker]]) –

    The new guild discovery splash. Only PNG/JPG is supported. Could be None to denote removing the splash. This is only available to guilds that contain DISCOVERABLE in Guild.features.

    Changed in version 2.5: Now accepts various resource types in addition to bytes.

  • community (bool) – Whether the guild should be a Community guild. If set to True, both rules_channel and public_updates_channel parameters are required.

  • invites_disabled (bool) –

    Whether the guild has paused invites, preventing new users from joining.

    This is only available to guilds that contain COMMUNITY in Guild.features.

    This cannot be changed at the same time as the community feature due a Discord API limitation.

    New in version 2.6.

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

  • afk_timeout (int) – The number of seconds until someone is moved to the AFK channel. This can be set to 60, 300, 900, 1800, and 3600.

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

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

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

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

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

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

  • system_channel_flags (SystemChannelFlags) – The new system channel settings to use with the new system channel.

  • preferred_locale (Locale) –

    The new preferred locale for the guild. Used as the primary language in the guild.

    Changed in version 2.5: Changed to Locale instead of str.

  • rules_channel (Optional[TextChannel]) – The new channel that is used for rules. This is only available to guilds that contain COMMUNITY in Guild.features. Could be None for no rules channel.

  • public_updates_channel (Optional[TextChannel]) – The new channel that is used for public updates from Discord. This is only available to guilds that contain COMMUNITY in Guild.features. Could be None for no public updates channel.

  • premium_progress_bar_enabled (bool) – Whether the server boost progress bar is enabled.

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

Raises:
  • NotFound – At least one of the assets (icon, banner, splash or discovery_splash) couldn’t be found.

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

  • HTTPException – Editing the guild failed.

  • TypeError – At least one of the assets (icon, banner, splash or discovery_splash) is a lottie sticker (see Sticker.read()), or one of the parameters default_notifications, verification_level, explicit_content_filter, or system_channel_flags was of the incorrect type.

  • ValueErrorcommunity was set without setting both rules_channel and public_updates_channel parameters, or if you are not the owner of the guild and request an ownership transfer, or the image format passed in to icon is invalid, or both community and invites_disabled were provided.

Returns:

The newly updated guild. Note that this has the same limitations as mentioned in Client.fetch_guild() and may not have full data.

Return type:

Guild

await fetch_channels()[source]

This function is a coroutine.

Retrieves all abc.GuildChannel that the guild has.

Note

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

New in version 1.2.

Raises:
Returns:

All channels that the guild has.

Return type:

Sequence[abc.GuildChannel]

await active_threads()[source]

This function is a coroutine.

Returns a list of active Thread that the client can access.

This includes both private and public threads.

New in version 2.0.

Raises:

HTTPException – The request to get the active threads failed.

Returns:

The active threads.

Return type:

List[Thread]

await fetch_scheduled_events(*, with_user_count=False)[source]

This function is a coroutine.

Retrieves a list of all GuildScheduledEvent instances that the guild has.

New in version 2.3.

Parameters:

with_user_count (bool) – Whether to include number of users subscribed to each event.

Raises:

HTTPException – Retrieving the guild scheduled events failed.

Returns:

The existing guild scheduled events.

Return type:

List[GuildScheduledEvent]

await fetch_scheduled_event(event_id, *, with_user_count=False)[source]

This function is a coroutine.

Retrieves a GuildScheduledEvent with the given ID.

New in version 2.3.

Parameters:
  • event_id (int) – The ID to look for.

  • with_user_count (bool) – Whether to include number of users subscribed to the event.

Raises:

HTTPException – Retrieving the guild scheduled event failed.

Returns:

The guild scheduled event.

Return type:

GuildScheduledEvent

await create_scheduled_event(*, name, scheduled_start_time, channel=..., entity_type=..., scheduled_end_time=..., privacy_level=..., entity_metadata=..., description=..., image=..., reason=None)[source]

This function is a coroutine.

Creates a GuildScheduledEvent.

Based on the channel/entity type, there are different restrictions regarding other parameter values, as shown in this table:

channel

entity_type

scheduled_end_time

entity_metadata with location

abc.Snowflake with type attribute being ChannelType.voice

voice (set automatically)

optional

unset

abc.Snowflake with type attribute being ChannelType.stage_voice

stage_instance (set automatically)

optional

unset

abc.Snowflake with missing/other type attribute

required

optional

unset

None

external (set automatically)

required

required

unset

external

required

required

New in version 2.3.

Changed in version 2.6: Now raises TypeError instead of ValueError for invalid parameter types.

Changed in version 2.6: Removed channel_id parameter in favor of channel.

Changed in version 2.6: Naive datetime parameters are now assumed to be in the local timezone instead of UTC.

Changed in version 2.6: Infer entity_type from channel if provided.

Parameters:
  • name (str) – The name of the guild scheduled event.

  • description (str) – The description of the guild scheduled event.

  • image (Union[bytes, Asset, Emoji, PartialEmoji, StickerItem, Sticker]) –

    The cover image of the guild scheduled event.

    New in version 2.4.

    Changed in version 2.5: Now accepts various resource types in addition to bytes.

  • channel (Optional[abc.Snowflake]) –

    The channel in which the guild scheduled event will be hosted. Passing in None assumes the entity_type to be GuildScheduledEventEntityType.external

    New in version 2.6.

  • privacy_level (GuildScheduledEventPrivacyLevel) – The privacy level of the guild scheduled event.

  • scheduled_start_time (datetime.datetime) – The time to schedule the guild scheduled event. If the datetime is naive, it is assumed to be local time.

  • scheduled_end_time (Optional[datetime.datetime]) – The time when the guild scheduled event is scheduled to end. If the datetime is naive, it is assumed to be local time.

  • entity_type (GuildScheduledEventEntityType) – The entity type of the guild scheduled event.

  • entity_metadata (GuildScheduledEventMetadata) – The entity metadata of the guild scheduled event.

  • reason (Optional[str]) – The reason for creating the guild scheduled event. Shows up on the audit log.

Raises:
  • NotFound – The image asset couldn’t be found.

  • HTTPException – The request failed.

  • TypeError – The image asset is a lottie sticker (see Sticker.read()), one of entity_type, privacy_level, or entity_metadata is not of the correct type, or the entity_type was not provided and could not be assumed from the channel.

Returns:

The newly created guild scheduled event.

Return type:

GuildScheduledEvent

await welcome_screen()[source]

This function is a coroutine.

Retrieves the guild’s WelcomeScreen.

Requires the manage_guild permission if the welcome screen is not enabled.

Note

To determine whether the welcome screen is enabled, check for the presence of WELCOME_SCREEN_ENABLED in Guild.features.

New in version 2.5.

Raises:
  • NotFound – The welcome screen is not set up, or you do not have permission to view it.

  • HTTPException – Retrieving the welcome screen failed.

Returns:

The guild’s welcome screen.

Return type:

WelcomeScreen

await edit_welcome_screen(*, enabled=..., channels=..., description=..., reason=None)[source]

This function is a coroutine.

This is a lower level method to WelcomeScreen.edit() that allows you to edit the welcome screen without fetching it and save an API request.

This requires ‘COMMUNITY’ in Guild.features.

New in version 2.5.

Parameters:
  • enabled (bool) – Whether the welcome screen is enabled.

  • description (Optional[str]) – The new guild description in the welcome screen.

  • channels (Optional[List[WelcomeScreenChannel]]) – The new welcome channels.

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

Raises:
Returns:

The newly edited welcome screen.

Return type:

WelcomeScreen

await fetch_member(member_id, /)[source]

This function is a coroutine.

Retrieves a Member with the given ID.

Note

This method is an API call. If you have Intents.members and member cache enabled, consider get_member() instead.

Parameters:

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

Raises:
Returns:

The member from the member ID.

Return type:

Member

await fetch_ban(user)[source]

This function is a coroutine.

Retrieves the BanEntry for a user.

You must have ban_members permission to use this.

Parameters:

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

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

  • NotFound – This user is not banned.

  • HTTPException – An error occurred while fetching the information.

Returns:

The BanEntry object for the specified user.

Return type:

BanEntry

await fetch_channel(channel_id, /)[source]

This function is a coroutine.

Retrieves a abc.GuildChannel or Thread with the given ID.

Note

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

New in version 2.0.

Raises:
  • InvalidData – An unknown channel type was received from Discord or the guild the channel belongs to is not the same as the one in this object points to.

  • HTTPException – Retrieving the channel failed.

  • NotFound – Invalid Channel ID.

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

Returns:

The channel from the ID.

Return type:

Union[abc.GuildChannel, Thread]

bans(*, limit=1000, before=None, after=None)[source]

Returns an AsyncIterator that enables receiving the destination’s bans.

You must have the ban_members permission to get this information.

Changed in version 2.5: Due to a breaking change in Discord’s API, this now returns an AsyncIterator instead of a list.

Examples

Usage

counter = 0
async for ban in guild.bans(limit=200):
    if not ban.user.bot:
        counter += 1

Flattening into a list:

bans = await guild.bans(limit=123).flatten()
# bans is now a list of BanEntry...

All parameters are optional.

Parameters:
  • limit (Optional[int]) – The number of bans to retrieve. If None, it retrieves every ban in the guild. Note, however, that this would make it a slow operation. Defaults to 1000.

  • before (Optional[Snowflake]) – Retrieve bans before this user.

  • after (Optional[Snowflake]) – Retrieve bans after this user.

Raises:
  • Forbidden – You do not have permissions to get the bans.

  • HTTPException – An error occurred while fetching the bans.

Yields:

BanEntry – The ban with the ban data parsed.

await prune_members(*, days, compute_prune_count=True, roles=..., reason=None)[source]

This function is a coroutine.

Prunes the guild from its inactive members.

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

You must have kick_members permission to use this.

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

To prune members that have specific roles see the roles parameter.

Changed in version 1.4: The roles keyword-only parameter was added.

Changed in version 2.6: Raises TypeError instead of InvalidArgument.

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

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

  • roles (List[abc.Snowflake]) – A list of abc.Snowflake that represent roles to include in the pruning process. If a member has a role that is not specified, they’ll be excluded.

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

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

  • HTTPException – An error occurred while pruning members.

  • TypeError – An integer was not passed for days.

Returns:

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

Return type:

Optional[int]

await templates()[source]

This function is a coroutine.

Gets the list of templates from this guild.

You must have manage_guild permission to use this.

New in version 1.7.

Raises:

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

Returns:

The templates for this guild.

Return type:

List[Template]

await webhooks()[source]

This function is a coroutine.

Gets the list of webhooks from this guild.

You must have manage_webhooks permission to use this.

Raises:

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

Returns:

The webhooks for this guild.

Return type:

List[Webhook]

await estimate_pruned_members(*, days, roles=...)[source]

This function is a coroutine.

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

Changed in version 2.6: Raises TypeError instead of InvalidArgument.

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

  • roles (List[abc.Snowflake]) –

    A list of abc.Snowflake that represent roles to include in the estimate. If a member has a role that is not specified, they’ll be excluded.

    New in version 1.7.

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

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

  • TypeError – An integer was not passed for days.

Returns:

The number of members estimated to be pruned.

Return type:

int

await invites()[source]

This function is a coroutine.

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

You must have manage_guild permission to use this.

Note

This method does not include the guild’s vanity URL invite. To get the vanity URL Invite, refer to Guild.vanity_invite().

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

  • HTTPException – An error occurred while fetching the information.

Returns:

The list of invites that are currently active.

Return type:

List[Invite]

await create_template(*, name, description=...)[source]

This function is a coroutine.

Creates a template for the guild.

You must have manage_guild permission to use this.

New in version 1.7.

Parameters:
  • name (str) – The name of the template.

  • description (str) – The description of the template.

Returns:

The created template.

Return type:

Template

await create_integration(*, type, id)[source]

This function is a coroutine.

Deprecated since version 2.5: No longer supported, bots cannot use this endpoint anymore.

Attaches an integration to the guild.

You must have manage_guild permission to use this.

New in version 1.4.

Parameters:
  • type (str) – The integration type (e.g. Twitch).

  • id (int) – The integration ID.

Raises:
  • Forbidden – You do not have permission to create the integration.

  • HTTPException – The account could not be found.

await integrations()[source]

This function is a coroutine.

Returns a list of all integrations attached to the guild.

You must have manage_guild permission to use this.

New in version 1.4.

Raises:
  • Forbidden – You do not have permission to create the integration.

  • HTTPException – Fetching the integrations failed.

Returns:

The list of integrations that are attached to the guild.

Return type:

List[Integration]

await fetch_stickers()[source]

This function is a coroutine.

Retrieves a list of all Stickers that the guild has.

New in version 2.0.

Note

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

Raises:

HTTPException – Retrieving the stickers failed.

Returns:

The retrieved stickers.

Return type:

List[GuildSticker]

await fetch_sticker(sticker_id, /)[source]

This function is a coroutine.

Retrieves a custom Sticker from the guild.

New in version 2.0.

Note

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

Parameters:

sticker_id (int) – The sticker’s ID.

Raises:
  • NotFound – The sticker requested could not be found.

  • HTTPException – Retrieving the sticker failed.

Returns:

The retrieved sticker.

Return type:

GuildSticker

await create_sticker(*, name, description=None, emoji, file, reason=None)[source]

This function is a coroutine.

Creates a Sticker for the guild.

You must have manage_emojis_and_stickers permission to do this.

New in version 2.0.

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

  • description (Optional[str]) – The sticker’s description. You can pass None or an empty string to not set a description.

  • emoji (str) – The name of a unicode emoji that represents the sticker’s expression.

  • file (File) – The file of the sticker to upload.

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

Raises:
  • Forbidden – You are not allowed to create stickers.

  • HTTPException – An error occurred creating a sticker.

Returns:

The newly created sticker.

Return type:

GuildSticker

await delete_sticker(sticker, *, reason=None)[source]

This function is a coroutine.

Deletes the custom Sticker from the guild.

You must have manage_emojis_and_stickers permission to do this.

New in version 2.0.

Parameters:
  • sticker (abc.Snowflake) – The sticker you are deleting.

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

Raises:
  • Forbidden – You are not allowed to delete stickers.

  • HTTPException – An error occurred deleting the sticker.

await fetch_emojis()[source]

This function is a coroutine.

Retrieves all custom Emojis that the guild has.

Note

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

Raises:

HTTPException – Retrieving the emojis failed.

Returns:

The retrieved emojis.

Return type:

List[Emoji]

await fetch_emoji(emoji_id, /)[source]

This function is a coroutine.

Retrieves a custom Emoji from the guild.

Note

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

Parameters:

emoji_id (int) – The emoji’s ID.

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

  • HTTPException – An error occurred fetching the emoji.

Returns:

The retrieved emoji.

Return type:

Emoji

await create_custom_emoji(*, name, image, roles=..., reason=None)[source]

This function is a coroutine.

Creates a custom Emoji for the guild.

Depending on the boost level of your guild (which can be obtained via premium_tier), the amount of custom emojis that can be created changes:

Boost level

Max custom emoji limit

0

50

1

100

2

150

3

250

You must have manage_emojis permission to do this.

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

  • image (Union[bytes, Asset, Emoji, PartialEmoji, StickerItem, Sticker]) –

    The image data of the emoji. Only JPG, PNG and GIF images are supported.

    Changed in version 2.5: Now accepts various resource types in addition to bytes.

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

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

Raises:
Returns:

The newly created emoji.

Return type:

Emoji

await delete_emoji(emoji, *, reason=None)[source]

This function is a coroutine.

Deletes the custom Emoji from the guild.

You must have manage_emojis permission to do this.

Parameters:
  • emoji (abc.Snowflake) – The emoji you are deleting.

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

Raises:
await fetch_roles()[source]

This function is a coroutine.

Retrieves all Role that the guild has.

Note

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

New in version 1.3.

Raises:

HTTPException – Retrieving the roles failed.

Returns:

All roles that the guild has.

Return type:

List[Role]

await get_or_fetch_member(member_id, *, strict=False)[source]

This function is a coroutine.

Tries to get a member from the cache with the given ID. If fails, it fetches the member from the API and caches it.

If you want to make a bulk get-or-fetch call, use get_or_fetch_members().

Parameters:
  • member_id (int) – The ID to search for.

  • strict (bool) – Whether to propagate exceptions from fetch_member() instead of returning None in case of failure (e.g. if the member wasn’t found). Defaults to False.

Returns:

The member with the given ID, or None if not found and strict is set to False.

Return type:

Optional[Member]

await getch_member(member_id, *, strict=False)[source]

This function is a coroutine.

Tries to get a member from the cache with the given ID. If fails, it fetches the member from the API and caches it.

If you want to make a bulk get-or-fetch call, use get_or_fetch_members().

Parameters:
  • member_id (int) – The ID to search for.

  • strict (bool) – Whether to propagate exceptions from fetch_member() instead of returning None in case of failure (e.g. if the member wasn’t found). Defaults to False.

Returns:

The member with the given ID, or None if not found and strict is set to False.

Return type:

Optional[Member]

await create_role(*, name=..., permissions=..., color=..., colour=..., hoist=..., icon=..., emoji=..., mentionable=..., reason=None)[source]

This function is a coroutine.

Creates a Role for the guild.

All fields are optional.

You must have manage_roles permission to do this.

Changed in version 1.6: Can now pass int to colour keyword-only parameter.

Changed in version 2.6: Raises TypeError instead of InvalidArgument.

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

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

  • colour (Union[Colour, int]) – The colour for the role. Defaults to Colour.default(). This is aliased to color as well.

  • hoist (bool) – Whether the role should be shown separately in the member list. Defaults to False.

  • icon (Union[bytes, Asset, Emoji, PartialEmoji, StickerItem, Sticker]) –

    The role’s icon image (if the guild has the ROLE_ICONS feature).

    Changed in version 2.5: Now accepts various resource types in addition to bytes.

  • emoji (str) – The role’s unicode emoji.

  • mentionable (bool) – Whether the role should be mentionable by others. Defaults to False.

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

Raises:
  • NotFound – The icon asset couldn’t be found.

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

  • HTTPException – Creating the role failed.

  • TypeError – An invalid keyword argument was given, or the icon asset is a lottie sticker (see Sticker.read()).

Returns:

The newly created role.

Return type:

Role

await edit_role_positions(positions, *, reason=None)[source]

This function is a coroutine.

Bulk edits a list of Role in the guild.

You must have manage_roles permission to do this.

New in version 1.4.

Changed in version 2.6: Raises TypeError instead of InvalidArgument.

Example:

positions = {
    bots_role: 1, # penultimate role
    tester_role: 2,
    admin_role: 6
}

await guild.edit_role_positions(positions=positions)
Parameters:
  • positions – A dict of Role to int to change the positions of each given role.

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

Raises:
  • Forbidden – You do not have permissions to move the roles.

  • HTTPException – Moving the roles failed.

  • TypeError – An invalid keyword argument was given.

Returns:

A list of all the roles in the guild.

Return type:

List[Role]

await kick(user, *, reason=None)[source]

This function is a coroutine.

Kicks a user from the guild.

The user must meet the abc.Snowflake abc.

You must have kick_members permission to do this.

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

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

Raises:
await ban(user, *, clean_history_duration=..., delete_message_days=..., reason=None)[source]

This function is a coroutine.

Bans a user from the guild.

The user must meet the abc.Snowflake abc.

You must have ban_members permission to do this.

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

  • clean_history_duration (Union[int, datetime.timedelta]) –

    The timespan (seconds or timedelta) of messages to delete from the user in the guild, up to 7 days (604800 seconds). Defaults to 1 day (86400 seconds).

    This is incompatible with delete_message_days.

    New in version 2.6.

    Note

    This may not be accurate with small durations (e.g. a few minutes) and delete a couple minutes’ worth of messages more than specified.

  • delete_message_days (int) –

    The number of days worth of messages to delete from the user in the guild. The minimum is 0 and the maximum is 7.

    This is incompatible with clean_history_duration.

    Deprecated since version 2.6: Use clean_history_duration instead.

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

Raises:
  • TypeError – Both clean_history_duration and delete_message_days were provided, or clean_history_duration has an invalid type.

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

  • HTTPException – Banning failed.

await unban(user, *, reason=None)[source]

This function is a coroutine.

Unbans a user from the guild.

The user must meet the abc.Snowflake abc.

You must have ban_members permission to do this.

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

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

Raises:
await vanity_invite(*, use_cached=False)[source]

This function is a coroutine.

Returns the guild’s special vanity invite.

The guild must have VANITY_URL in features.

If use_cached is False, then you must have manage_guild permission to use this.

Parameters:

use_cached (bool) –

Whether to use the cached Guild.vanity_url_code and attempt to convert it into a full invite.

Note

If set to True, the Invite.uses information will not be accurate.

New in version 2.5.

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

  • HTTPException – Retrieving the vanity invite failed.

Returns:

The special vanity invite. If None then the guild does not have a vanity invite set.

Return type:

Optional[Invite]

await widget()[source]

This function is a coroutine.

Retrieves the widget of the guild.

Note

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

Raises:
Returns:

The guild’s widget.

Return type:

Widget

await widget_settings()[source]

This function is a coroutine.

Retrieves the widget settings of the guild.

To edit the widget settings, you may also use edit_widget().

New in version 2.5.

Raises:
  • Forbidden – You do not have permission to view the widget settings.

  • HTTPException – Retrieving the widget settings failed.

Returns:

The guild’s widget settings.

Return type:

WidgetSettings

await edit_widget(*, enabled=..., channel=..., reason=None)[source]

This function is a coroutine.

Edits the widget of the guild.

You must have manage_guild permission to use this.

New in version 2.0.

Changed in version 2.5: Returns the new widget settings.

Parameters:
  • enabled (bool) – Whether to enable the widget for the guild.

  • channel (Optional[Snowflake]) – The new widget channel. None removes the widget channel. If set, an invite link for this channel will be generated, which allows users to join the guild from the widget.

  • reason (Optional[str]) –

    The reason for editing the widget. Shows up on the audit log.

    New in version 2.4.

Raises:
Returns:

The new widget settings.

Return type:

WidgetSettings

widget_image_url(style=<WidgetStyle.shield: 'shield'>)[source]

Returns an URL to the widget’s .png image.

New in version 2.5.

Parameters:

style (WidgetStyle) – The widget style.

Returns:

The widget image URL.

Return type:

str

await edit_mfa_level(mfa_level, *, reason=None)[source]

This function is a coroutine.

Edits the two-factor authentication level of the guild.

You must be the guild owner to use this.

New in version 2.6.

Parameters:
  • mfa_level (int) – The new 2FA level. If set to 0, the guild does not require 2FA for their administrative members to take moderation actions. If set to 1, then 2FA is required.

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

Raises:
await chunk(*, cache=True)[source]

This function is a coroutine.

Returns a list of all guild members.

Requests all members that belong to this guild. In order to use this, Intents.members() must be enabled.

This is a websocket operation and can be slow.

New in version 1.5.

Parameters:

cache (bool) – Whether to cache the members as well.

Raises:

ClientException – The members intent is not enabled.

Returns:

Returns a list of all the members within the guild.

Return type:

Optional[List[Member]]

await query_members(query=None, *, limit=5, user_ids=None, presences=False, cache=True)[source]

This function is a coroutine.

Request members that belong to this guild whose username starts with the query given.

This is a websocket operation and can be slow.

See also search_members().

New in version 1.3.

Parameters:
  • query (Optional[str]) – The string that the username’s start with.

  • limit (int) – The maximum number of members to send back. This must be a number between 5 and 100.

  • presences (bool) –

    Whether to request for presences to be provided. This defaults to False.

    New in version 1.6.

  • cache (bool) – Whether to cache the members internally. This makes operations such as get_member() work for those that matched.

  • user_ids (Optional[List[int]]) –

    List of user IDs to search for. If the user ID is not in the guild then it won’t be returned.

    New in version 1.4.

Raises:
Returns:

The list of members that have matched the query.

Return type:

List[Member]

await search_members(query, *, limit=1, cache=True)[source]

This function is a coroutine.

Retrieves members that belong to this guild whose username or nickname starts with the query given.

Note that unlike query_members(), this is not a websocket operation, but an HTTP operation.

See also query_members().

New in version 2.5.

Parameters:
  • query (str) – The string that the usernames or nicknames start with.

  • limit (int) – The maximum number of members to send back. This must be a number between 1 and 1000.

  • cache (bool) – Whether to cache the members internally. This makes operations such as get_member() work for those that matched.

Raises:

ValueError – Invalid parameters were passed to the function

Returns:

The list of members that have matched the query.

Return type:

List[Member]

await get_or_fetch_members(user_ids, *, presences=False, cache=True)[source]

This function is a coroutine.

Tries to get the guild members matching the provided IDs from cache. If some of them were not found, the method requests the missing members using websocket operations. If cache kwarg is True (default value) the missing members will be cached.

If more than 100 members are missing, several websocket operations are made.

Websocket operations can be slow, however, this method is cheaper than multiple get_or_fetch_member() calls.

New in version 2.4.

Parameters:
  • user_ids (List[int]) – List of user IDs to search for. If the user ID is not in the guild then it won’t be returned.

  • presences (bool) – Whether to request for presences to be provided. Defaults to False.

  • cache (bool) – Whether to cache the missing members internally. This makes operations such as get_member() work for those that matched. It also speeds up this method on repeated calls. Defaults to True.

Raises:
Returns:

The list of members with the given IDs, if they exist.

Return type:

List[Member]

await getch_members(user_ids, *, presences=False, cache=True)[source]

This function is a coroutine.

Tries to get the guild members matching the provided IDs from cache. If some of them were not found, the method requests the missing members using websocket operations. If cache kwarg is True (default value) the missing members will be cached.

If more than 100 members are missing, several websocket operations are made.

Websocket operations can be slow, however, this method is cheaper than multiple get_or_fetch_member() calls.

New in version 2.4.

Parameters:
  • user_ids (List[int]) – List of user IDs to search for. If the user ID is not in the guild then it won’t be returned.

  • presences (bool) – Whether to request for presences to be provided. Defaults to False.

  • cache (bool) – Whether to cache the missing members internally. This makes operations such as get_member() work for those that matched. It also speeds up this method on repeated calls. Defaults to True.

Raises:
Returns:

The list of members with the given IDs, if they exist.

Return type:

List[Member]

await fetch_voice_regions()[source]

This function is a coroutine.

Retrieves a list of VoiceRegion for this guild.

New in version 2.5.

Raises:

HTTPException – Retrieving voice regions failed.

await change_voice_state(*, channel, self_mute=False, self_deaf=False)[source]

This function is a coroutine.

Changes client’s voice state in the guild.

New in version 1.4.

Parameters:
  • channel (Optional[VoiceChannel]) – The channel the client wants to join. Use None to disconnect.

  • self_mute (bool) – Whether the client should be self-muted.

  • self_deaf (bool) – Whether the client should be self-deafened.

await bulk_fetch_command_permissions()[source]

This function is a coroutine.

Requests a list of GuildApplicationCommandPermissions configured for this guild.

New in version 2.1.

await fetch_command_permissions(command_id)[source]

This function is a coroutine.

Retrieves GuildApplicationCommandPermissions for a specific command.

New in version 2.1.

Parameters:

command_id (int) –

The ID of the application command, or the application ID to fetch application-wide permissions.

Changed in version 2.5: Can now also fetch application-wide permissions.

Returns:

The application command permissions.

Return type:

GuildApplicationCommandPermissions

await timeout(user, *, duration=..., until=..., reason=None)[source]

This function is a coroutine.

Times out the member from the guild; until then, the member will not be able to interact with the guild.

Exactly one of duration or until must be provided. To remove a timeout, set one of the parameters to None.

The user must meet the abc.Snowflake abc.

You must have the moderate_members permission to do this.

New in version 2.3.

Parameters:
  • user (abc.Snowflake) – The member to timeout.

  • duration (Optional[Union[float, datetime.timedelta]]) – The duration (seconds or timedelta) of the member’s timeout. Set to None to remove the timeout. Supports up to 28 days in the future. May not be used in combination with the until parameter.

  • until (Optional[datetime.datetime]) – The expiry date/time of the member’s timeout. Set to None to remove the timeout. Supports up to 28 days in the future. May not be used in combination with the duration parameter.

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

Raises:
  • Forbidden – You do not have permissions to timeout this member.

  • HTTPException – Timing out the member failed.

Returns:

The newly updated member.

Return type:

Member

await fetch_automod_rule(rule_id, /)[source]

This function is a coroutine.

Retrieves an auto moderation rules from the guild. See also fetch_automod_rules().

Requires the manage_guild permission.

New in version 2.6.

Raises:
  • Forbidden – You do not have proper permissions to retrieve auto moderation rules.

  • NotFound – An auto moderation rule with the provided ID does not exist in the guild.

  • HTTPException – Retrieving the rule failed.

Returns:

The auto moderation rule.

Return type:

AutoModRule

await fetch_automod_rules()[source]

This function is a coroutine.

Retrieves the guild’s auto moderation rules. See also fetch_automod_rule().

Requires the manage_guild permission.

New in version 2.6.

Raises:
  • Forbidden – You do not have proper permissions to retrieve auto moderation rules.

  • NotFound – The guild does not have any auto moderation rules set up.

  • HTTPException – Retrieving the rules failed.

Returns:

The guild’s auto moderation rules.

Return type:

List[AutoModRule]

await create_automod_rule(*, name, event_type, trigger_type, actions, trigger_metadata=None, enabled=False, exempt_roles=None, exempt_channels=None, reason=None)[source]

This function is a coroutine.

Creates a new AutoModRule for the guild.

You must have Permissions.manage_guild permission to do this.

The maximum number of rules for each trigger type is limited, see the api docs for more details.

New in version 2.6.

Parameters:
  • name (str) – The rule name.

  • event_type (AutoModEventType) – The type of events that this rule will be applied to.

  • trigger_type (AutoModTriggerType) – The type of trigger that determines whether this rule’s actions should run for a specific event. If set to keyword, keyword_preset, or mention_spam, trigger_metadata must be set accordingly. This cannot be changed after creation.

  • actions (Sequence[Union[AutoModBlockMessageAction, AutoModSendAlertAction, AutoModTimeoutAction, AutoModAction]]) – The list of actions that will execute if a matching event triggered this rule. Must contain at least one action.

  • trigger_metadata (AutoModTriggerMetadata) – Additional metadata associated with the trigger type.

  • enabled (bool) – Whether to enable the rule. Defaults to False.

  • exempt_roles (Optional[Sequence[abc.Snowflake]]) – The roles that are exempt from this rule, up to 20. By default, no roles are exempt.

  • exempt_channels (Optional[Sequence[abc.Snowflake]]) – The channels that are exempt from this rule, up to 50. By default, no channels are exempt. Can also include categories, in which case all channels inside that category will be exempt.

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

Raises:
  • ValueError – The specified trigger type requires trigger_metadata to be set, or no actions have been provided.

  • Forbidden – You do not have proper permissions to create auto moderation rules.

  • HTTPException – Creating the rule failed.

Returns:

The newly created auto moderation rule.

Return type:

AutoModRule

class disnake.BanEntry[source]

A namedtuple which represents a ban returned from bans().

reason

The reason this user was banned.

Type:

Optional[str]

user

The User that was banned.

Type:

User

GuildPreview
class disnake.GuildPreview[source]

Represents a Guild preview object.

New in version 2.5.

name

The guild’s name.

Type:

str

emojis

All emojis that the guild owns.

Type:

Tuple[Emoji, …]

stickers

All stickers that the guild owns.

Type:

Tuple[GuildSticker, …]

id

The ID of the guild this preview represents.

Type:

int

description

The guild’s description.

Type:

Optional[str]

features

A list of features that the guild has. The features that a guild can have are subject to arbitrary change by Discord.

See Guild.features for a list of features.

Type:

List[str]

approximate_member_count

The approximate number of members in the guild.

Type:

int

approximate_presence_count

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

Type:

int

property icon[source]

Returns the guild preview’s icon asset, if available.

Type:

Optional[Asset]

property splash[source]

Returns the guild preview’s invite splash asset, if available.

Type:

Optional[Asset]

property discovery_splash[source]

Returns the guild preview’s discovery splash asset, if available.

Type:

Optional[Asset]

GuildScheduledEvent
class disnake.GuildScheduledEvent[source]

Represents a guild scheduled event.

New in version 2.3.

x == y

Checks if two guild scheduled events are equal.

x != y

Checks if two guild scheduled events are not equal.

hash(x)

Returns the guild scheduled event’s hash.

id

The ID of the guild scheduled event.

Type:

int

guild_id

The guild ID which the guild scheduled event belongs to.

Type:

int

channel_id

The channel ID in which the guild scheduled event will be hosted. This field is None if entity_type is GuildScheduledEventEntityType.external.

Type:

Optional[int]

creator_id

The ID of the user that created the guild scheduled event. This field is None for events created before October 25th, 2021.

Type:

Optional[int]

creator

The user that created the guild scheduled event. This field is None for events created before October 25th, 2021.

Type:

Optional[User]

name

The name of the guild scheduled event (1-100 characters).

Type:

str

description

The description of the guild scheduled event (1-1000 characters).

Type:

str

scheduled_start_time

The time when the guild scheduled event will start.

Type:

datetime.datetime

scheduled_end_time

The time when the guild scheduled event will end, or None if the event does not have a scheduled time to end.

Type:

Optional[datetime.datetime]

privacy_level

The privacy level of the guild scheduled event.

Type:

GuildScheduledEventPrivacyLevel

status

The status of the guild scheduled event.

Type:

GuildScheduledEventStatus

entity_type

The type of the guild scheduled event.

Type:

GuildScheduledEventEntityType

entity_id

The ID of an entity associated with the guild scheduled event.

Type:

Optional[int]

entity_metadata

Additional metadata for the guild scheduled event.

Type:

GuildScheduledEventMetadata

user_count

The number of users subscribed to the guild scheduled event. If the guild scheduled event was fetched with with_user_count set to False, this field is None.

Type:

Optional[int]

property created_at[source]

Returns the guild scheduled event’s creation time in UTC.

New in version 2.6.

Type:

datetime.datetime

property url[source]

The guild scheduled event’s URL.

New in version 2.6.

Type:

str

guild

The guild which the guild scheduled event belongs to.

Type:

Optional[Guild]

channel

The channel in which the guild scheduled event will be hosted.

This will be None if entity_type is GuildScheduledEventEntityType.external.

Type:

Optional[abc.GuildChannel]

property image[source]

The cover image asset of the guild scheduled event, if available.

Type:

Optional[Asset]

await delete()[source]

This function is a coroutine.

Deletes the guild scheduled event.

Raises:
  • Forbidden – You do not have proper permissions to delete the event.

  • NotFound – The event does not exist.

  • HTTPException – Deleting the event failed.

await edit(*, name=..., description=..., image=..., channel=..., privacy_level=..., scheduled_start_time=..., scheduled_end_time=..., entity_type=..., entity_metadata=..., status=..., reason=None)[source]

This function is a coroutine.

Edits the guild scheduled event.

Changed in version 2.6: Updates must follow requirements of Guild.create_scheduled_event()

Changed in version 2.6: Now raises TypeError instead of ValueError for invalid parameter types.

Changed in version 2.6: Removed channel_id parameter in favor of channel.

Changed in version 2.6: Naive datetime parameters are now assumed to be in the local timezone instead of UTC.

Parameters:
  • name (str) – The name of the guild scheduled event.

  • description (Optional[str]) – The description of the guild scheduled event.

  • image (Optional[Union[bytes, Asset, Emoji, PartialEmoji, StickerItem, Sticker]]) –

    The cover image of the guild scheduled event. Set to None to remove the image.

    New in version 2.4.

    Changed in version 2.5: Now accepts various resource types in addition to bytes.

  • channel (Optional[abc.Snowflake]) –

    The channel in which the guild scheduled event will be hosted. Set to None if changing entity_type to GuildScheduledEventEntityType.external.

    New in version 2.6.

  • privacy_level (GuildScheduledEventPrivacyLevel) – The privacy level of the guild scheduled event.

  • scheduled_start_time (datetime.datetime) – The time to schedule the guild scheduled event. If the datetime is naive, it is assumed to be local time.

  • scheduled_end_time (Optional[datetime.datetime]) – The time when the guild scheduled event is scheduled to end. If the datetime is naive, it is assumed to be local time.

  • entity_type (GuildScheduledEventEntityType) – The entity type of the guild scheduled event.

  • entity_metadata (Optional[GuildScheduledEventMetadata]) – The entity metadata of the guild scheduled event.

  • status (GuildScheduledEventStatus) – The status of the guild scheduled event.

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

Raises:
Returns:

The newly updated guild scheduled event instance.

Return type:

GuildScheduledEvent

fetch_users(*, limit=None, with_members=True, before=None, after=None)[source]

This function is a coroutine.

Returns an AsyncIterator of users subscribed to the guild scheduled event.

If before is specified, users are returned in reverse order, i.e. starting with the highest ID.

Changed in version 2.5: Now returns an AsyncIterator instead of a list of the first 100 users.

Parameters:
  • limit (Optional[int]) – The number of users to retrieve.

  • with_members (bool) – Whether to include some users as members. Defaults to True.

  • before (Optional[abc.Snowflake]) – Retrieve users before this object.

  • after (Optional[abc.Snowflake]) – Retrieve users after this object.

Raises:
  • Forbidden – You do not have proper permissions to fetch the users.

  • NotFound – The event does not exist.

  • HTTPException – Retrieving the users failed.

Yields:

Union[User, Member] – The member (if retrievable) or user subscribed to the guild scheduled event.

Examples

Usage

async for user in event.fetch_users(limit=500):
    print(user.name)

Flattening into a list

users = await event.fetch_users(limit=250).flatten()
GuildScheduledEventMetadata
Attributes
class disnake.GuildScheduledEventMetadata[source]

Represents a guild scheduled event entity metadata.

New in version 2.3.

location

The location of the guild scheduled event. If GuildScheduledEvent.entity_type is GuildScheduledEventEntityType.external, this value is not None.

Type:

Optional[str]

Integration
class disnake.Integration[source]

Represents a guild integration.

New in version 1.4.

id

The integration ID.

Type:

int

name

The integration name.

Type:

str

guild

The guild of the integration.

Type:

Guild

type

The integration type (i.e. Twitch).

Type:

str

enabled

Whether the integration is currently enabled.

Type:

bool

account

The account linked to this integration.

Type:

IntegrationAccount

user

The user that added this integration.

Type:

User

await delete(*, reason=None)[source]

This function is a coroutine.

Deprecated since version 2.5: Can only be used on the application’s own integration and is therefore equivalent to leaving the guild.

Deletes the integration.

You must have manage_guild permission to use this.

Parameters:

reason (Optional[str]) –

The reason the integration was deleted. Shows up on the audit log.

New in version 2.0.

Raises:
  • Forbidden – You do not have permission to delete the integration.

  • HTTPException – Deleting the integration failed.

class disnake.IntegrationAccount[source]

Represents an integration account.

New in version 1.4.

id

The account ID.

Type:

str

name

The account name.

Type:

str

class disnake.BotIntegration[source]

Represents a bot integration on Discord.

New in version 2.0.

id

The integration ID.

Type:

int

name

The integration name.

Type:

str

guild

The guild of the integration.

Type:

Guild

type

The integration type (i.e. Twitch).

Type:

str

enabled

Whether the integration is currently enabled.

Type:

bool

user

The user that added this integration.

Type:

User

account

The integration account information.

Type:

IntegrationAccount

application

The application tied to this integration.

Type:

IntegrationApplication

scopes

The OAuth2 scopes the application has been authorized for.

New in version 2.6.

Type:

List[str]

await delete(*, reason=None)[source]

This function is a coroutine.

Deprecated since version 2.5: Can only be used on the application’s own integration and is therefore equivalent to leaving the guild.

Deletes the integration.

You must have manage_guild permission to use this.

Parameters:

reason (Optional[str]) –

The reason the integration was deleted. Shows up on the audit log.

New in version 2.0.

Raises:
  • Forbidden – You do not have permission to delete the integration.

  • HTTPException – Deleting the integration failed.

class disnake.IntegrationApplication[source]

Represents an application for a bot integration.

New in version 2.0.

id

The application’s ID.

Type:

int

name

The application’s name.

Type:

str

icon

The application’s icon hash.

Type:

Optional[str]

description

The application’s description. Can be an empty string.

Type:

str

user

The bot user associated with this application.

Type:

Optional[User]

property summary[source]

The application’s summary. Can be an empty string.

Deprecated since version 2.5: This field is deprecated by discord and is now always blank. Consider using description instead.

Type:

str

class disnake.StreamIntegration[source]

Represents a stream integration for Twitch or YouTube.

New in version 2.0.

id

The integration ID.

Type:

int

name

The integration name.

Type:

str

guild

The guild of the integration.

Type:

Guild

type

The integration type (i.e. Twitch).

Type:

str

enabled

Whether the integration is currently enabled.

Type:

bool

syncing

Whether the integration is currently syncing.

Type:

bool

enable_emoticons

Whether emoticons should be synced for this integration (currently twitch only).

Type:

Optional[bool]

expire_behaviour

The behaviour of expiring subscribers. Aliased to expire_behavior as well.

Type:

ExpireBehaviour

expire_grace_period

The grace period (in days) for expiring subscribers.

Type:

int

user

The user for the integration.

Type:

User

account

The integration account information.

Type:

IntegrationAccount

synced_at

An aware UTC datetime representing when the integration was last synced.

Type:

datetime.datetime

property expire_behavior[source]

An alias for expire_behaviour.

Type:

ExpireBehaviour

property role[source]

Optional[Role] The role which the integration uses for subscribers.

await edit(*, expire_behaviour=..., expire_grace_period=..., enable_emoticons=...)[source]

This function is a coroutine.

Deprecated since version 2.5: No longer supported, bots cannot use this endpoint anymore.

Edits the integration.

You must have manage_guild permission to use this.

Changed in version 2.6: Raises TypeError instead of InvalidArgument.

Parameters:
  • expire_behaviour (ExpireBehaviour) – The behaviour when an integration subscription lapses. Aliased to expire_behavior as well.

  • expire_grace_period (int) – The period (in days) where the integration will ignore lapsed subscriptions.

  • enable_emoticons (bool) – Where emoticons should be synced for this integration (currently twitch only).

Raises:
await sync()[source]

This function is a coroutine.

Deprecated since version 2.5: No longer supported, bots cannot use this endpoint anymore.

Syncs the integration.

You must have manage_guild permission to use this.

Raises:
  • Forbidden – You do not have permission to sync the integration.

  • HTTPException – Syncing the integration failed.

await delete(*, reason=None)[source]

This function is a coroutine.

Deprecated since version 2.5: Can only be used on the application’s own integration and is therefore equivalent to leaving the guild.

Deletes the integration.

You must have manage_guild permission to use this.

Parameters:

reason (Optional[str]) –

The reason the integration was deleted. Shows up on the audit log.

New in version 2.0.

Raises:
  • Forbidden – You do not have permission to delete the integration.

  • HTTPException – Deleting the integration failed.

class disnake.PartialIntegration[source]

Represents a partial guild integration.

New in version 2.6.

id

The integration ID.

Type:

int

name

The integration name.

Type:

str

guild

The guild of the integration.

Type:

Guild

type

The integration type (i.e. Twitch).

Type:

str

account

The account linked to this integration.

Type:

IntegrationAccount

application_id

The ID of the application tied to this integration.

Type:

Optional[int]

Interaction
class disnake.Interaction[source]

A base class representing a user-initiated Discord interaction.

An interaction happens when a user performs an action that the client needs to be notified of. Current examples are application commands and components.

New in version 2.0.

data

The interaction’s raw data. This might be replaced with a more processed version in subclasses.

Type:

Mapping[str, Any]

id

The interaction’s ID.

Type:

int

type

The interaction’s type.

Type:

InteractionType

application_id

The application ID that the interaction was for.

Type:

int

guild_id

The guild ID the interaction was sent from.

Type:

Optional[int]

guild_locale

The selected language of the interaction’s guild. This value is only meaningful in guilds with COMMUNITY feature and receives a default value otherwise. If the interaction was in a DM, then this value is None.

New in version 2.4.

Changed in version 2.5: Changed to Locale instead of str.

Type:

Optional[Locale]

channel_id

The channel ID the interaction was sent from.

Type:

int

author

The user or member that sent the interaction.

Type:

Union[User, Member]

locale

The selected language of the interaction’s author.

New in version 2.4.

Changed in version 2.5: Changed to Locale instead of str.

Type:

Locale

token

The token to continue the interaction. These are valid for 15 minutes.

Type:

str

client

The interaction client.

Type:

Client

original_message()[source]

An alias of original_response().

edit_original_message()[source]

An alias of edit_original_response().

delete_original_message()[source]

An alias of delete_original_response().

property bot[source]

The bot handling the interaction.

Only applicable when used with Bot. This is an alias for client.

Type:

Bot

property created_at[source]

Returns the interaction’s creation time in UTC.

Type:

datetime.datetime

property user[source]

The user or member that sent the interaction. There is an alias for this named author.

Type:

Union[User, Member]

property guild[source]

The guild the interaction was sent from.

Type:

Optional[Guild]

me

Union[Member, ClientUser]: Similar to Guild.me except it may return the ClientUser in private message contexts.

channel

The channel the interaction was sent from.

Note that due to a Discord limitation, threads that the bot cannot access and DM channels are not resolved since there is no data to complete them. These are PartialMessageable instead.

If you want to compute the interaction author’s or bot’s permissions in the channel, consider using permissions or app_permissions instead.

Type:

Union[abc.GuildChannel, Thread, PartialMessageable]

property permissions[source]

The resolved permissions of the member in the channel, including overwrites.

In a guild context, this is provided directly by Discord.

In a non-guild context this will be an instance of Permissions.private_channel().

Type:

Permissions

property app_permissions[source]

The resolved permissions of the bot in the channel, including overwrites.

In a guild context, this is provided directly by Discord.

In a non-guild context this will be an instance of Permissions.private_channel().

New in version 2.6.

Type:

Permissions

response

Returns an object responsible for handling responding to the interaction.

A response can only be done once. If secondary messages need to be sent, consider using followup instead.

Type:

InteractionResponse

followup

Returns the follow up webhook for follow up interactions.

Type:

Webhook

expires_at

Returns the interaction’s expiration time in UTC.

This is exactly 15 minutes after the interaction was created.

New in version 2.5.

Type:

datetime.datetime

is_expired()[source]

Whether the interaction can still be used to make requests to Discord.

This does not take into account the 3 second limit for the initial response.

New in version 2.5.

Return type:

bool

await original_response()[source]

This function is a coroutine.

Fetches the original interaction response message associated with the interaction.

Here is a table with response types and their associated original response:

Response type

Original response

InteractionResponse.send_message()

The message you sent

InteractionResponse.edit_message()

The message you edited

InteractionResponse.defer()

The message with thinking state (bot is thinking…)

Other response types

None

Repeated calls to this will return a cached value.

Changed in version 2.6: This function was renamed from original_message.

Raises:

HTTPException – Fetching the original response message failed.

Returns:

The original interaction response message.

Return type:

InteractionMessage

await edit_original_response(content=..., *, embed=..., embeds=..., file=..., files=..., attachments=..., view=..., components=..., allowed_mentions=None)[source]

This function is a coroutine.

Edits the original, previously sent interaction response message.

This is a lower level interface to InteractionMessage.edit() in case you do not want to fetch the message and save an HTTP request.

This method is also the only way to edit the original response if the message sent was ephemeral.

Note

If the original response message has embeds with images that were created from local files (using the file parameter with Embed.set_image() or Embed.set_thumbnail()), those images will be removed if the message’s attachments are edited in any way (i.e. by setting file/files/attachments, or adding an embed with local files).

Changed in version 2.6: This function was renamed from edit_original_message.

Parameters:
  • content (Optional[str]) – The content to edit the message with, or None to clear it.

  • embed (Optional[Embed]) – The new embed to replace the original with. This cannot be mixed with the embeds parameter. Could be None to remove the embed.

  • embeds (List[Embed]) – The new embeds to replace the original with. Must be a maximum of 10. This cannot be mixed with the embed parameter. To remove all embeds [] should be passed.

  • file (File) – The file to upload. This cannot be mixed with the files parameter. Files will be appended to the message, see the attachments parameter to remove/replace existing files.

  • files (List[File]) – A list of files to upload. This cannot be mixed with the file parameter. Files will be appended to the message, see the attachments parameter to remove/replace existing files.

  • attachments (Optional[List[Attachment]]) –

    A list of attachments to keep in the message. If [] or None is passed then all existing attachments are removed. Keeps existing attachments if not provided.

    New in version 2.2.

    Changed in version 2.5: Supports passing None to clear attachments.

  • view (Optional[View]) – The updated view to update this message with. This cannot be mixed with components. If None is passed then the view is removed.

  • components (Optional[Union[disnake.ui.ActionRow, disnake.ui.WrappedComponent, List[Union[disnake.ui.ActionRow, disnake.ui.WrappedComponent, List[disnake.ui.WrappedComponent]]]]]) –

    A list of components to update this message with. This cannot be mixed with view. If None is passed then the components are removed.

    New in version 2.4.

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

Raises:
  • HTTPException – Editing the message failed.

  • Forbidden – Edited a message that is not yours.

  • TypeError – You specified both embed and embeds or file and files

  • ValueError – The length of embeds was invalid.

Returns:

The newly edited message.

Return type:

InteractionMessage

await delete_original_response(*, delay=None)[source]

This function is a coroutine.

Deletes the original interaction response message.

This is a lower level interface to InteractionMessage.delete() in case you do not want to fetch the message and save an HTTP request.

Changed in version 2.6: This function was renamed from delete_original_message.

Parameters:

delay (float) – If provided, the number of seconds to wait in the background before deleting the original response message. If the deletion fails, then it is silently ignored.

Raises:
await send(content=None, *, embed=..., embeds=..., file=..., files=..., allowed_mentions=..., view=..., components=..., tts=False, ephemeral=False, suppress_embeds=False, delete_after=...)[source]

This function is a coroutine.

Sends a message using either response.send_message or followup.send.

If the interaction hasn’t been responded to yet, this method will call response.send_message. Otherwise, it will call followup.send.

Note

This method does not return a Message object. If you need a message object, use original_response() to fetch it, or use followup.send directly instead of this method if you’re sending a followup message.

Parameters:
  • content (Optional[str]) – The content of the message to send.

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

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

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

  • files (List[File]) – A list of files to upload. Must be a maximum of 10. This cannot be mixed with the file parameter.

  • allowed_mentions (AllowedMentions) – Controls the mentions being processed in this message. If this is passed, then the object is merged with Client.allowed_mentions. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set in Client.allowed_mentions. If no object is passed at all then the defaults given by Client.allowed_mentions are used instead.

  • tts (bool) – Whether the message should be sent using text-to-speech.

  • view (disnake.ui.View) – The view to send with the message. This cannot be mixed with components.

  • components (Union[disnake.ui.ActionRow, disnake.ui.WrappedComponent, List[Union[disnake.ui.ActionRow, disnake.ui.WrappedComponent, List[disnake.ui.WrappedComponent]]]]) –

    A list of components to send with the message. This cannot be mixed with view.

    New in version 2.4.

  • ephemeral (bool) – Whether the message should only be visible to the user who started the interaction. If a view is sent with an ephemeral message and it has no timeout set then the timeout is set to 15 minutes.

  • suppress_embeds (bool) –

    Whether to suppress embeds for the message. This hides all embeds from the UI if set to True.

    New in version 2.5.

  • delete_after (float) – If provided, the number of seconds to wait in the background before deleting the message we just sent. If the deletion fails, then it is silently ignored.

Raises:
ApplicationCommandInteraction
class disnake.ApplicationCommandInteraction[source]

Represents an interaction with an application command.

Current examples are slash commands, user commands and message commands.

New in version 2.1.

id

The interaction’s ID.

Type:

int

type

The interaction’s type.

Type:

InteractionType

application_id

The application ID that the interaction was for.

Type:

int

guild_id

The guild ID the interaction was sent from.

Type:

Optional[int]

channel_id

The channel ID the interaction was sent from.

Type:

int

author

The user or member that sent the interaction.

Type:

Union[User, Member]

locale

The selected language of the interaction’s author.

New in version 2.4.

Changed in version 2.5: Changed to Locale instead of str.

Type:

Locale

guild_locale

The selected language of the interaction’s guild. This value is only meaningful in guilds with COMMUNITY feature and receives a default value otherwise. If the interaction was in a DM, then this value is None.

New in version 2.4.

Changed in version 2.5: Changed to Locale instead of str.

Type:

Optional[Locale]

token

The token to continue the interaction. These are valid for 15 minutes.

Type:

str

data

The wrapped interaction data.

Type:

ApplicationCommandInteractionData

client

The interaction client.

Type:

Client

application_command

The command invoked by the interaction.

Type:

InvokableApplicationCommand

command_failed

Whether the command failed to be checked or invoked.

Type:

bool

original_message()[source]

An alias of original_response().

edit_original_message()[source]

An alias of edit_original_response().

delete_original_message()[source]

An alias of delete_original_response().

property target[source]

The user or message targetted by a user or message command

Type:

Optional[Union[abc.User, Message]]

property options[source]

The full option tree, including nestings

Type:

Dict[str, Any]

property filled_options[source]

The options of the command (or sub-command) being invoked

Type:

Dict[str, Any]

property app_permissions[source]

The resolved permissions of the bot in the channel, including overwrites.

In a guild context, this is provided directly by Discord.

In a non-guild context this will be an instance of Permissions.private_channel().

New in version 2.6.

Type:

Permissions

property bot[source]

The bot handling the interaction.

Only applicable when used with Bot. This is an alias for client.

Type:

Bot

channel

The channel the interaction was sent from.

Note that due to a Discord limitation, threads that the bot cannot access and DM channels are not resolved since there is no data to complete them. These are PartialMessageable instead.

If you want to compute the interaction author’s or bot’s permissions in the channel, consider using permissions or app_permissions instead.

Type:

Union[abc.GuildChannel, Thread, PartialMessageable]

property created_at[source]

Returns the interaction’s creation time in UTC.

Type:

datetime.datetime

await delete_original_response(*, delay=None)[source]

This function is a coroutine.

Deletes the original interaction response message.

This is a lower level interface to InteractionMessage.delete() in case you do not want to fetch the message and save an HTTP request.

Changed in version 2.6: This function was renamed from delete_original_message.

Parameters:

delay (float) – If provided, the number of seconds to wait in the background before deleting the original response message. If the deletion fails, then it is silently ignored.

Raises:
await edit_original_response(content=..., *, embed=..., embeds=..., file=..., files=..., attachments=..., view=..., components=..., allowed_mentions=None)[source]

This function is a coroutine.

Edits the original, previously sent interaction response message.

This is a lower level interface to InteractionMessage.edit() in case you do not want to fetch the message and save an HTTP request.

This method is also the only way to edit the original response if the message sent was ephemeral.

Note

If the original response message has embeds with images that were created from local files (using the file parameter with Embed.set_image() or Embed.set_thumbnail()), those images will be removed if the message’s attachments are edited in any way (i.e. by setting file/files/attachments, or adding an embed with local files).

Changed in version 2.6: This function was renamed from edit_original_message.

Parameters:
  • content (Optional[str]) – The content to edit the message with, or None to clear it.

  • embed (Optional[Embed]) – The new embed to replace the original with. This cannot be mixed with the embeds parameter. Could be None to remove the embed.

  • embeds (List[Embed]) – The new embeds to replace the original with. Must be a maximum of 10. This cannot be mixed with the embed parameter. To remove all embeds [] should be passed.

  • file (File) – The file to upload. This cannot be mixed with the files parameter. Files will be appended to the message, see the attachments parameter to remove/replace existing files.

  • files (List[File]) – A list of files to upload. This cannot be mixed with the file parameter. Files will be appended to the message, see the attachments parameter to remove/replace existing files.

  • attachments (Optional[List[Attachment]]) –

    A list of attachments to keep in the message. If [] or None is passed then all existing attachments are removed. Keeps existing attachments if not provided.

    New in version 2.2.

    Changed in version 2.5: Supports passing None to clear attachments.

  • view (Optional[View]) – The updated view to update this message with. This cannot be mixed with components. If None is passed then the view is removed.

  • components (Optional[Union[disnake.ui.ActionRow, disnake.ui.WrappedComponent, List[Union[disnake.ui.ActionRow, disnake.ui.WrappedComponent, List[disnake.ui.WrappedComponent]]]]]) –

    A list of components to update this message with. This cannot be mixed with view. If None is passed then the components are removed.

    New in version 2.4.

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

Raises:
  • HTTPException – Editing the message failed.

  • Forbidden – Edited a message that is not yours.

  • TypeError – You specified both embed and embeds or file and files

  • ValueError – The length of embeds was invalid.

Returns:

The newly edited message.

Return type:

InteractionMessage

expires_at

Returns the interaction’s expiration time in UTC.

This is exactly 15 minutes after the interaction was created.

New in version 2.5.

Type:

datetime.datetime

followup

Returns the follow up webhook for follow up interactions.

Type:

Webhook

property guild[source]

The guild the interaction was sent from.

Type:

Optional[Guild]

is_expired()[source]

Whether the interaction can still be used to make requests to Discord.

This does not take into account the 3 second limit for the initial response.

New in version 2.5.

Return type:

bool

me

Union[Member, ClientUser]: Similar to Guild.me except it may return the ClientUser in private message contexts.

await original_response()[source]

This function is a coroutine.

Fetches the original interaction response message associated with the interaction.

Here is a table with response types and their associated original response:

Response type

Original response

InteractionResponse.send_message()

The message you sent

InteractionResponse.edit_message()

The message you edited

InteractionResponse.defer()

The message with thinking state (bot is thinking…)

Other response types

None

Repeated calls to this will return a cached value.

Changed in version 2.6: This function was renamed from original_message.

Raises:

HTTPException – Fetching the original response message failed.

Returns:

The original interaction response message.

Return type:

InteractionMessage

property permissions[source]

The resolved permissions of the member in the channel, including overwrites.

In a guild context, this is provided directly by Discord.

In a non-guild context this will be an instance of Permissions.private_channel().

Type:

Permissions

response

Returns an object responsible for handling responding to the interaction.

A response can only be done once. If secondary messages need to be sent, consider using followup instead.

Type:

InteractionResponse

await send(content=None, *, embed=..., embeds=..., file=..., files=..., allowed_mentions=..., view=..., components=..., tts=False, ephemeral=False, suppress_embeds=False, delete_after=...)[source]

This function is a coroutine.

Sends a message using either response.send_message or followup.send.

If the interaction hasn’t been responded to yet, this method will call response.send_message. Otherwise, it will call followup.send.

Note

This method does not return a Message object. If you need a message object, use original_response() to fetch it, or use followup.send directly instead of this method if you’re sending a followup message.

Parameters:
  • content (Optional[str]) – The content of the message to send.

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

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

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

  • files (List[File]) – A list of files to upload. Must be a maximum of 10. This cannot be mixed with the file parameter.

  • allowed_mentions (AllowedMentions) – Controls the mentions being processed in this message. If this is passed, then the object is merged with Client.allowed_mentions. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set in Client.allowed_mentions. If no object is passed at all then the defaults given by Client.allowed_mentions are used instead.

  • tts (bool) – Whether the message should be sent using text-to-speech.

  • view (disnake.ui.View) – The view to send with the message. This cannot be mixed with components.

  • components (Union[disnake.ui.ActionRow, disnake.ui.WrappedComponent, List[Union[disnake.ui.ActionRow, disnake.ui.WrappedComponent, List[disnake.ui.WrappedComponent]]]]) –

    A list of components to send with the message. This cannot be mixed with view.

    New in version 2.4.

  • ephemeral (bool) – Whether the message should only be visible to the user who started the interaction. If a view is sent with an ephemeral message and it has no timeout set then the timeout is set to 15 minutes.

  • suppress_embeds (bool) –

    Whether to suppress embeds for the message. This hides all embeds from the UI if set to True.

    New in version 2.5.

  • delete_after (float) – If provided, the number of seconds to wait in the background before deleting the message we just sent. If the deletion fails, then it is silently ignored.

Raises:
property user[source]

The user or member that sent the interaction. There is an alias for this named author.

Type:

Union[User, Member]

GuildCommandInteraction
class disnake.GuildCommandInteraction[source]

An ApplicationCommandInteraction subclass, primarily meant for annotations.

This prevents the command from being invoked in DMs by automatically setting ApplicationCommand.dm_permission to False for user/message commands and top-level slash commands.

Note that this does not apply to slash subcommands, subcommand groups, or autocomplete callbacks.

Additionally, annotations of some attributes are modified to match the expected types in guilds.

UserCommandInteraction
class disnake.UserCommandInteraction[source]

An ApplicationCommandInteraction subclass meant for annotations.

No runtime behavior is changed but annotations are modified to seem like the interaction is specifically a user command.

MessageCommandInteraction
class disnake.MessageCommandInteraction[source]

An ApplicationCommandInteraction subclass meant for annotations.

No runtime behavior is changed but annotations are modified to seem like the interaction is specifically a message command.

MessageInteraction
class disnake.MessageInteraction[source]

Represents an interaction with a message component.

Current examples are buttons and dropdowns.

New in version 2.1.

id

The interaction’s ID.

Type:

int

type

The interaction type.

Type:

InteractionType

application_id

The application ID that the interaction was for.

Type:

int

token

The token to continue the interaction. These are valid for 15 minutes.

Type:

str

guild_id

The guild ID the interaction was sent from.

Type:

Optional[int]

channel_id

The channel ID the interaction was sent from.

Type:

int

author

The user or member that sent the interaction.

Type:

Union[User, Member]

locale

The selected language of the interaction’s author.

New in version 2.4.

Changed in version 2.5: Changed to Locale instead of str.

Type:

Locale

guild_locale

The selected language of the interaction’s guild. This value is only meaningful in guilds with COMMUNITY feature and receives a default value otherwise. If the interaction was in a DM, then this value is None.

New in version 2.4.

Changed in version 2.5: Changed to Locale instead of str.

Type:

Optional[Locale]

message

The message that sent this interaction.

Type:

Optional[Message]

data

The wrapped interaction data.

Type:

MessageInteractionData

client

The interaction client.

Type:

Client

original_message()[source]

An alias of original_response().

edit_original_message()[source]

An alias of edit_original_response().

delete_original_message()[source]

An alias of delete_original_response().

property values[source]

The values the user selected.

Type:

Optional[List[str]]

component

The component the user interacted with

Type:

Union[Button, SelectMenu]

property app_permissions[source]

The resolved permissions of the bot in the channel, including overwrites.

In a guild context, this is provided directly by Discord.

In a non-guild context this will be an instance of Permissions.private_channel().

New in version 2.6.

Type:

Permissions

property bot[source]

The bot handling the interaction.

Only applicable when used with Bot. This is an alias for client.

Type:

Bot

channel

The channel the interaction was sent from.

Note that due to a Discord limitation, threads that the bot cannot access and DM channels are not resolved since there is no data to complete them. These are PartialMessageable instead.

If you want to compute the interaction author’s or bot’s permissions in the channel, consider using permissions or app_permissions instead.

Type:

Union[abc.GuildChannel, Thread, PartialMessageable]

property created_at[source]

Returns the interaction’s creation time in UTC.

Type:

datetime.datetime

await delete_original_response(*, delay=None)[source]

This function is a coroutine.

Deletes the original interaction response message.

This is a lower level interface to InteractionMessage.delete() in case you do not want to fetch the message and save an HTTP request.

Changed in version 2.6: This function was renamed from delete_original_message.

Parameters:

delay (float) – If provided, the number of seconds to wait in the background before deleting the original response message. If the deletion fails, then it is silently ignored.

Raises:
await edit_original_response(content=..., *, embed=..., embeds=..., file=..., files=..., attachments=..., view=..., components=..., allowed_mentions=None)[source]

This function is a coroutine.

Edits the original, previously sent interaction response message.

This is a lower level interface to InteractionMessage.edit() in case you do not want to fetch the message and save an HTTP request.

This method is also the only way to edit the original response if the message sent was ephemeral.

Note

If the original response message has embeds with images that were created from local files (using the file parameter with Embed.set_image() or Embed.set_thumbnail()), those images will be removed if the message’s attachments are edited in any way (i.e. by setting file/files/attachments, or adding an embed with local files).

Changed in version 2.6: This function was renamed from edit_original_message.

Parameters:
  • content (Optional[str]) – The content to edit the message with, or None to clear it.

  • embed (Optional[Embed]) – The new embed to replace the original with. This cannot be mixed with the embeds parameter. Could be None to remove the embed.

  • embeds (List[Embed]) – The new embeds to replace the original with. Must be a maximum of 10. This cannot be mixed with the embed parameter. To remove all embeds [] should be passed.

  • file (File) – The file to upload. This cannot be mixed with the files parameter. Files will be appended to the message, see the attachments parameter to remove/replace existing files.

  • files (List[File]) – A list of files to upload. This cannot be mixed with the file parameter. Files will be appended to the message, see the attachments parameter to remove/replace existing files.

  • attachments (Optional[List[Attachment]]) –

    A list of attachments to keep in the message. If [] or None is passed then all existing attachments are removed. Keeps existing attachments if not provided.

    New in version 2.2.

    Changed in version 2.5: Supports passing None to clear attachments.

  • view (Optional[View]) – The updated view to update this message with. This cannot be mixed with components. If None is passed then the view is removed.

  • components (Optional[Union[disnake.ui.ActionRow, disnake.ui.WrappedComponent, List[Union[disnake.ui.ActionRow, disnake.ui.WrappedComponent, List[disnake.ui.WrappedComponent]]]]]) –

    A list of components to update this message with. This cannot be mixed with view. If None is passed then the components are removed.

    New in version 2.4.

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

Raises:
  • HTTPException – Editing the message failed.

  • Forbidden – Edited a message that is not yours.

  • TypeError – You specified both embed and embeds or file and files

  • ValueError – The length of embeds was invalid.

Returns:

The newly edited message.

Return type:

InteractionMessage

expires_at

Returns the interaction’s expiration time in UTC.

This is exactly 15 minutes after the interaction was created.

New in version 2.5.

Type:

datetime.datetime

followup

Returns the follow up webhook for follow up interactions.

Type:

Webhook

property guild[source]

The guild the interaction was sent from.

Type:

Optional[Guild]

is_expired()[source]

Whether the interaction can still be used to make requests to Discord.

This does not take into account the 3 second limit for the initial response.

New in version 2.5.

Return type:

bool

me

Union[Member, ClientUser]: Similar to Guild.me except it may return the ClientUser in private message contexts.

await original_response()[source]

This function is a coroutine.

Fetches the original interaction response message associated with the interaction.

Here is a table with response types and their associated original response:

Response type

Original response

InteractionResponse.send_message()

The message you sent

InteractionResponse.edit_message()

The message you edited

InteractionResponse.defer()

The message with thinking state (bot is thinking…)

Other response types

None

Repeated calls to this will return a cached value.

Changed in version 2.6: This function was renamed from original_message.

Raises:

HTTPException – Fetching the original response message failed.

Returns:

The original interaction response message.

Return type:

InteractionMessage

property permissions[source]

The resolved permissions of the member in the channel, including overwrites.

In a guild context, this is provided directly by Discord.

In a non-guild context this will be an instance of Permissions.private_channel().

Type:

Permissions

response

Returns an object responsible for handling responding to the interaction.

A response can only be done once. If secondary messages need to be sent, consider using followup instead.

Type:

InteractionResponse

await send(content=None, *, embed=..., embeds=..., file=..., files=..., allowed_mentions=..., view=..., components=..., tts=False, ephemeral=False, suppress_embeds=False, delete_after=...)[source]

This function is a coroutine.

Sends a message using either response.send_message or followup.send.

If the interaction hasn’t been responded to yet, this method will call response.send_message. Otherwise, it will call followup.send.

Note

This method does not return a Message object. If you need a message object, use original_response() to fetch it, or use followup.send directly instead of this method if you’re sending a followup message.

Parameters:
  • content (Optional[str]) – The content of the message to send.

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

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

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

  • files (List[File]) – A list of files to upload. Must be a maximum of 10. This cannot be mixed with the file parameter.

  • allowed_mentions (AllowedMentions) – Controls the mentions being processed in this message. If this is passed, then the object is merged with Client.allowed_mentions. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set in Client.allowed_mentions. If no object is passed at all then the defaults given by Client.allowed_mentions are used instead.

  • tts (bool) – Whether the message should be sent using text-to-speech.

  • view (disnake.ui.View) – The view to send with the message. This cannot be mixed with components.

  • components (Union[disnake.ui.ActionRow, disnake.ui.WrappedComponent, List[Union[disnake.ui.ActionRow, disnake.ui.WrappedComponent, List[disnake.ui.WrappedComponent]]]]) –

    A list of components to send with the message. This cannot be mixed with view.

    New in version 2.4.

  • ephemeral (bool) – Whether the message should only be visible to the user who started the interaction. If a view is sent with an ephemeral message and it has no timeout set then the timeout is set to 15 minutes.

  • suppress_embeds (bool) –

    Whether to suppress embeds for the message. This hides all embeds from the UI if set to True.

    New in version 2.5.

  • delete_after (float) – If provided, the number of seconds to wait in the background before deleting the message we just sent. If the deletion fails, then it is silently ignored.

Raises:
property user[source]

The user or member that sent the interaction. There is an alias for this named author.

Type:

Union[User, Member]

ModalInteraction
class disnake.ModalInteraction[source]

Represents an interaction with a modal.

New in version 2.4.

id

The interaction’s ID.

Type:

int

type

The interaction type.

Type:

InteractionType

application_id

The application ID that the interaction was for.

Type:

int

token

The token to continue the interaction. These are valid for 15 minutes.

Type:

str

guild_id

The guild ID the interaction was sent from.

Type:

Optional[int]

channel_id

The channel ID the interaction was sent from.

Type:

int

author

The user or member that sent the interaction.

Type:

Union[User, Member]

locale

The selected language of the interaction’s author.

Changed in version 2.5: Changed to Locale instead of str.

Type:

Locale

guild_locale

The selected language of the interaction’s guild. This value is only meaningful in guilds with COMMUNITY feature and receives a default value otherwise. If the interaction was in a DM, then this value is None.

Changed in version 2.5: Changed to Locale instead of str.

Type:

Optional[Locale]

message

The message that this interaction’s modal originated from, if the modal was sent in response to a component interaction.

New in version 2.5.

Type:

Optional[Message]

data

The wrapped interaction data.

Type:

ModalInteractionData

client

The interaction client.

Type:

Client

original_message()[source]

An alias of original_response().

edit_original_message()[source]

An alias of edit_original_response().

delete_original_message()[source]

An alias of delete_original_response().

for ... in walk_raw_components()[source]

Returns a generator that yields raw component data from action rows one by one, as provided by Discord. This does not contain all fields of the components due to API limitations.

New in version 2.6.

Return type:

Generator[dict, None, None]

text_values

Returns the text values the user has entered in the modal. This is a dict of the form {custom_id: value}.

Type:

Dict[str, str]

property custom_id[source]

The custom ID of the modal.

Type:

str

property app_permissions[source]

The resolved permissions of the bot in the channel, including overwrites.

In a guild context, this is provided directly by Discord.

In a non-guild context this will be an instance of Permissions.private_channel().

New in version 2.6.

Type:

Permissions

property bot[source]

The bot handling the interaction.

Only applicable when used with Bot. This is an alias for client.

Type:

Bot

channel

The channel the interaction was sent from.

Note that due to a Discord limitation, threads that the bot cannot access and DM channels are not resolved since there is no data to complete them. These are PartialMessageable instead.

If you want to compute the interaction author’s or bot’s permissions in the channel, consider using permissions or app_permissions instead.

Type:

Union[abc.GuildChannel, Thread, PartialMessageable]

property created_at[source]

Returns the interaction’s creation time in UTC.

Type:

datetime.datetime

await delete_original_response(*, delay=None)[source]

This function is a coroutine.

Deletes the original interaction response message.

This is a lower level interface to InteractionMessage.delete() in case you do not want to fetch the message and save an HTTP request.

Changed in version 2.6: This function was renamed from delete_original_message.

Parameters:

delay (float) – If provided, the number of seconds to wait in the background before deleting the original response message. If the deletion fails, then it is silently ignored.

Raises:
await edit_original_response(content=..., *, embed=..., embeds=..., file=..., files=..., attachments=..., view=..., components=..., allowed_mentions=None)[source]

This function is a coroutine.

Edits the original, previously sent interaction response message.

This is a lower level interface to InteractionMessage.edit() in case you do not want to fetch the message and save an HTTP request.

This method is also the only way to edit the original response if the message sent was ephemeral.

Note

If the original response message has embeds with images that were created from local files (using the file parameter with Embed.set_image() or Embed.set_thumbnail()), those images will be removed if the message’s attachments are edited in any way (i.e. by setting file/files/attachments, or adding an embed with local files).

Changed in version 2.6: This function was renamed from edit_original_message.

Parameters:
  • content (Optional[str]) – The content to edit the message with, or None to clear it.

  • embed (Optional[Embed]) – The new embed to replace the original with. This cannot be mixed with the embeds parameter. Could be None to remove the embed.

  • embeds (List[Embed]) – The new embeds to replace the original with. Must be a maximum of 10. This cannot be mixed with the embed parameter. To remove all embeds [] should be passed.

  • file (File) – The file to upload. This cannot be mixed with the files parameter. Files will be appended to the message, see the attachments parameter to remove/replace existing files.

  • files (List[File]) – A list of files to upload. This cannot be mixed with the file parameter. Files will be appended to the message, see the attachments parameter to remove/replace existing files.

  • attachments (Optional[List[Attachment]]) –

    A list of attachments to keep in the message. If [] or None is passed then all existing attachments are removed. Keeps existing attachments if not provided.

    New in version 2.2.

    Changed in version 2.5: Supports passing None to clear attachments.

  • view (Optional[View]) – The updated view to update this message with. This cannot be mixed with components. If None is passed then the view is removed.

  • components (Optional[Union[disnake.ui.ActionRow, disnake.ui.WrappedComponent, List[Union[disnake.ui.ActionRow, disnake.ui.WrappedComponent, List[disnake.ui.WrappedComponent]]]]]) –

    A list of components to update this message with. This cannot be mixed with view. If None is passed then the components are removed.

    New in version 2.4.

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

Raises:
  • HTTPException – Editing the message failed.

  • Forbidden – Edited a message that is not yours.

  • TypeError – You specified both embed and embeds or file and files

  • ValueError – The length of embeds was invalid.

Returns:

The newly edited message.

Return type:

InteractionMessage

expires_at

Returns the interaction’s expiration time in UTC.

This is exactly 15 minutes after the interaction was created.

New in version 2.5.

Type:

datetime.datetime

followup

Returns the follow up webhook for follow up interactions.

Type:

Webhook

property guild[source]

The guild the interaction was sent from.

Type:

Optional[Guild]

is_expired()[source]

Whether the interaction can still be used to make requests to Discord.

This does not take into account the 3 second limit for the initial response.

New in version 2.5.

Return type:

bool

me

Union[Member, ClientUser]: Similar to Guild.me except it may return the ClientUser in private message contexts.

await original_response()[source]

This function is a coroutine.

Fetches the original interaction response message associated with the interaction.

Here is a table with response types and their associated original response:

Response type

Original response

InteractionResponse.send_message()

The message you sent

InteractionResponse.edit_message()

The message you edited

InteractionResponse.defer()

The message with thinking state (bot is thinking…)

Other response types

None

Repeated calls to this will return a cached value.

Changed in version 2.6: This function was renamed from original_message.

Raises:

HTTPException – Fetching the original response message failed.

Returns:

The original interaction response message.

Return type:

InteractionMessage

property permissions[source]

The resolved permissions of the member in the channel, including overwrites.

In a guild context, this is provided directly by Discord.

In a non-guild context this will be an instance of Permissions.private_channel().

Type:

Permissions

response

Returns an object responsible for handling responding to the interaction.

A response can only be done once. If secondary messages need to be sent, consider using followup instead.

Type:

InteractionResponse

await send(content=None, *, embed=..., embeds=..., file=..., files=..., allowed_mentions=..., view=..., components=..., tts=False, ephemeral=False, suppress_embeds=False, delete_after=...)[source]

This function is a coroutine.

Sends a message using either response.send_message or followup.send.

If the interaction hasn’t been responded to yet, this method will call response.send_message. Otherwise, it will call followup.send.

Note

This method does not return a Message object. If you need a message object, use original_response() to fetch it, or use followup.send directly instead of this method if you’re sending a followup message.

Parameters:
  • content (Optional[str]) – The content of the message to send.

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

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

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

  • files (List[File]) – A list of files to upload. Must be a maximum of 10. This cannot be mixed with the file parameter.

  • allowed_mentions (AllowedMentions) – Controls the mentions being processed in this message. If this is passed, then the object is merged with Client.allowed_mentions. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set in Client.allowed_mentions. If no object is passed at all then the defaults given by Client.allowed_mentions are used instead.

  • tts (bool) – Whether the message should be sent using text-to-speech.

  • view (disnake.ui.View) – The view to send with the message. This cannot be mixed with components.

  • components (Union[disnake.ui.ActionRow, disnake.ui.WrappedComponent, List[Union[disnake.ui.ActionRow, disnake.ui.WrappedComponent, List[disnake.ui.WrappedComponent]]]]) –

    A list of components to send with the message. This cannot be mixed with view.

    New in version 2.4.

  • ephemeral (bool) – Whether the message should only be visible to the user who started the interaction. If a view is sent with an ephemeral message and it has no timeout set then the timeout is set to 15 minutes.

  • suppress_embeds (bool) –

    Whether to suppress embeds for the message. This hides all embeds from the UI if set to True.

    New in version 2.5.

  • delete_after (float) – If provided, the number of seconds to wait in the background before deleting the message we just sent. If the deletion fails, then it is silently ignored.

Raises:
property user[source]

The user or member that sent the interaction. There is an alias for this named author.

Type:

Union[User, Member]

InteractionResponse
Attributes
Methods
class disnake.InteractionResponse[source]

Represents a Discord interaction response.

This type can be accessed through Interaction.response.

New in version 2.0.

property type[source]

If a response was successfully made, this is the type of the response.

New in version 2.6.

Type:

Optional[InteractionResponseType]

is_done()[source]

Whether an interaction response has been done before.

An interaction can only be responded to once.

Return type:

bool

await defer(*, with_message=..., ephemeral=...)[source]

This function is a coroutine.

Defers the interaction response.

This is typically used when the interaction is acknowledged and a secondary action will be done later.

Changed in version 2.5: Raises TypeError when an interaction cannot be deferred.

Parameters:
Raises:
await pong()[source]

This function is a coroutine.

Pongs the ping interaction.

This should rarely be used.

Raises:
await send_message(content=None, *, embed=..., embeds=..., file=..., files=..., allowed_mentions=..., view=..., components=..., tts=False, ephemeral=False, suppress_embeds=False, delete_after=...)[source]

This function is a coroutine.

Responds to this interaction by sending a message.

Parameters:
  • content (Optional[str]) – The content of the message to send.

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

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

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

  • files (List[File]) – A list of files to upload. Must be a maximum of 10. This cannot be mixed with the file parameter.

  • allowed_mentions (AllowedMentions) – Controls the mentions being processed in this message.

  • view (disnake.ui.View) – The view to send with the message. This cannot be mixed with components.

  • components (Union[disnake.ui.ActionRow, disnake.ui.WrappedComponent, List[Union[disnake.ui.ActionRow, disnake.ui.WrappedComponent, List[disnake.ui.WrappedComponent]]]]) –

    A list of components to send with the message. This cannot be mixed with view.

    New in version 2.4.

  • tts (bool) – Whether the message should be sent using text-to-speech.

  • ephemeral (bool) – Whether the message should only be visible to the user who started the interaction. If a view is sent with an ephemeral message and it has no timeout set then the timeout is set to 15 minutes.

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

  • suppress_embeds (bool) –

    Whether to suppress embeds for the message. This hides all embeds from the UI if set to True.

    New in version 2.5.

Raises:
await edit_message(content=..., *, embed=..., embeds=..., file=..., files=..., attachments=..., allowed_mentions=..., view=..., components=...)[source]

This function is a coroutine.

Responds to this interaction by editing the original message of a component interaction or modal interaction (if the modal was sent in response to a component interaction).

Changed in version 2.5: Now supports editing the original message of modal interactions that started from a component.

Note

If the original message has embeds with images that were created from local files (using the file parameter with Embed.set_image() or Embed.set_thumbnail()), those images will be removed if the message’s attachments are edited in any way (i.e. by setting file/files/attachments, or adding an embed with local files).

Parameters:
  • content (Optional[str]) – The new content to replace the message with. None removes the content.

  • embed (Optional[Embed]) – The new embed to replace the original with. This cannot be mixed with the embeds parameter. Could be None to remove the embed.

  • embeds (List[Embed]) – The new embeds to replace the original with. Must be a maximum of 10. This cannot be mixed with the embed parameter. To remove all embeds [] should be passed.

  • file (File) –

    The file to upload. This cannot be mixed with the files parameter. Files will be appended to the message.

    New in version 2.2.

  • files (List[File]) –

    A list of files to upload. This cannot be mixed with the file parameter. Files will be appended to the message.

    New in version 2.2.

  • attachments (Optional[List[Attachment]]) –

    A list of attachments to keep in the message. If [] or None is passed then all existing attachments are removed. Keeps existing attachments if not provided.

    New in version 2.4.

    Changed in version 2.5: Supports passing None to clear attachments.

  • allowed_mentions (AllowedMentions) – Controls the mentions being processed in this message.

  • view (Optional[View]) – The updated view to update this message with. This cannot be mixed with components. If None is passed then the view is removed.

  • components (Optional[Union[disnake.ui.ActionRow, disnake.ui.WrappedComponent, List[Union[disnake.ui.ActionRow, disnake.ui.WrappedComponent, List[disnake.ui.WrappedComponent]]]]]) –

    A list of components to update this message with. This cannot be mixed with view. If None is passed then the components are removed.

    New in version 2.4.

Raises:
await autocomplete(*, choices)[source]

This function is a coroutine.

Responds to this interaction by displaying a list of possible autocomplete results. Only works for autocomplete interactions.

Parameters:

choices (Union[List[OptionChoice], List[Union[str, int]], Dict[str, Union[str, int]]]) – The list of choices to suggest.

Raises:
await send_modal(modal=None, *, title=None, custom_id=None, components=None)[source]

This function is a coroutine.

Responds to this interaction by displaying a modal.

New in version 2.4.

Note

Not passing the modal parameter here will not register a callback, and a on_modal_submit() interaction will need to be handled manually.

Parameters:
Raises:
InteractionMessage
class disnake.InteractionMessage[source]

Represents the original interaction response message.

This allows you to edit or delete the message associated with the interaction response. To retrieve this object see Interaction.original_response().

This inherits from disnake.Message with changes to edit() and delete() to work.

New in version 2.0.

type

The type of message.

Type:

MessageType

author

A Member that sent the message. If channel is a private channel, then it is a User instead.

Type:

Union[Member, abc.User]

content

The actual contents of the message.

Type:

str

embeds

A list of embeds the message has.

Type:

List[Embed]

channel

The channel that the message was sent from. Could be a DMChannel or GroupChannel if it’s a private message.

Type:

Union[TextChannel, VoiceChannel, Thread, DMChannel, GroupChannel, PartialMessageable]

reference

The message that this message references. This is only applicable to message replies.

Type:

Optional[MessageReference]

interaction

The interaction that this message references. This exists only when the message is a response to an interaction without an existing message.

New in version 2.1.

Type:

Optional[InteractionReference]

mention_everyone

Specifies if the message mentions everyone.

Note

This does not check if the @everyone or the @here text is in the message itself. Rather this boolean indicates if either the @everyone or the @here text is in the message and it did end up mentioning.

Type:

bool

mentions

A list of Member that were mentioned. If the message is in a private message then the list will be of User instead.

Warning

The order of the mentions list is not in any particular order so you should not rely on it. This is a Discord limitation, not one with the library.

Type:

List[abc.User]

role_mentions

A list of Role that were mentioned. If the message is in a private message then the list is always empty.

Type:

List[Role]

id

The message ID.

Type:

int

webhook_id

The ID of the application that sent this message.

Type:

Optional[int]

attachments

A list of attachments given to a message.

Type:

List[Attachment]

pinned

Specifies if the message is currently pinned.

Type:

bool

flags

Extra features of the message.

Type:

MessageFlags

reactions

Reactions to a message. Reactions can be either custom emoji or standard unicode emoji.

Type:

List[Reaction]

stickers

A list of sticker items given to the message.

Type:

List[StickerItem]

components

A list of components in the message.

Type:

List[Component]

guild

The guild that the message belongs to, if applicable.

Type:

Optional[Guild]

await add_reaction(emoji)[source]

This function is a coroutine.

Adds a reaction to the message.

The emoji may be a unicode emoji or a custom guild Emoji.

You must have the read_message_history permission to use this. If nobody else has reacted to the message using this emoji, the add_reactions permission is required.

Changed in version 2.6: Raises TypeError instead of InvalidArgument.

Parameters:

emoji (Union[Emoji, Reaction, PartialEmoji, str]) – The emoji to react with.

Raises:
  • HTTPException – Adding the reaction failed.

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

  • NotFound – The emoji you specified was not found.

  • TypeError – The emoji parameter is invalid.

channel_mentions

A list of abc.GuildChannel that were mentioned. If the message is in a private message then the list is always empty.

Type:

List[abc.GuildChannel]

clean_content

A property that returns the content in a “cleaned up” manner. This basically means that mentions are transformed into the way the client shows it. e.g. <#id> will transform into #name.

This will also transform @everyone and @here mentions into non-mentions.

Note

This does not affect markdown. If you want to escape or remove markdown then use utils.escape_markdown() or utils.remove_markdown() respectively, along with this function.

Type:

str

await clear_reaction(emoji)[source]

This function is a coroutine.

Clears a specific reaction from the message.

The emoji may be a unicode emoji or a custom guild Emoji.

You need the manage_messages permission to use this.

New in version 1.3.

Changed in version 2.6: Raises TypeError instead of InvalidArgument.

Parameters:

emoji (Union[Emoji, Reaction, PartialEmoji, str]) – The emoji to clear.

Raises:
  • HTTPException – Clearing the reaction failed.

  • Forbidden – You do not have the proper permissions to clear the reaction.

  • NotFound – The emoji you specified was not found.

  • TypeError – The emoji parameter is invalid.

await clear_reactions()[source]

This function is a coroutine.

Removes all the reactions from the message.

You need the manage_messages permission to use this.

Raises:
  • HTTPException – Removing the reactions failed.

  • Forbidden – You do not have the proper permissions to remove all the reactions.

await create_thread(*, name, auto_archive_duration=None, slowmode_delay=None, reason=None)[source]

This function is a coroutine.

Creates a public thread from this message.

You must have create_public_threads in order to create a public thread from a message.

The channel this message belongs in must be a TextChannel.

New in version 2.0.

Changed in version 2.6: Raises TypeError instead of InvalidArgument.

Parameters:
  • name (str) – The name of the thread.

  • auto_archive_duration (Union[int, ThreadArchiveDuration]) – The duration in minutes before a thread is automatically archived for inactivity. If not provided, the channel’s default auto archive duration is used. Must be one of 60, 1440, 4320, or 10080.

  • slowmode_delay (Optional[int]) –

    Specifies the slowmode rate limit for users in this thread, in seconds. A value of 0 disables slowmode. The maximum value possible is 21600. If set to None or not provided, slowmode is inherited from the parent channel.

    New in version 2.3.

  • reason (Optional[str]) –

    The reason for creating the thread. Shows up on the audit log.

    New in version 2.5.

Raises:
  • Forbidden – You do not have permissions to create a thread.

  • HTTPException – Creating the thread failed.

  • TypeError – This message does not have guild info attached.

Returns:

The created thread.

Return type:

Thread

property created_at[source]

The message’s creation time in UTC.

Type:

datetime.datetime

property edited_at[source]

An aware UTC datetime object containing the edited time of the message.

Type:

Optional[datetime.datetime]

is_system()[source]

Whether the message is a system message.

A system message is a message that is constructed entirely by the Discord API in response to something.

New in version 1.3.

Return type:

bool

property jump_url[source]

Returns a URL that allows the client to jump to this message.

Type:

str

await pin(*, reason=None)[source]

This function is a coroutine.

Pins the message.

You must have the manage_messages permission to do this in a non-private channel context.

Parameters:

reason (Optional[str]) –

The reason for pinning the message. Shows up on the audit log.

New in version 1.4.

Raises:
  • Forbidden – You do not have permissions to pin the message.

  • NotFound – The message or channel was not found or deleted.

  • HTTPException – Pinning the message failed, probably due to the channel having more than 50 pinned messages.

await publish()[source]

This function is a coroutine.

Publishes this message to your announcement channel.

You must have the send_messages permission to do this.

If the message is not your own then the manage_messages permission is also needed.

Raises:
  • Forbidden – You do not have the proper permissions to publish this message.

  • HTTPException – Publishing the message failed.

raw_channel_mentions

A property that returns an array of channel IDs matched with the syntax of <#channel_id> in the message content.

Type:

List[int]

raw_mentions

A property that returns an array of user IDs matched with the syntax of <@user_id> in the message content.

This allows you to receive the user IDs of mentioned users even in a private message context.

Type:

List[int]

raw_role_mentions

A property that returns an array of role IDs matched with the syntax of <@&role_id> in the message content.

Type:

List[int]

await remove_reaction(emoji, member)[source]

This function is a coroutine.

Removes a reaction by the member from the message.

The emoji may be a unicode emoji or a custom guild Emoji.

If the reaction is not your own (i.e. member parameter is not you) then the manage_messages permission is needed.

The member parameter must represent a member and meet the abc.Snowflake abc.

Changed in version 2.6: Raises TypeError instead of InvalidArgument.

Parameters:
Raises:
  • HTTPException – Removing the reaction failed.

  • Forbidden – You do not have the proper permissions to remove the reaction.

  • NotFound – The member or emoji you specified was not found.

  • TypeError – The emoji parameter is invalid.

await reply(content=None, *, fail_if_not_exists=True, **kwargs)[source]

This function is a coroutine.

A shortcut method to abc.Messageable.send() to reply to the Message.

New in version 1.6.

Changed in version 2.3: Added fail_if_not_exists keyword argument. Defaults to True.

Changed in version 2.6: Raises TypeError or ValueError instead of InvalidArgument.

Parameters:

fail_if_not_exists (bool) –

Whether replying using the message reference should raise HTTPException if the message no longer exists or Discord could not fetch the message.

New in version 2.3.

Raises:
  • HTTPException – Sending the message failed.

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

  • TypeError – You specified both embed and embeds, or file and files, or view and components.

  • ValueError – The files or embeds list is too large.

Returns:

The message that was sent.

Return type:

Message

system_content

A property that returns the content that is rendered regardless of the Message.type.

In the case of MessageType.default and MessageType.reply, this just returns the regular Message.content. Otherwise this returns an English message denoting the contents of the system message.

Type:

str

property thread[source]

The thread started from this message. None if no thread has been started.

New in version 2.4.

Type:

Optional[Thread]

to_reference(*, fail_if_not_exists=True)[source]

Creates a MessageReference from the current message.

New in version 1.6.

Parameters:

fail_if_not_exists (bool) –

Whether replying using the message reference should raise HTTPException if the message no longer exists or Discord could not fetch the message.

New in version 1.7.

Returns:

The reference to this message.

Return type:

MessageReference

await unpin(*, reason=None)[source]

This function is a coroutine.

Unpins the message.

You must have the manage_messages permission to do this in a non-private channel context.

Parameters:

reason (Optional[str]) –

The reason for unpinning the message. Shows up on the audit log.

New in version 1.4.

Raises:
  • Forbidden – You do not have permissions to unpin the message.

  • NotFound – The message or channel was not found or deleted.

  • HTTPException – Unpinning the message failed.

await edit(content=..., *, embed=..., embeds=..., file=..., files=..., attachments=..., allowed_mentions=..., view=..., components=...)[source]

This function is a coroutine.

Edits the message.

Note

If the original message has embeds with images that were created from local files (using the file parameter with Embed.set_image() or Embed.set_thumbnail()), those images will be removed if the message’s attachments are edited in any way (i.e. by setting file/files/attachments, or adding an embed with local files).

Parameters:
  • content (Optional[str]) – The content to edit the message with, or None to clear it.

  • embed (Optional[Embed]) – The new embed to replace the original with. This cannot be mixed with the embeds parameter. Could be None to remove the embed.

  • embeds (List[Embed]) – The new embeds to replace the original with. Must be a maximum of 10. This cannot be mixed with the embed parameter. To remove all embeds [] should be passed.

  • file (File) – The file to upload. This cannot be mixed with the files parameter. Files will be appended to the message, see the attachments parameter to remove/replace existing files.

  • files (List[File]) – A list of files to upload. This cannot be mixed with the file parameter. Files will be appended to the message, see the attachments parameter to remove/replace existing files.

  • attachments (Optional[List[Attachment]]) –

    A list of attachments to keep in the message. If [] or None is passed then all existing attachments are removed. Keeps existing attachments if not provided.

    New in version 2.2.

    Changed in version 2.5: Supports passing None to clear attachments.

  • view (Optional[View]) – The updated view to update this message with. This cannot be mixed with components. If None is passed then the view is removed.

  • components (Optional[Union[disnake.ui.ActionRow, disnake.ui.WrappedComponent, List[Union[disnake.ui.ActionRow, disnake.ui.WrappedComponent, List[disnake.ui.WrappedComponent]]]]]) –

    A list of components to update this message with. This cannot be mixed with view. If None is passed then the components are removed.

    New in version 2.4.

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

Raises:
  • HTTPException – Editing the message failed.

  • Forbidden – Edited a message that is not yours.

  • TypeError – You specified both embed and embeds or file and files

  • ValueError – The length of embeds was invalid.

Returns:

The newly edited message.

Return type:

InteractionMessage

await delete(*, delay=None)[source]

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.

ApplicationCommandInteractionData
class disnake.ApplicationCommandInteractionData[source]

Represents the data of an interaction with an application command.

New in version 2.1.

id

The application command ID.

Type:

int

name

The application command name.

Type:

str

type

The application command type.

Type:

ApplicationCommandType

resolved

All resolved objects related to this interaction.

Type:

ApplicationCommandInteractionDataResolved

options

A list of options from the API.

Type:

List[ApplicationCommandInteractionDataOption]

target_id

ID of the user or message targetted by a user or message command

Type:

int

target

The user or message targetted by a user or message command

Type:

Union[User, Member, Message]

property focused_option[source]

The focused option

ApplicationCommandInteractionDataOption
class disnake.ApplicationCommandInteractionDataOption[source]

This class represents the structure of an interaction data option from the API.

name

The option’s name.

Type:

str

type

The option’s type.

Type:

OptionType

value

The option’s value.

Type:

Any

options

The list of options of this option. Only exists for subcommands and groups.

Type:

List[ApplicationCommandInteractionDataOption]

focused

Whether this option is focused by the user. May be True in autocomplete interactions.

Type:

bool

ApplicationCommandInteractionDataResolved
class disnake.ApplicationCommandInteractionDataResolved[source]

Represents the resolved data related to an interaction with an application command.

New in version 2.1.

members

A mapping of IDs to partial members (deaf and mute attributes are missing).

Type:

Dict[int, Member]

users

A mapping of IDs to users.

Type:

Dict[int, User]

roles

A mapping of IDs to roles.

Type:

Dict[int, Role]

channels

A mapping of IDs to partial channels (only id, name and permissions are included, threads also have thread_metadata and parent_id).

Type:

Dict[int, Channel]

messages

A mapping of IDs to messages.

Type:

Dict[int, Message]

attachments

A mapping of IDs to attachments.

New in version 2.4.

Type:

Dict[int, Attachment]

get(key)[source]

Return the value for key if key is in the dictionary, else default.

MessageInteractionData
class disnake.MessageInteractionData[source]

Represents the data of an interaction with a message component.

New in version 2.1.

custom_id

The custom ID of the component.

Type:

str

component_type

The type of the component.

Type:

ComponentType

values

The values the user has selected.

Type:

Optional[List[str]]

ModalInteractionData
Attributes
class disnake.ModalInteractionData[source]

Represents the data of an interaction with a modal.

New in version 2.4.

custom_id

The custom ID of the modal.

Type:

str

components

The raw component data of the modal interaction, as provided by Discord. This does not contain all fields of the components due to API limitations.

New in version 2.6.

Type:

List[dict]

Member
class disnake.Member[source]

Represents a Discord member to a Guild.

This implements a lot of the functionality of User.

x == y

Checks if two members are equal. Note that this works with User instances too.

x != y

Checks if two members are not equal. Note that this works with User instances too.

hash(x)

Returns the member’s hash.

str(x)

Returns the member’s name with the discriminator.

joined_at

An aware datetime object that specifies the date and time in UTC that the member joined the guild. If the member left and rejoined the guild, this will be the latest date. In certain cases, this can be None.

Type:

Optional[datetime.datetime]

activities

The activities that the user is currently doing.

Note

Due to a Discord API limitation, a user’s Spotify activity may not appear if they are listening to a song with a title longer than 128 characters. See #1738 for more information.

Type:

Tuple[Union[BaseActivity, Spotify]]

guild

The guild that the member belongs to.

Type:

Guild

nick

The guild specific nickname of the user.

Type:

Optional[str]

pending

Whether the member is pending member verification.

New in version 1.6.

Type:

bool

premium_since

An aware datetime object that specifies the date and time in UTC when the member used their “Nitro boost” on the guild, if available. This could be None.

Type:

Optional[datetime.datetime]

async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)[source]

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

You must have Permissions.read_message_history permission to use this.

Examples

Usage

counter = 0
async for message in channel.history(limit=200):
    if message.author == client.user:
        counter += 1

Flattening into a list:

messages = await channel.history(limit=123).flatten()
# messages is now a list of Message...

All parameters are optional.

Parameters:
  • limit (Optional[int]) – The number of messages to retrieve. If None, retrieves every message in the channel. Note, however, that this would make it a slow operation.

  • before (Optional[Union[abc.Snowflake, datetime.datetime]]) – Retrieve messages before this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.

  • after (Optional[Union[abc.Snowflake, datetime.datetime]]) – Retrieve messages after this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.

  • around (Optional[Union[abc.Snowflake, datetime.datetime]]) – Retrieve messages around this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time. When using this argument, the maximum limit is 101. Note that if the limit is an even number then this will return at most limit + 1 messages.

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

Raises:
  • Forbidden – You do not have permissions to get channel message history.

  • HTTPException – The request to get message history failed.

Yields:

Message – The message with the message data parsed.

async with typing()[source]

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

This is useful for denoting long computations in your bot.

Note

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

Example Usage:

async with channel.typing():
    # simulate something heavy
    await asyncio.sleep(10)

await channel.send('done!')
property name

Equivalent to User.name

property id

Equivalent to User.id

property bot

Equivalent to User.bot

property system

Equivalent to User.system

property created_at

Equivalent to User.created_at

property default_avatar

Equivalent to User.default_avatar

property avatar

Equivalent to User.avatar

property dm_channel

Equivalent to User.dm_channel

await create_dm()[source]

This function is a coroutine.

Creates a DMChannel with this user.

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

Returns:

The channel that was created.

Return type:

DMChannel

property mutual_guilds

Equivalent to User.mutual_guilds

property public_flags

Equivalent to User.public_flags

property banner

Equivalent to User.banner

property accent_color

Equivalent to User.accent_color

property accent_colour

Equivalent to User.accent_colour

property raw_status[source]

The member’s overall status as a string value.

New in version 1.5.

Type:

str

property status[source]

The member’s overall status. If the value is unknown, then it will be a str instead.

Type:

Status

property mobile_status[source]

The member’s status on a mobile device, if applicable.

Type:

Status

property desktop_status[source]

The member’s status on the desktop client, if applicable.

Type:

Status

property web_status[source]

The member’s status on the web client, if applicable.

Type:

Status

is_on_mobile()[source]

Whether the member is active on a mobile device.

Return type:

bool

property colour[source]

A property that returns a colour denoting the rendered colour for the member. If the default colour is the one rendered then an instance of Colour.default() is returned.

There is an alias for this named color.

Type:

Colour

property color[source]

A property that returns a color denoting the rendered color for the member. If the default color is the one rendered then an instance of Colour.default() is returned.

There is an alias for this named colour.

Type:

Colour

property roles[source]

A list of Role that the member belongs to. Note that the first element of this list is always the default @everyone’ role.

These roles are sorted by their position in the role hierarchy.

Type:

List[Role]

property mention[source]

Returns a string that allows you to mention the member.

Type:

str

property display_name[source]

Returns the user’s display name.

For regular users this is just their username, but if they have a guild specific nickname then that is returned instead.

Type:

str

property display_avatar[source]

Returns the member’s display avatar.

For regular members this is just their avatar, but if they have a guild specific avatar then that is returned instead.

New in version 2.0.

Type:

Asset

property guild_avatar[source]

Returns an Asset for the guild avatar the member has. If unavailable, None is returned.

New in version 2.0.

Type:

Optional[Asset]

property activity[source]

Returns the primary activity the user is currently doing. Could be None if no activity is being done.

Note

Due to a Discord API limitation, this may be None if the user is listening to a song on Spotify with a title longer than 128 characters. See #1738 for more information.

Note

A user may have multiple activities, these can be accessed under activities.

Type:

Optional[Union[BaseActivity, Spotify]]

mentioned_in(message)[source]

Whether the member is mentioned in the specified message.

Parameters:

message (Message) – The message to check.

Returns:

Indicates if the member is mentioned in the message.

Return type:

bool

property top_role[source]

Returns the member’s highest role.

This is useful for figuring where a member stands in the role hierarchy chain.

Type:

Role

property role_icon[source]

Returns the member’s displayed role icon, if any.

New in version 2.5.

Type:

Optional[Union[Asset, PartialEmoji]]

property guild_permissions[source]

Returns the member’s guild permissions.

This only takes into consideration the guild permissions and not most of the implied permissions or any of the channel permission overwrites. For 100% accurate permission calculation, please use abc.GuildChannel.permissions_for().

This does take into consideration guild ownership and the administrator implication.

Type:

Permissions

property voice[source]

Returns the member’s current voice state.

Type:

Optional[VoiceState]

property current_timeout[source]

Returns the datetime when the timeout expires, if any.

New in version 2.3.

Type:

Optional[datetime.datetime]

await ban(*, clean_history_duration=..., delete_message_days=..., reason=None)[source]

This function is a coroutine.

Bans this member. Equivalent to Guild.ban().

await unban(*, reason=None)[source]

This function is a coroutine.

Unbans this member. Equivalent to Guild.unban().

await kick(*, reason=None)[source]

This function is a coroutine.

Kicks this member. Equivalent to Guild.kick().

await edit(*, nick=..., mute=..., deafen=..., suppress=..., roles=..., voice_channel=..., timeout=..., reason=None)[source]

This function is a coroutine.

Edits the member’s data.

Depending on the parameter passed, this requires different permissions listed below:

All parameters are optional.

Changed in version 1.1: Can now pass None to voice_channel to kick a member from voice.

Changed in version 2.0: The newly member is now optionally returned, if applicable.

Parameters:
  • nick (Optional[str]) – The member’s new nickname. Use None to remove the nickname.

  • mute (bool) – Whether the member should be guild muted or un-muted.

  • deafen (bool) – Whether the member should be guild deafened or un-deafened.

  • suppress (bool) –

    Whether the member should be suppressed in stage channels.

    New in version 1.7.

  • roles (Sequence[Role]) – The member’s new list of roles. This replaces the roles.

  • voice_channel (Optional[VoiceChannel]) – The voice channel to move the member to. Pass None to kick them from voice.

  • timeout (Optional[Union[float, datetime.timedelta, datetime.datetime]]) –

    The duration (seconds or timedelta) or the expiry (datetime) of the timeout; until then, the member will not be able to interact with the guild. Set to None to remove the timeout. Supports up to 28 days in the future.

    New in version 2.3.

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

Raises:
  • Forbidden – You do not have the proper permissions to the action requested.

  • HTTPException – The operation failed.

Returns:

The newly updated member, if applicable. This is only returned when certain fields are updated.

Return type:

Optional[Member]

await request_to_speak()[source]

This function is a coroutine.

Requests to speak in the connected channel.

Only applies to stage channels.

Note

Requesting members that are not the client is equivalent to edit providing suppress as False.

New in version 1.7.

Raises:
  • Forbidden – You do not have the proper permissions to the action requested.

  • HTTPException – The operation failed.

await fetch_message(id, /)[source]

This function is a coroutine.

Retrieves a single Message from the destination.

Parameters:

id (int) – The message ID to look for.

Raises:
  • NotFound – The specified message was not found.

  • Forbidden – You do not have the permissions required to get a message.

  • HTTPException – Retrieving the message failed.

Returns:

The message asked for.

Return type:

Message

await move_to(channel, *, reason=None)[source]

This function is a coroutine.

Moves a member to a new voice channel (they must be connected first).

You must have move_members permission to use this.

This raises the same exceptions as edit().

Changed in version 1.1: Can now pass None to kick a member from voice.

Parameters:
  • channel (Optional[VoiceChannel]) – The new voice channel to move the member to. Pass None to kick them from voice.

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

await pins()[source]

This function is a coroutine.

Retrieves all messages that are currently pinned in the channel.

Note

Due to a limitation with the Discord API, the Message objects returned by this method do not contain complete Message.reactions data.

Raises:

HTTPException – Retrieving the pinned messages failed.

Returns:

The messages that are currently pinned.

Return type:

List[Message]

await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, suppress_embeds=False, allowed_mentions=None, reference=None, mention_author=None, view=None, components=None)[source]

This function is a coroutine.

Sends a message to the destination with the content given.

The content must be a type that can convert to a string through str(content).

At least one of content, embed/embeds, file/files, stickers, components, or view must be provided.

To upload a single file, the file parameter should be used with a single File object. To upload multiple files, the files parameter should be used with a list of File objects. Specifying both parameters will lead to an exception.

To upload a single embed, the embed parameter should be used with a single Embed object. To upload multiple embeds, the embeds parameter should be used with a list of Embed objects. Specifying both parameters will lead to an exception.

Changed in version 2.6: Raises TypeError or ValueError instead of InvalidArgument.

Parameters:
  • content (Optional[str]) – The content of the message to send.

  • tts (bool) – Whether the message should be sent using text-to-speech.

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

  • embeds (List[Embed]) –

    A list of embeds to send with the content. Must be a maximum of 10. This cannot be mixed with the embed parameter.

    New in version 2.0.

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

  • files (List[File]) – A list of files to upload. Must be a maximum of 10. This cannot be mixed with the file parameter.

  • stickers (Sequence[Union[GuildSticker, StickerItem]]) –

    A list of stickers to upload. Must be a maximum of 3.

    New in version 2.0.

  • nonce (Union[str, int]) – The nonce to use for sending this message. If the message was successfully sent, then the message will have a nonce with this value.

  • delete_after (float) – If provided, the number of seconds to wait in the background before deleting the message we just sent. If the deletion fails, then it is silently ignored.

  • allowed_mentions (AllowedMentions) –

    Controls the mentions being processed in this message. If this is passed, then the object is merged with Client.allowed_mentions. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set in Client.allowed_mentions. If no object is passed at all then the defaults given by Client.allowed_mentions are used instead.

    New in version 1.4.

  • reference (Union[Message, MessageReference, PartialMessage]) –

    A reference to the Message to which you are replying, this can be created using Message.to_reference() or passed directly as a Message. You can control whether this mentions the author of the referenced message using the AllowedMentions.replied_user attribute of allowed_mentions or by setting mention_author.

    New in version 1.6.

  • mention_author (Optional[bool]) –

    If set, overrides the AllowedMentions.replied_user attribute of allowed_mentions.

    New in version 1.6.

  • view (ui.View) –

    A Discord UI View to add to the message. This cannot be mixed with components.

    New in version 2.0.

  • components (Union[disnake.ui.ActionRow, disnake.ui.WrappedComponent, List[Union[disnake.ui.ActionRow, disnake.ui.WrappedComponent, List[disnake.ui.WrappedComponent]]]]) –

    A list of components to include in the message. This cannot be mixed with view.

    New in version 2.4.

  • suppress_embeds (bool) –

    Whether to suppress embeds for the message. This hides all embeds from the UI if set to True.

    New in version 2.5.

Raises:
Returns:

The message that was sent.

Return type:

Message

await trigger_typing()[source]

This function is a coroutine.

Triggers a typing indicator to the destination.

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

await add_roles(*roles, reason=None, atomic=True)[source]

This function is a coroutine.

Gives the member a number of Roles.

You must have manage_roles permission to use this, and the added Roles must appear lower in the list of roles than the highest role of the member.

Parameters:
  • *roles (abc.Snowflake) – An argument list of abc.Snowflake representing a Role to give to the member.

  • reason (Optional[str]) – The reason for adding these roles. Shows up on the audit log.

  • atomic (bool) – Whether to atomically add roles. This will ensure that multiple operations will always be applied regardless of the current state of the cache.

Raises:
await remove_roles(*roles, reason=None, atomic=True)[source]

This function is a coroutine.

Removes Roles from this member.

You must have manage_roles permission to use this, and the removed Roles must appear lower in the list of roles than the highest role of the member.

Parameters:
  • *roles (abc.Snowflake) – An argument list of abc.Snowflake representing a Role to remove from the member.

  • reason (Optional[str]) – The reason for removing these roles. Shows up on the audit log.

  • atomic (bool) – Whether to atomically remove roles. This will ensure that multiple operations will always be applied regardless of the current state of the cache.

Raises:
  • Forbidden – You do not have permissions to remove these roles.

  • HTTPException – Removing the roles failed.

get_role(role_id, /)[source]

Returns a role with the given ID from roles which the member has.

New in version 2.0.

Parameters:

role_id (int) – The role ID to search for.

Returns:

The role or None if not found in the member’s roles.

Return type:

Optional[Role]

await timeout(*, duration=..., until=..., reason=None)[source]

This function is a coroutine.

Times out the member from the guild; until then, the member will not be able to interact with the guild.

Exactly one of duration or until must be provided. To remove a timeout, set one of the parameters to None.

You must have the Permissions.moderate_members permission to do this.

New in version 2.3.

Parameters:
  • duration (Optional[Union[float, datetime.timedelta]]) – The duration (seconds or timedelta) of the member’s timeout. Set to None to remove the timeout. Supports up to 28 days in the future. May not be used in combination with the until parameter.

  • until (Optional[datetime.datetime]) – The expiry date/time of the member’s timeout. Set to None to remove the timeout. Supports up to 28 days in the future. May not be used in combination with the duration parameter.

  • reason (Optional[str]) – The reason for this timeout. Appears on the audit log.

Raises:
  • Forbidden – You do not have permissions to timeout this member.

  • HTTPException – Timing out the member failed.

Returns:

The newly updated member.

Return type:

Member

Spotify
class disnake.Spotify[source]

Represents a Spotify listening activity from Discord.

x == y

Checks if two activities are equal.

x != y

Checks if two activities are not equal.

hash(x)

Returns the activity’s hash.

str(x)

Returns the string ‘Spotify’.

property type[source]

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

It always returns ActivityType.listening.

Type:

ActivityType

property colour[source]

Returns the Spotify integration colour, as a Colour.

There is an alias for this named color

Type:

Colour

property color[source]

Returns the Spotify integration colour, as a Colour.

There is an alias for this named colour

Type:

Colour

property name[source]

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

Type:

str

property title[source]

The title of the song being played.

Type:

str

property artists[source]

The artists of the song being played.

Type:

List[str]

property artist[source]

The artist of the song being played.

This does not attempt to split the artist information into multiple artists. Useful if there’s only a single artist.

Type:

str

property album[source]

The album that the song being played belongs to.

Type:

str

property album_cover_url[source]

The album cover image URL from Spotify’s CDN.

Type:

str

property track_id[source]

The track ID used by Spotify to identify this song.

Type:

str

property track_url[source]

The track URL to listen on Spotify.

New in version 2.0.

Type:

str

property duration[source]

The duration of the song being played, if applicable.

Changed in version 2.6: This attribute can now be None.

Type:

Optional[datetime.timedelta]

property party_id[source]

The party ID of the listening party.

Type:

str

property created_at[source]

When the user started doing this activity in UTC.

New in version 1.3.

Type:

Optional[datetime.datetime]

property end[source]

When the user will stop doing this activity in UTC, if applicable.

Changed in version 2.6: This attribute can now be None.

Type:

Optional[datetime.datetime]

property start[source]

When the user started doing this activity in UTC, if applicable.

Changed in version 2.6: This attribute can now be None.

Type:

Optional[datetime.datetime]

VoiceState
class disnake.VoiceState[source]

Represents a Discord user’s voice state.

deaf

Whether the user is currently deafened by the guild.

Type:

bool

mute

Whether the user is currently muted by the guild.

Type:

bool

self_mute

Whether the user is currently muted by their own accord.

Type:

bool

self_deaf

Whether the user is currently deafened by their own accord.

Type:

bool

self_stream

Whether the user is currently streaming via ‘Go Live’ feature.

New in version 1.3.

Type:

bool

self_video

Whether the user is currently broadcasting video.

Type:

bool

suppress

Whether the user is suppressed from speaking.

Only applies to stage channels.

New in version 1.7.

Type:

bool

requested_to_speak_at

An aware datetime object that specifies the date and time in UTC that the member requested to speak. It will be None if they are not requesting to speak anymore or have been accepted to speak.

Only applies to stage channels.

New in version 1.7.

Type:

Optional[datetime.datetime]

afk

Whether the user is currently in the AFK channel in the guild.

Type:

bool

channel

The voice channel that the user is currently connected to. None if the user is not currently in a voice channel.

Type:

Optional[Union[VoiceChannel, StageChannel]]

Emoji
class disnake.Emoji[source]

Represents a custom emoji.

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

x == y

Checks if two emoji are the same.

x != y

Checks if two emoji are not the same.

hash(x)

Return the emoji’s hash.

iter(x)

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

str(x)

Returns the emoji rendered for Discord.

name

The emoji’s name.

Type:

str

id

The emoji’s ID.

Type:

int

require_colons

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

Type:

bool

animated

Whether the emoji is animated or not.

Type:

bool

managed

Whether the emoji is managed by a Twitch integration.

Type:

bool

guild_id

The guild ID the emoji belongs to.

Type:

int

available

Whether the emoji is available for use.

Type:

bool

user

The user that created the emoji. This can only be retrieved using Guild.fetch_emoji() and having manage_emojis permission.

Type:

Optional[User]

property created_at[source]

Returns the emoji’s creation time in UTC.

Type:

datetime.datetime

property url[source]

Returns the URL of the emoji.

Type:

str

property roles[source]

A list of roles that are allowed to use this emoji.

If roles is empty, the emoji is unrestricted.

Type:

List[Role]

property guild[source]

The guild this emoji belongs to.

Type:

Guild

is_usable()[source]

Whether the bot can use this emoji.

New in version 1.3.

Return type:

bool

await delete(*, reason=None)[source]

This function is a coroutine.

Deletes the custom emoji.

You must have manage_emojis permission to do this.

Parameters:

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

Raises:
await edit(*, name=..., roles=..., reason=None)[source]

This function is a coroutine.

Edits the custom emoji.

You must have manage_emojis permission to do this.

Changed in version 2.0: The newly updated emoji is returned.

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

  • roles (Optional[List[Snowflake]]) – A list of roles that can use this emoji. An empty list can be passed to make it available to everyone.

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

Raises:
Returns:

The newly updated emoji.

Return type:

Emoji

await read()[source]

This function is a coroutine.

Retrieves the content of this asset as a bytes object.

Raises:
Returns:

The content of the asset.

Return type:

bytes

await save(fp, *, seek_begin=True)[source]

This function is a coroutine.

Saves this asset into a file-like object.

Parameters:
  • fp (Union[io.BufferedIOBase, os.PathLike]) – The file-like object to save this asset to or the filename to use. If a filename is passed then a file is created with that filename and used instead.

  • seek_begin (bool) – Whether to seek to the beginning of the file after saving is successfully done.

Raises:
Returns:

The number of bytes written.

Return type:

int

await to_file(*, spoiler=False, filename=None, description=None)[source]

This function is a coroutine.

Converts the asset into a File suitable for sending via abc.Messageable.send().

New in version 2.5.

Changed in version 2.6: Raises TypeError instead of InvalidArgument.

Parameters:
  • spoiler (bool) – Whether the file is a spoiler.

  • filename (Optional[str]) – The filename to display when uploading to Discord. If this is not given, it defaults to the name of the asset’s URL.

  • description (Optional[str]) – The file’s description.

Raises:
Returns:

The asset as a file suitable for sending.

Return type:

File

PartialEmoji
class disnake.PartialEmoji[source]

Represents a “partial” emoji.

This model will be given in two scenarios:

x == y

Checks if two emoji are the same.

x != y

Checks if two emoji are not the same.

hash(x)

Return the emoji’s hash.

str(x)

Returns the emoji rendered for Discord.

name

The custom emoji name, if applicable, or the unicode codepoint of the non-custom emoji. This can be None if the emoji got deleted (e.g. removing a reaction with a deleted emoji).

Type:

Optional[str]

animated

Whether the emoji is animated or not.

Type:

bool

id

The ID of the custom emoji, if applicable.

Type:

Optional[int]

classmethod from_str(value)[source]

Converts a Discord string representation of an emoji to a PartialEmoji.

The formats accepted are:

  • a:name:id

  • <a:name:id>

  • name:id

  • <:name:id>

If the format does not match then it is assumed to be a unicode emoji.

New in version 2.0.

Parameters:

value (str) – The string representation of an emoji.

Returns:

The partial emoji from this string.

Return type:

PartialEmoji

is_custom_emoji()[source]

Whether the partial emoji is a custom non-Unicode emoji.

Return type:

bool

is_unicode_emoji()[source]

Whether the partial emoji is a Unicode emoji.

Return type:

bool

property created_at[source]

Returns the emoji’s creation time in UTC, or None if it’s a Unicode emoji.

New in version 1.6.

Type:

Optional[datetime.datetime]

property url[source]

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

If this isn’t a custom emoji then an empty string is returned

Type:

str

await read()[source]

This function is a coroutine.

Retrieves the data of this emoji as a bytes object.

Changed in version 2.6: Raises TypeError instead of InvalidArgument.

Raises:
Returns:

The content of the asset.

Return type:

bytes

await save(fp, *, seek_begin=True)[source]

This function is a coroutine.

Saves this asset into a file-like object.

Parameters:
  • fp (Union[io.BufferedIOBase, os.PathLike]) – The file-like object to save this asset to or the filename to use. If a filename is passed then a file is created with that filename and used instead.

  • seek_begin (bool) – Whether to seek to the beginning of the file after saving is successfully done.

Raises:
Returns:

The number of bytes written.

Return type:

int

await to_file(*, spoiler=False, filename=None, description=None)[source]

This function is a coroutine.

Converts the asset into a File suitable for sending via abc.Messageable.send().

New in version 2.5.

Changed in version 2.6: Raises TypeError instead of InvalidArgument.

Parameters:
  • spoiler (bool) – Whether the file is a spoiler.

  • filename (Optional[str]) – The filename to display when uploading to Discord. If this is not given, it defaults to the name of the asset’s URL.

  • description (Optional[str]) – The file’s description.

Raises:
Returns:

The asset as a file suitable for sending.

Return type:

File

Role
class disnake.Role[source]

Represents a Discord role in a Guild.

x == y

Checks if two roles are equal.

x != y

Checks if two roles are not equal.

x > y

Checks if a role is higher than another in the hierarchy.

x < y

Checks if a role is lower than another in the hierarchy.

x >= y

Checks if a role is higher or equal to another in the hierarchy.

x <= y

Checks if a role is lower or equal to another in the hierarchy.

hash(x)

Return the role’s hash.

str(x)

Returns the role’s name.

id

The ID of the role.

Type:

int

name

The name of the role.

Type:

str

guild

The guild the role belongs to.

Type:

Guild

hoist

Indicates if the role will be displayed separately from other members.

Type:

bool

position

The position of the role. This number is usually positive. The bottom role has a position of 0.

Warning

Multiple roles can have the same position number. As a consequence of this, comparing via role position is prone to subtle bugs if checking for role hierarchy. The recommended and correct way to compare for roles in the hierarchy is using the comparison operators on the role objects themselves.

Type:

int

managed

Indicates if the role is managed by the guild through some form of integrations such as Twitch.

Type:

bool

mentionable

Indicates if the role can be mentioned by users.

Type:

bool

tags

The role tags associated with this role.

Type:

Optional[RoleTags]

is_default()[source]

Checks if the role is the default role.

Return type:

bool

is_bot_managed()[source]

Whether the role is associated with a bot.

New in version 1.6.

Return type:

bool

is_premium_subscriber()[source]

Whether the role is the premium subscriber, AKA “boost”, role for the guild.

New in version 1.6.

Return type:

bool

is_integration()[source]

Whether the role is managed by an integration.

New in version 1.6.

Return type:

bool

is_assignable()[source]

Whether the role is able to be assigned or removed by the bot.

New in version 2.0.

Return type:

bool

property permissions[source]

Returns the role’s permissions.

Type:

Permissions

property colour[source]

Returns the role colour. An alias exists under color.

Type:

Colour

property color[source]

Returns the role color. An alias exists under colour.

Type:

Colour

property icon[source]

Returns the role’s icon asset, if available.

New in version 2.0.

Type:

Optional[Asset]

property emoji[source]

Returns the role’s emoji, if available.

New in version 2.0.

Type:

Optional[PartialEmoji]

property created_at[source]

Returns the role’s creation time in UTC.

Type:

datetime.datetime

property mention[source]

Returns a string that allows you to mention a role.

Type:

str

property members[source]

Returns all the members with this role.

Type:

List[Member]

await edit(*, name=..., permissions=..., colour=..., color=..., hoist=..., icon=..., emoji=..., mentionable=..., position=..., reason=...)[source]

This function is a coroutine.

Edits the role.

You must have the manage_roles permission to use this.

All fields are optional.

Changed in version 1.4: Can now pass int to colour keyword-only parameter.

Changed in version 2.0: Edits are no longer in-place, the newly edited role is returned instead.

Changed in version 2.6: Raises TypeError or ValueError instead of InvalidArgument.

Parameters:
  • name (str) – The new role name to change to.

  • permissions (Permissions) – The new permissions to change to.

  • colour (Union[Colour, int]) – The new colour to change to. (aliased to color as well)

  • hoist (bool) – Indicates if the role should be shown separately in the member list.

  • icon (Optional[Union[bytes, Asset, Emoji, PartialEmoji, StickerItem, Sticker]]) –

    The role’s new icon image (if the guild has the ROLE_ICONS feature).

    Changed in version 2.5: Now accepts various resource types in addition to bytes.

  • emoji (Optional[str]) – The role’s new unicode emoji.

  • mentionable (bool) – Indicates if the role should be mentionable by others.

  • position (int) – The new role’s position. This must be below your top role’s position or it will fail.

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

Raises:
  • NotFound – The icon asset couldn’t be found.

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

  • HTTPException – Editing the role failed.

  • TypeError – The default role was asked to be moved or the icon asset is a lottie sticker (see Sticker.read())

  • ValueError – An invalid position was provided.

Returns:

The newly edited role.

Return type:

Role

await delete(*, reason=None)[source]

This function is a coroutine.

Deletes the role.

You must have the manage_roles permission to use this.

Parameters:

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

Raises:
RoleTags
class disnake.RoleTags[source]

Represents tags on a role.

A role tag is a piece of extra information attached to a managed role that gives it context for the reason the role is managed.

While this can be accessed, a useful interface is also provided in the Role and Guild classes as well.

New in version 1.6.

bot_id

The bot’s user ID that manages this role.

Type:

Optional[int]

integration_id

The integration ID that manages the role.

Type:

Optional[int]

is_bot_managed()[source]

Whether the role is associated with a bot.

Return type:

bool

is_premium_subscriber()[source]

Whether the role is the premium subscriber, AKA “boost”, role for the guild.

Return type:

bool

is_integration()[source]

Whether the role is managed by an integration.

Return type:

bool

PartialMessageable
Attributes
Methods
class disnake.PartialMessageable[source]

Represents a partial messageable to aid with working messageable channels when only a channel ID is present.

The only way to construct this class is through Client.get_partial_messageable().

Note that this class is trimmed down and has no rich attributes.

New in version 2.0.

x == y

Checks if two partial messageables are equal.

x != y

Checks if two partial messageables are not equal.

hash(x)

Returns the partial messageable’s hash.

id

The channel ID associated with this partial messageable.

Type:

int

type

The channel type associated with this partial messageable, if given.

Type:

Optional[ChannelType]

await fetch_message(id, /)[source]

This function is a coroutine.

Retrieves a single Message from the destination.

Parameters:

id (int) – The message ID to look for.

Raises:
  • NotFound – The specified message was not found.

  • Forbidden – You do not have the permissions required to get a message.

  • HTTPException – Retrieving the message failed.

Returns:

The message asked for.

Return type:

Message

history(*, limit=100, before=None, after=None, around=None, oldest_first=None)[source]

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

You must have Permissions.read_message_history permission to use this.

Examples

Usage

counter = 0
async for message in channel.history(limit=200):
    if message.author == client.user:
        counter += 1

Flattening into a list:

messages = await channel.history(limit=123).flatten()
# messages is now a list of Message...

All parameters are optional.

Parameters:
  • limit (Optional[int]) – The number of messages to retrieve. If None, retrieves every message in the channel. Note, however, that this would make it a slow operation.

  • before (Optional[Union[abc.Snowflake, datetime.datetime]]) – Retrieve messages before this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.

  • after (Optional[Union[abc.Snowflake, datetime.datetime]]) – Retrieve messages after this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.

  • around (Optional[Union[abc.Snowflake, datetime.datetime]]) – Retrieve messages around this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time. When using this argument, the maximum limit is 101. Note that if the limit is an even number then this will return at most limit + 1 messages.

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

Raises:
  • Forbidden – You do not have permissions to get channel message history.

  • HTTPException – The request to get message history failed.

Yields:

Message – The message with the message data parsed.

await pins()[source]

This function is a coroutine.

Retrieves all messages that are currently pinned in the channel.

Note

Due to a limitation with the Discord API, the Message objects returned by this method do not contain complete Message.reactions data.

Raises:

HTTPException – Retrieving the pinned messages failed.

Returns:

The messages that are currently pinned.

Return type:

List[Message]

await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, suppress_embeds=False, allowed_mentions=None, reference=None, mention_author=None, view=None, components=None)[source]

This function is a coroutine.

Sends a message to the destination with the content given.

The content must be a type that can convert to a string through str(content).

At least one of content, embed/embeds, file/files, stickers, components, or view must be provided.

To upload a single file, the file parameter should be used with a single File object. To upload multiple files, the files parameter should be used with a list of File objects. Specifying both parameters will lead to an exception.

To upload a single embed, the embed parameter should be used with a single Embed object. To upload multiple embeds, the embeds parameter should be used with a list of Embed objects. Specifying both parameters will lead to an exception.

Changed in version 2.6: Raises TypeError or ValueError instead of InvalidArgument.

Parameters:
  • content (Optional[str]) – The content of the message to send.

  • tts (bool) – Whether the message should be sent using text-to-speech.

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

  • embeds (List[Embed]) –

    A list of embeds to send with the content. Must be a maximum of 10. This cannot be mixed with the embed parameter.

    New in version 2.0.

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

  • files (List[File]) – A list of files to upload. Must be a maximum of 10. This cannot be mixed with the file parameter.

  • stickers (Sequence[Union[GuildSticker, StickerItem]]) –

    A list of stickers to upload. Must be a maximum of 3.

    New in version 2.0.

  • nonce (Union[str, int]) – The nonce to use for sending this message. If the message was successfully sent, then the message will have a nonce with this value.

  • delete_after (float) – If provided, the number of seconds to wait in the background before deleting the message we just sent. If the deletion fails, then it is silently ignored.

  • allowed_mentions (AllowedMentions) –

    Controls the mentions being processed in this message. If this is passed, then the object is merged with Client.allowed_mentions. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set in Client.allowed_mentions. If no object is passed at all then the defaults given by Client.allowed_mentions are used instead.

    New in version 1.4.

  • reference (Union[Message, MessageReference, PartialMessage]) –

    A reference to the Message to which you are replying, this can be created using Message.to_reference() or passed directly as a Message. You can control whether this mentions the author of the referenced message using the AllowedMentions.replied_user attribute of allowed_mentions or by setting mention_author.

    New in version 1.6.

  • mention_author (Optional[bool]) –

    If set, overrides the AllowedMentions.replied_user attribute of allowed_mentions.

    New in version 1.6.

  • view (ui.View) –

    A Discord UI View to add to the message. This cannot be mixed with components.

    New in version 2.0.

  • components (Union[disnake.ui.ActionRow, disnake.ui.WrappedComponent, List[Union[disnake.ui.ActionRow, disnake.ui.WrappedComponent, List[disnake.ui.WrappedComponent]]]]) –

    A list of components to include in the message. This cannot be mixed with view.

    New in version 2.4.

  • suppress_embeds (bool) –

    Whether to suppress embeds for the message. This hides all embeds from the UI if set to True.

    New in version 2.5.

Raises:
Returns:

The message that was sent.

Return type:

Message

await trigger_typing()[source]

This function is a coroutine.

Triggers a typing indicator to the destination.

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

typing()[source]

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

This is useful for denoting long computations in your bot.

Note

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

Example Usage:

async with channel.typing():
    # simulate something heavy
    await asyncio.sleep(10)

await channel.send('done!')
get_partial_message(message_id, /)[source]

Creates a PartialMessage from the given message ID.

This is useful if you want to work with a message and only have its ID without doing an unnecessary API call.

Parameters:

message_id (int) – The message ID to create a partial message for.

Returns:

The partial message object.

Return type:

PartialMessage

TextChannel
class disnake.TextChannel[source]

Represents a Discord guild text channel.

x == y

Checks if two channels are equal.

x != y

Checks if two channels are not equal.

hash(x)

Returns the channel’s hash.

str(x)

Returns the channel’s name.

name

The channel’s name.

Type:

str

guild

The guild the channel belongs to.

Type:

Guild

id

The channel’s ID.

Type:

int

category_id

The category channel ID this channel belongs to, if applicable.

Type:

Optional[int]

topic

The channel’s topic. None if it doesn’t exist.

Type:

Optional[str]

position

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

Type:

int

last_message_id

The last message ID of the message sent to this channel. It may not point to an existing or valid message.

Type:

Optional[int]

slowmode_delay

The number of seconds a member must wait between sending messages in this channel. A value of 0 denotes that it is disabled. Bots, and users with manage_channels or manage_messages permissions, bypass slowmode.

Type:

int

nsfw

Whether the channel is marked as “not safe for work”.

Note

To check if the channel or the guild of that channel are marked as NSFW, consider is_nsfw() instead.

Type:

bool

default_auto_archive_duration

The default auto archive duration in minutes for threads created in this channel.

New in version 2.0.

Type:

int

last_pin_timestamp

The time the most recent message was pinned, or None if no message is currently pinned.

New in version 2.5.

Type:

Optional[datetime.datetime]

async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)[source]

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

You must have Permissions.read_message_history permission to use this.

Examples

Usage

counter = 0
async for message in channel.history(limit=200):
    if message.author == client.user:
        counter += 1

Flattening into a list:

messages = await channel.history(limit=123).flatten()
# messages is now a list of Message...

All parameters are optional.

Parameters:
  • limit (Optional[int]) – The number of messages to retrieve. If None, retrieves every message in the channel. Note, however, that this would make it a slow operation.

  • before (Optional[Union[abc.Snowflake, datetime.datetime]]) – Retrieve messages before this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.

  • after (Optional[Union[abc.Snowflake, datetime.datetime]]) – Retrieve messages after this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.

  • around (Optional[Union[abc.Snowflake, datetime.datetime]]) – Retrieve messages around this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time. When using this argument, the maximum limit is 101. Note that if the limit is an even number then this will return at most limit + 1 messages.

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

Raises:
  • Forbidden – You do not have permissions to get channel message history.

  • HTTPException – The request to get message history failed.

Yields:

Message – The message with the message data parsed.

async with typing()[source]

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

This is useful for denoting long computations in your bot.

Note

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

Example Usage:

async with channel.typing():
    # simulate something heavy
    await asyncio.sleep(10)

await channel.send('done!')
property type[source]

The channel’s Discord type.

This always returns ChannelType.text or ChannelType.news.

Type:

ChannelType

permissions_for(obj, /, *, ignore_timeout=...)[source]

Handles permission resolution for the Member or Role.

This function takes into consideration the following cases:

  • Guild owner

  • Guild roles

  • Channel overrides

  • Member overrides

  • Timeouts

If a Role is passed, then it checks the permissions someone with that role would have, which is essentially:

  • The default role permissions

  • The permissions of the role used as a parameter

  • The default role permission overwrites

  • The permission overwrites of the role used as a parameter

Changed in version 2.0: The object passed in can now be a role object.

Parameters:
  • obj (Union[Member, Role]) – The object to resolve permissions for. This could be either a member or a role. If it’s a role then member overwrites are not computed.

  • ignore_timeout (bool) –

    Whether or not to ignore the user’s timeout. Defaults to False.

    New in version 2.4.

    Note

    This only applies to Member objects.

    Changed in version 2.6: The default was changed to False.

Raises:

TypeErrorignore_timeout is only supported for Member objects.

Returns:

The resolved permissions for the member or role.

Return type:

Permissions

property members[source]

Returns all members that can see this channel.

Type:

List[Member]

property threads[source]

Returns all the threads that you can see.

New in version 2.0.

Type:

List[Thread]

is_nsfw()[source]

Whether the channel is marked as NSFW.

Return type:

bool

is_news()[source]

Whether the channel is a news channel.

Return type:

bool

property last_message[source]

Gets the last message in this channel from the cache.

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

Reliable Fetching

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

Returns:

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

Return type:

Optional[Message]

await edit(*, name=..., topic=..., position=..., nsfw=..., sync_permissions=..., category=..., slowmode_delay=..., default_auto_archive_duration=..., type=..., overwrites=..., flags=..., reason=None, **kwargs)[source]

This function is a coroutine.

Edits the channel.

You must have manage_channels permission to do this.

Changed in version 1.3: The overwrites keyword-only parameter was added.

Changed in version 1.4: The type keyword-only parameter was added.

Changed in version 2.0: Edits are no longer in-place, the newly edited channel is returned instead.

Changed in version 2.6: Raises TypeError or ValueError instead of InvalidArgument.

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

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

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

  • nsfw (bool) – Whether to mark the channel as NSFW.

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

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

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

  • type (ChannelType) – The new type of this text channel. Currently, only conversion between ChannelType.text and ChannelType.news is supported. This is only available to guilds that contain NEWS in Guild.features.

  • overwrites (Mapping) – A Mapping of target (either a role or a member) to PermissionOverwrite to apply to the channel.

  • default_auto_archive_duration (Optional[Union[int, ThreadArchiveDuration]]) – The new default auto archive duration in minutes for threads created in this channel. Must be one of 60, 1440, 4320, or 10080.

  • flags (ChannelFlags) –

    The new flags to set for this channel. This will overwrite any existing flags set on this channel.

    New in version 2.6.

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

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

  • HTTPException – Editing the channel failed.

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

  • ValueError – The position is less than 0.

Returns:

The newly edited text channel. If the edit was only positional then None is returned instead.

Return type:

Optional[TextChannel]

await clone(*, name=None, reason=None)[source]

This function is a coroutine.

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

You must have Permissions.manage_channels permission to do this.

New in version 1.1.

Parameters:
  • name (Optional[str]) – The name of the new channel. If not provided, defaults to this channel name.

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

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

  • HTTPException – Creating the channel failed.

Returns:

The channel that was created.

Return type:

abc.GuildChannel

await delete_messages(messages)[source]

This function is a coroutine.

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

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

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

You must have manage_messages permission to do this.

Parameters:

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

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

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

  • NotFound – If single delete, then the message was already deleted.

  • HTTPException – Deleting the messages failed.

await purge(*, limit=100, check=..., before=None, after=None, around=None, oldest_first=False, bulk=True)[source]

This function is a coroutine.

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

You must have manage_messages permission to delete messages even if they are your own. read_message_history permission is also needed to retrieve message history.

Examples

Deleting bot’s messages

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

deleted = await channel.purge(limit=100, check=is_me)
await channel.send(f'Deleted {len(deleted)} message(s)')
Parameters:
Raises:
  • Forbidden – You do not have proper permissions to do the actions required.

  • HTTPException – Purging the messages failed.

Returns:

A list of messages that were deleted.

Return type:

List[Message]

await webhooks()[source]

This function is a coroutine.

Retrieves the list of webhooks this channel has.

You must have manage_webhooks permission to use this.

Raises:

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

Returns:

The list of webhooks this channel has.

Return type:

List[Webhook]

await create_webhook(*, name, avatar=None, reason=None)[source]

This function is a coroutine.

Creates a webhook for this channel.

You must have manage_webhooks permission to do this.

Changed in version 1.1: The reason keyword-only parameter was added.

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

  • avatar (Optional[Union[bytes, Asset, Emoji, PartialEmoji, StickerItem, Sticker]]) –

    The webhook’s default avatar. This operates similarly to edit().

    Changed in version 2.5: Now accepts various resource types in addition to bytes.

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

Raises:
Returns:

The newly created webhook.

Return type:

Webhook

await follow(*, destination, reason=None)[source]

This function is a coroutine.

Follows a channel using a webhook.

Only news channels can be followed.

Note

The webhook returned will not provide a token to do webhook actions, as Discord does not provide it.

New in version 1.3.

Changed in version 2.6: Raises TypeError instead of InvalidArgument.

Parameters:
  • destination (TextChannel) – The channel you would like to follow from.

  • reason (Optional[str]) –

    The reason for following the channel. Shows up on the destination guild’s audit log.

    New in version 1.4.

Raises:
  • HTTPException – Following the channel failed.

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

  • TypeError – The current or provided channel is not of the correct type.

Returns:

The newly created webhook.

Return type:

Webhook

get_partial_message(message_id, /)[source]

Creates a PartialMessage from the given message ID.

This is useful if you want to work with a message and only have its ID without doing an unnecessary API call.

New in version 1.6.

Parameters:

message_id (int) – The message ID to create a partial message for.

Returns:

The partial message object.

Return type:

PartialMessage

get_thread(thread_id, /)[source]

Returns a thread with the given ID.

New in version 2.0.

Parameters:

thread_id (int) – The ID to search for.

Returns:

The returned thread or None if not found.

Return type:

Optional[Thread]

await create_thread(*, name, message=None, auto_archive_duration=None, type=None, invitable=None, slowmode_delay=None, reason=None)[source]

This function is a coroutine.

Creates a thread in this text channel.

To create a public thread, you must have create_public_threads permission. For a private thread, create_private_threads permission is needed instead. Additionally, the guild must have PRIVATE_THREADS in Guild.features to create private threads.

New in version 2.0.

Changed in version 2.5:

  • Only one of message and type may be provided.

  • type is now required if message is not provided.

Parameters:
  • name (str) – The name of the thread.

  • message (abc.Snowflake) –

    A snowflake representing the message to create the thread with.

    Changed in version 2.5: Cannot be provided with type.

  • type (ChannelType) –

    The type of thread to create.

    Changed in version 2.5: Cannot be provided with message. Now required if message is not provided.

  • auto_archive_duration (Union[int, ThreadArchiveDuration]) – The duration in minutes before a thread is automatically archived for inactivity. If not provided, the channel’s default auto archive duration is used. Must be one of 60, 1440, 4320, or 10080.

  • invitable (bool) –

    Whether non-moderators can add other non-moderators to this thread. Only available for private threads. If a message is passed then this parameter is ignored, as a thread created with a message is always a public thread. Defaults to True.

    New in version 2.3.

  • slowmode_delay (Optional[int]) –

    Specifies the slowmode rate limit for users in this thread, in seconds. A value of 0 disables slowmode. The maximum value possible is 21600. If set to None or not provided, slowmode is inherited from the parent channel.

    New in version 2.3.

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

Raises:
Returns:

The newly created thread

Return type:

Thread

archived_threads(*, private=False, joined=False, limit=50, before=None)[source]

Returns an AsyncIterator that iterates over all archived threads in the channel.

You must have read_message_history permission to use this. If iterating over private threads then manage_threads permission is also required.

New in version 2.0.

Parameters:
  • limit (Optional[int]) – The number of threads to retrieve. If None, retrieves every archived thread in the channel. Note, however, that this would make it a slow operation.

  • before (Optional[Union[abc.Snowflake, datetime.datetime]]) – Retrieve archived channels before the given date or ID.

  • private (bool) – Whether to retrieve private archived threads.

  • joined (bool) – Whether to retrieve private archived threads that you’ve joined. You cannot set joined to True and private to False.

Raises:
  • Forbidden – You do not have permissions to get archived threads.

  • HTTPException – The request to get the archived threads failed.

Yields:

Thread – The archived threads.

property category[source]

The category this channel belongs to.

If there is no category then this is None.

Type:

Optional[CategoryChannel]

property changed_roles[source]

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

Type:

List[Role]

await create_invite(*, reason=None, max_age=0, max_uses=0, temporary=False, unique=True, target_type=None, target_user=None, target_application=None, guild_scheduled_event=None)[source]

This function is a coroutine.

Creates an instant invite from a text or voice channel.

You must have Permissions.create_instant_invite permission to do this.

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

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

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

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

  • target_type (Optional[InviteTarget]) –

    The type of target for the voice channel invite, if any.

    New in version 2.0.

  • target_user (Optional[User]) –

    The user whose stream to display for this invite, required if target_type is TargetType.stream. The user must be streaming in the channel.

    New in version 2.0.

  • target_application (Optional[PartyType]) –

    The ID of the embedded application for the invite, required if target_type is TargetType.embedded_application.

    New in version 2.0.

  • guild_scheduled_event (Optional[GuildScheduledEvent]) –

    The guild scheduled event to include with the invite.

    New in version 2.3.

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

Raises:
  • HTTPException – Invite creation failed.

  • NotFound – The channel that was passed is a category or an invalid channel.

Returns:

The newly created invite.

Return type:

Invite

property created_at[source]

Returns the channel’s creation time in UTC.

Type:

datetime.datetime

await delete(*, reason=None)[source]

This function is a coroutine.

Deletes the channel.

You must have Permissions.manage_channels permission to do this.

Parameters:

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

Raises:
  • Forbidden – You do not have proper permissions to delete the channel.

  • NotFound – The channel was not found or was already deleted.

  • HTTPException – Deleting the channel failed.

await fetch_message(id, /)[source]

This function is a coroutine.

Retrieves a single Message from the destination.

Parameters:

id (int) – The message ID to look for.

Raises:
  • NotFound – The specified message was not found.

  • Forbidden – You do not have the permissions required to get a message.

  • HTTPException – Retrieving the message failed.

Returns:

The message asked for.

Return type:

Message

property flags[source]

The channel flags for this channel.

New in version 2.6.

Type:

ChannelFlags

await invites()[source]

This function is a coroutine.

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

You must have Permissions.manage_channels permission to use this.

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

  • HTTPException – An error occurred while fetching the information.

Returns:

The list of invites that are currently active.

Return type:

List[Invite]

property jump_url[source]

A URL that can be used to jump to this channel.

New in version 2.4.

Note

This exists for all guild channels but may not be usable by the client for all guild channel types.

property mention[source]

The string that allows you to mention the channel.

Type:

str

await move(**kwargs)[source]

This function is a coroutine.

A rich interface to help move a channel relative to other channels.

If exact position movement is required, edit should be used instead.

You must have Permissions.manage_channels permission to do this.

Note

Voice channels will always be sorted below text channels. This is a Discord limitation.

New in version 1.7.

Changed in version 2.6: Raises TypeError or ValueError instead of InvalidArgument.

Parameters:
  • beginning (bool) – Whether to move the channel to the beginning of the channel list (or category if given). This is mutually exclusive with end, before, and after.

  • end (bool) – Whether to move the channel to the end of the channel list (or category if given). This is mutually exclusive with beginning, before, and after.

  • before (abc.Snowflake) – The channel that should be before our current channel. This is mutually exclusive with beginning, end, and after.

  • after (abc.Snowflake) – The channel that should be after our current channel. This is mutually exclusive with beginning, end, and before.

  • offset (int) – The number of channels to offset the move by. For example, an offset of 2 with beginning=True would move it 2 after the beginning. A positive number moves it below while a negative number moves it above. Note that this number is relative and computed after the beginning, end, before, and after parameters.

  • category (Optional[abc.Snowflake]) – The category to move this channel under. If None is given then it moves it out of the category. This parameter is ignored if moving a category channel.

  • sync_permissions (bool) – Whether to sync the permissions with the category (if given).

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

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

  • HTTPException – Moving the channel failed.

  • TypeError – A bad mix of arguments were passed.

  • ValueError – An invalid position was given.

property overwrites[source]

Returns all of the channel’s overwrites.

This is returned as a dictionary where the key contains the target which can be either a Role or a Member and the value is the overwrite as a PermissionOverwrite.

Returns:

The channel’s permission overwrites.

Return type:

Dict[Union[Role, Member], PermissionOverwrite]

overwrites_for(obj)[source]

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

Parameters:

obj (Union[Role, abc.User]) – The role or user denoting whose overwrite to get.

Returns:

The permission overwrites for this object.

Return type:

PermissionOverwrite

property permissions_synced[source]

Whether or not the permissions for this channel are synced with the category it belongs to.

If there is no category then this is False.

New in version 1.3.

Type:

bool

await pins()[source]

This function is a coroutine.

Retrieves all messages that are currently pinned in the channel.

Note

Due to a limitation with the Discord API, the Message objects returned by this method do not contain complete Message.reactions data.

Raises:

HTTPException – Retrieving the pinned messages failed.

Returns:

The messages that are currently pinned.

Return type:

List[Message]

await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, suppress_embeds=False, allowed_mentions=None, reference=None, mention_author=None, view=None, components=None)[source]

This function is a coroutine.

Sends a message to the destination with the content given.

The content must be a type that can convert to a string through str(content).

At least one of content, embed/embeds, file/files, stickers, components, or view must be provided.

To upload a single file, the file parameter should be used with a single File object. To upload multiple files, the files parameter should be used with a list of File objects. Specifying both parameters will lead to an exception.

To upload a single embed, the embed parameter should be used with a single Embed object. To upload multiple embeds, the embeds parameter should be used with a list of Embed objects. Specifying both parameters will lead to an exception.

Changed in version 2.6: Raises TypeError or ValueError instead of InvalidArgument.

Parameters:
  • content (Optional[str]) – The content of the message to send.

  • tts (bool) – Whether the message should be sent using text-to-speech.

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

  • embeds (List[Embed]) –

    A list of embeds to send with the content. Must be a maximum of 10. This cannot be mixed with the embed parameter.

    New in version 2.0.

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

  • files (List[File]) – A list of files to upload. Must be a maximum of 10. This cannot be mixed with the file parameter.

  • stickers (Sequence[Union[GuildSticker, StickerItem]]) –

    A list of stickers to upload. Must be a maximum of 3.

    New in version 2.0.

  • nonce (Union[str, int]) – The nonce to use for sending this message. If the message was successfully sent, then the message will have a nonce with this value.

  • delete_after (float) – If provided, the number of seconds to wait in the background before deleting the message we just sent. If the deletion fails, then it is silently ignored.

  • allowed_mentions (AllowedMentions) –

    Controls the mentions being processed in this message. If this is passed, then the object is merged with Client.allowed_mentions. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set in Client.allowed_mentions. If no object is passed at all then the defaults given by Client.allowed_mentions are used instead.

    New in version 1.4.

  • reference (Union[Message, MessageReference, PartialMessage]) –

    A reference to the Message to which you are replying, this can be created using Message.to_reference() or passed directly as a Message. You can control whether this mentions the author of the referenced message using the AllowedMentions.replied_user attribute of allowed_mentions or by setting mention_author.

    New in version 1.6.

  • mention_author (Optional[bool]) –

    If set, overrides the AllowedMentions.replied_user attribute of allowed_mentions.

    New in version 1.6.

  • view (ui.View) –

    A Discord UI View to add to the message. This cannot be mixed with components.

    New in version 2.0.

  • components (Union[disnake.ui.ActionRow, disnake.ui.WrappedComponent, List[Union[disnake.ui.ActionRow, disnake.ui.WrappedComponent, List[disnake.ui.WrappedComponent]]]]) –

    A list of components to include in the message. This cannot be mixed with view.

    New in version 2.4.

  • suppress_embeds (bool) –

    Whether to suppress embeds for the message. This hides all embeds from the UI if set to True.

    New in version 2.5.

Raises:
Returns:

The message that was sent.

Return type:

Message

await set_permissions(target, *, overwrite=..., reason=None, **permissions)[source]

This function is a coroutine.

Sets the channel specific permission overwrites for a target in the channel.

The target parameter should either be a Member or a Role that belongs to guild.

The overwrite parameter, if given, must either be None or PermissionOverwrite. For convenience, you can pass in keyword arguments denoting Permissions attributes. If this is done, then you cannot mix the keyword arguments with the overwrite parameter.

If the overwrite parameter is None, then the permission overwrites are deleted.

You must have Permissions.manage_roles permission to do this.

Note

This method replaces the old overwrites with the ones given.

Changed in version 2.6: Raises TypeError instead of InvalidArgument.

Examples

Setting allow and deny:

await message.channel.set_permissions(message.author, view_channel=True,
                                                      send_messages=False)

Deleting overwrites

await channel.set_permissions(member, overwrite=None)

Using PermissionOverwrite

overwrite = disnake.PermissionOverwrite()
overwrite.send_messages = False
overwrite.view_channel = True
await channel.set_permissions(member, overwrite=overwrite)
Parameters:
  • target (Union[Member, Role]) – The member or role to overwrite permissions for.

  • overwrite (Optional[PermissionOverwrite]) – The permissions to allow and deny to the target, or None to delete the overwrite.

  • **permissions – A keyword argument list of permissions to set for ease of use. Cannot be mixed with overwrite.

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

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

  • HTTPException – Editing channel specific permissions failed.

  • NotFound – The role or member being edited is not part of the guild.

  • TypeErroroverwrite is invalid, the target type was not Role or Member, both keyword arguments and overwrite were provided, or invalid permissions were provided as keyword arguments.

await trigger_typing()[source]

This function is a coroutine.

Triggers a typing indicator to the destination.

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

Thread
class disnake.Thread[source]

Represents a Discord thread.

x == y

Checks if two threads are equal.

x != y

Checks if two threads are not equal.

hash(x)

Returns the thread’s hash.

str(x)

Returns the thread’s name.

New in version 2.0.

name

The thread name.

Type:

str

guild

The guild the thread belongs to.

Type:

Guild

id

The thread ID.

Type:

int

parent_id

The parent TextChannel or ForumChannel ID this thread belongs to.

Type:

int

owner_id

The user’s ID that created this thread.

Type:

Optional[int]

last_message_id

The last message ID of the message sent to this thread. It may not point to an existing or valid message.

Type:

Optional[int]

slowmode_delay

The number of seconds a member must wait between sending messages in this thread. A value of 0 denotes that it is disabled. Bots, and users with manage_channels or manage_messages, bypass slowmode.

Type:

int

message_count

An approximate number of messages in this thread.

Note

If the thread was created before July 1, 2022, this could be inaccurate.

Type:

Optional[int]

member_count

An approximate number of members in this thread. This caps at 50.

Type:

Optional[int]

total_message_sent

The total number of messages sent in the thread, including deleted messages.

New in version 2.6.

Note

If the thread was created before July 1, 2022, this could be inaccurate.

Type:

Optional[int]

me

A thread member representing yourself, if you’ve joined the thread. This could not be available.

Type:

Optional[ThreadMember]

archived

Whether the thread is archived.

Type:

bool

locked

Whether the thread is locked.

Type:

bool

invitable

Whether non-moderators can add other non-moderators to this thread. This is always True for public threads.

Type:

bool

auto_archive_duration

The duration in minutes until the thread is automatically archived due to inactivity. Usually a value of 60, 1440, 4320 and 10080.

Type:

int

archive_timestamp

An aware timestamp of when the thread’s archived status was last updated in UTC.

Type:

datetime.datetime

create_timestamp

An aware timestamp of when the thread was created in UTC. This is only available for threads created after 2022-01-09.

New in version 2.4.

Type:

Optional[datetime.datetime]

last_pin_timestamp

The time the most recent message was pinned, or None if no message is currently pinned.

New in version 2.5.

Type:

Optional[datetime.datetime]

async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)[source]

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

You must have Permissions.read_message_history permission to use this.

Examples

Usage

counter = 0
async for message in channel.history(limit=200):
    if message.author == client.user:
        counter += 1

Flattening into a list:

messages = await channel.history(limit=123).flatten()
# messages is now a list of Message...

All parameters are optional.

Parameters:
  • limit (Optional[int]) – The number of messages to retrieve. If None, retrieves every message in the channel. Note, however, that this would make it a slow operation.

  • before (Optional[Union[abc.Snowflake, datetime.datetime]]) – Retrieve messages before this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.

  • after (Optional[Union[abc.Snowflake, datetime.datetime]]) – Retrieve messages after this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.

  • around (Optional[Union[abc.Snowflake, datetime.datetime]]) – Retrieve messages around this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time. When using this argument, the maximum limit is 101. Note that if the limit is an even number then this will return at most limit + 1 messages.

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

Raises:
  • Forbidden – You do not have permissions to get channel message history.

  • HTTPException – The request to get message history failed.

Yields:

Message – The message with the message data parsed.

async with typing()[source]

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

This is useful for denoting long computations in your bot.

Note

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

Example Usage:

async with channel.typing():
    # simulate something heavy
    await asyncio.sleep(10)

await channel.send('done!')
property type[source]

The channel’s Discord type.

This always returns ChannelType.public_thread, ChannelType.private_thread, or ChannelType.news_thread.

Type:

ChannelType

property parent[source]

The parent channel this thread belongs to.

Type:

Optional[Union[TextChannel, ForumChannel]]

property owner[source]

The member this thread belongs to.

Type:

Optional[Member]

property mention[source]

The string that allows you to mention the thread.

Type:

str

property members[source]

A list of thread members in this thread.

This requires Intents.members to be properly filled. Most of the time however, this data is not provided by the gateway and a call to fetch_members() is needed.

Type:

List[ThreadMember]

property last_message[source]

Gets the last message in this channel from the cache.

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

Reliable Fetching

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

Returns:

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

Return type:

Optional[Message]

property category[source]

The category channel the parent channel belongs to, if applicable.

Raises:

ClientException – The parent channel was not cached and returned None.

Returns:

The parent channel’s category.

Return type:

Optional[CategoryChannel]

property category_id[source]

The category channel ID the parent channel belongs to, if applicable.

Raises:

ClientException – The parent channel was not cached and returned None.

Returns:

The parent channel’s category ID.

Return type:

Optional[int]

property created_at[source]

Returns the thread’s creation time in UTC.

Changed in version 2.4: If create_timestamp is provided by discord, that will be used instead of the time in the ID.

Type:

datetime.datetime

property flags[source]

The channel flags for this thread.

New in version 2.5.

Type:

ChannelFlags

property jump_url[source]

A URL that can be used to jump to this thread.

New in version 2.4.

is_private()[source]

Whether the thread is a private thread.

A private thread is only viewable by those that have been explicitly invited or have manage_threads.

Return type:

bool

is_news()[source]

Whether the thread is a news thread.

A news thread is a thread that has a parent that is a news channel, i.e. TextChannel.is_news() is True.

Return type:

bool

is_nsfw()[source]

Whether the thread is NSFW or not.

An NSFW thread is a thread that has a parent that is an NSFW channel, i.e. TextChannel.is_nsfw() is True.

Return type:

bool

is_pinned()[source]

Whether the thread is pinned in a ForumChannel

Pinned threads are not affected by the auto archive duration.

This is a shortcut to self.flags.pinned.

New in version 2.5.

Return type:

bool

property applied_tags[source]

The tags currently applied to this thread. Only applicable to threads in ForumChannels.

New in version 2.6.

Type:

List[ForumTag]

permissions_for(obj, /, *, ignore_timeout=...)[source]

Handles permission resolution for the Member or Role.

Since threads do not have their own permissions, they inherit them from the parent channel. This is a convenience method for calling permissions_for() on the parent channel.

Parameters:
  • obj (Union[Member, Role]) – The object to resolve permissions for. This could be either a member or a role. If it’s a role then member overwrites are not computed.

  • ignore_timeout (bool) –

    Whether or not to ignore the user’s timeout. Defaults to False.

    New in version 2.4.

    Note

    This only applies to Member objects.

    Changed in version 2.6: The default was changed to False.

Raises:

ClientException – The parent channel was not cached and returned None

Returns:

The resolved permissions for the member or role.

Return type:

Permissions

await delete_messages(messages)[source]

This function is a coroutine.

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

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

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

You must have the manage_messages permission to use this.

Usable only by bot accounts.

Parameters:

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

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

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

  • NotFound – If single delete, then the message was already deleted.

  • HTTPException – Deleting the messages failed.

await purge(*, limit=100, check=..., before=None, after=None, around=None, oldest_first=False, bulk=True)[source]

This function is a coroutine.

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

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

Examples

Deleting bot’s messages

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

deleted = await thread.purge(limit=100, check=is_me)
await thread.send(f'Deleted {len(deleted)} message(s)')
Parameters:
Raises:
  • Forbidden – You do not have proper permissions to do the actions required.

  • HTTPException – Purging the messages failed.

Returns:

The list of messages that were deleted.

Return type:

List[Message]

await edit(*, name=..., archived=..., locked=..., invitable=..., slowmode_delay=..., auto_archive_duration=..., pinned=..., flags=..., applied_tags=..., reason=None)[source]

This function is a coroutine.

Edits the thread.

Editing the thread requires Permissions.manage_threads. The thread creator can also edit name, archived, auto_archive_duration and applied_tags. Note that if the thread is locked then only those with Permissions.manage_threads can unarchive a thread.

The thread must be unarchived to be edited.

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

  • archived (bool) – Whether to archive the thread or not.

  • locked (bool) – Whether to lock the thread or not.

  • invitable (bool) – Whether non-moderators can add other non-moderators to this thread. Only available for private threads.

  • auto_archive_duration (Union[int, ThreadArchiveDuration]) – The new duration in minutes before a thread is automatically archived for inactivity. Must be one of 60, 1440, 4320, or 10080.

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

  • pinned (bool) –

    Whether to pin the thread or not. This is only available for threads created in a ForumChannel.

    New in version 2.5.

  • flags (ChannelFlags) –

    The new channel flags to set for this thread. This will overwrite any existing flags set on this channel. If parameter pinned is provided, that will override the setting of ChannelFlags.pinned.

    New in version 2.6.

  • applied_tags (Sequence[abc.Snowflake]) –

    The new tags of the thread. Maximum of 5. Can also be used to reorder existing tags.

    This is only available for threads in a ForumChannel.

    If moderated tags are edited, Permissions.manage_threads permissions are required.

    See also add_tags() and remove_tags().

    New in version 2.6.

  • reason (Optional[str]) –

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

    New in version 2.5.

Raises:
Returns:

The newly edited thread.

Return type:

Thread

await join()[source]

This function is a coroutine.

Joins this thread.

You must have send_messages_in_threads to join a thread. If the thread is private, manage_threads is also needed.

Raises:
await leave()[source]

This function is a coroutine.

Leaves this thread.

Raises:

HTTPException – Leaving the thread failed.

await add_user(user)[source]

This function is a coroutine.

Adds a user to this thread.

You must have send_messages permission to add a user to a public thread. If the thread is private then send_messages and either create_private_threads or manage_messages permissions is required to add a user to the thread.

Parameters:

user (abc.Snowflake) – The user to add to the thread.

Raises:
  • Forbidden – You do not have permissions to add the user to the thread.

  • HTTPException – Adding the user to the thread failed.

await remove_user(user)[source]

This function is a coroutine.

Removes a user from this thread.

You must have manage_threads or be the creator of the thread to remove a user.

Parameters:

user (abc.Snowflake) – The user to add to the thread.

Raises:
  • Forbidden – You do not have permissions to remove the user from the thread.

  • HTTPException – Removing the user from the thread failed.

await fetch_member(member_id, /)[source]

This function is a coroutine.

Retrieves a single ThreadMember from this thread.

Parameters:

member_id (int) – The ID of the member to fetch.

Raises:
Returns:

The thread member asked for.

Return type:

ThreadMember

await fetch_members()[source]

This function is a coroutine.

Retrieves all ThreadMember that are in this thread.

This requires Intents.members to get information about members other than yourself.

Raises:

HTTPException – Retrieving the members failed.

Returns:

All thread members in the thread.

Return type:

List[ThreadMember]

await delete(*, reason=None)[source]

This function is a coroutine.

Deletes this thread.

You must have manage_threads to delete threads. Alternatively, you may delete a thread if it’s in a ForumChannel, you are the thread creator, and there are no messages other than the initial message.

Parameters:

reason (Optional[str]) –

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

New in version 2.5.

Raises:
  • Forbidden – You do not have permissions to delete this thread.

  • HTTPException – Deleting the thread failed.

await add_tags(*tags, reason=None)[source]

This function is a coroutine.

Adds the given tags to this thread, up to 5 in total.

The thread must be in a ForumChannel.

Adding tags requires you to have Permissions.manage_threads permissions, or be the owner of the thread. However, adding moderated tags always requires Permissions.manage_threads permissions.

New in version 2.6.

Parameters:
  • *tags (abc.Snowflake) – An argument list of abc.Snowflake representing the ForumTags to add to the thread.

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

Raises:
await remove_tags(*tags, reason=None)[source]

This function is a coroutine.

Removes the given tags from this thread.

The thread must be in a ForumChannel.

Removing tags requires you to have Permissions.manage_threads permissions, or be the owner of the thread. However, removing moderated tags always requires Permissions.manage_threads permissions.

New in version 2.6.

Parameters:
  • *tags (abc.Snowflake) – An argument list of abc.Snowflake representing the ForumTags to remove from the thread.

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

Raises:
get_partial_message(message_id, /)[source]

Creates a PartialMessage from the message ID.

This is useful if you want to work with a message and only have its ID without doing an unnecessary API call.

New in version 2.0.

Parameters:

message_id (int) – The message ID to create a partial message for.

Returns:

The partial message.

Return type:

PartialMessage

await fetch_message(id, /)[source]

This function is a coroutine.

Retrieves a single Message from the destination.

Parameters:

id (int) – The message ID to look for.

Raises:
  • NotFound – The specified message was not found.

  • Forbidden – You do not have the permissions required to get a message.

  • HTTPException – Retrieving the message failed.

Returns:

The message asked for.

Return type:

Message

await pins()[source]

This function is a coroutine.

Retrieves all messages that are currently pinned in the channel.

Note

Due to a limitation with the Discord API, the Message objects returned by this method do not contain complete Message.reactions data.

Raises:

HTTPException – Retrieving the pinned messages failed.

Returns:

The messages that are currently pinned.

Return type:

List[Message]

await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, suppress_embeds=False, allowed_mentions=None, reference=None, mention_author=None, view=None, components=None)[source]

This function is a coroutine.

Sends a message to the destination with the content given.

The content must be a type that can convert to a string through str(content).

At least one of content, embed/embeds, file/files, stickers, components, or view must be provided.

To upload a single file, the file parameter should be used with a single File object. To upload multiple files, the files parameter should be used with a list of File objects. Specifying both parameters will lead to an exception.

To upload a single embed, the embed parameter should be used with a single Embed object. To upload multiple embeds, the embeds parameter should be used with a list of Embed objects. Specifying both parameters will lead to an exception.

Changed in version 2.6: Raises TypeError or ValueError instead of InvalidArgument.

Parameters:
  • content (Optional[str]) – The content of the message to send.

  • tts (bool) – Whether the message should be sent using text-to-speech.

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

  • embeds (List[Embed]) –

    A list of embeds to send with the content. Must be a maximum of 10. This cannot be mixed with the embed parameter.

    New in version 2.0.

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

  • files (List[File]) – A list of files to upload. Must be a maximum of 10. This cannot be mixed with the file parameter.

  • stickers (Sequence[Union[GuildSticker, StickerItem]]) –

    A list of stickers to upload. Must be a maximum of 3.

    New in version 2.0.

  • nonce (Union[str, int]) – The nonce to use for sending this message. If the message was successfully sent, then the message will have a nonce with this value.

  • delete_after (float) – If provided, the number of seconds to wait in the background before deleting the message we just sent. If the deletion fails, then it is silently ignored.

  • allowed_mentions (AllowedMentions) –

    Controls the mentions being processed in this message. If this is passed, then the object is merged with Client.allowed_mentions. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set in Client.allowed_mentions. If no object is passed at all then the defaults given by Client.allowed_mentions are used instead.

    New in version 1.4.

  • reference (Union[Message, MessageReference, PartialMessage]) –

    A reference to the Message to which you are replying, this can be created using Message.to_reference() or passed directly as a Message. You can control whether this mentions the author of the referenced message using the AllowedMentions.replied_user attribute of allowed_mentions or by setting mention_author.

    New in version 1.6.

  • mention_author (Optional[bool]) –

    If set, overrides the AllowedMentions.replied_user attribute of allowed_mentions.

    New in version 1.6.

  • view (ui.View) –

    A Discord UI View to add to the message. This cannot be mixed with components.

    New in version 2.0.

  • components (Union[disnake.ui.ActionRow, disnake.ui.WrappedComponent, List[Union[disnake.ui.ActionRow, disnake.ui.WrappedComponent, List[disnake.ui.WrappedComponent]]]]) –

    A list of components to include in the message. This cannot be mixed with view.

    New in version 2.4.

  • suppress_embeds (bool) –

    Whether to suppress embeds for the message. This hides all embeds from the UI if set to True.

    New in version 2.5.

Raises:
Returns:

The message that was sent.

Return type:

Message

await trigger_typing()[source]

This function is a coroutine.

Triggers a typing indicator to the destination.

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

ThreadMember
class disnake.ThreadMember[source]

Represents a Discord thread member.

x == y

Checks if two thread members are equal.

x != y

Checks if two thread members are not equal.

hash(x)

Returns the thread member’s hash.

str(x)

Returns the thread member’s name.

New in version 2.0.

id

The thread member’s ID.

Type:

int

thread_id

The thread’s ID.

Type:

int

joined_at

The time the member joined the thread in UTC.

Type:

datetime.datetime

property thread[source]

The thread this member belongs to.

Type:

Thread

ForumTag
Attributes
Methods
class disnake.ForumTag[source]

Represents a tag for threads in forum channels.

x == y

Checks if two tags are equal.

x != y

Checks if two tags are not equal.

hash(x)

Returns the tag’s hash.

str(x)

Returns the tag’s name.

New in version 2.6.

Examples

Creating a new tag:

tags = forum.available_tags
tags.append(ForumTag(name="cool new tag", moderated=True))
await forum.edit(available_tags=tags)

Editing an existing tag:

tags = []
for tag in forum.available_tags:
    if tag.id == 1234:
        tag = tag.with_changes(name="whoa new name")
    tags.append(tag)
await forum.edit(available_tags=tags)
id

The tag’s ID. Note that if this tag was manually constructed, this will be 0.

Type:

int

name

The tag’s name.

Type:

str

moderated

Whether only moderators can add this tag to threads or remove it. Defaults to False.

Type:

bool

emoji

The emoji associated with this tag, if any. Due to a Discord limitation, this will have an empty name if it is a custom PartialEmoji.

Type:

Optional[Union[Emoji, PartialEmoji]]

with_changes(*, name=..., emoji=..., moderated=...)[source]

Returns a new instance with the given changes applied, for easy use with ForumChannel.edit(). All other fields will be kept intact.

Returns:

The new tag instance.

Return type:

ForumTag

VoiceChannel
class disnake.VoiceChannel[source]

Represents a Discord guild voice channel.

x == y

Checks if two channels are equal.

x != y

Checks if two channels are not equal.

hash(x)

Returns the channel’s hash.

str(x)

Returns the channel’s name.

name

The channel’s name.

Type:

str

guild

The guild the channel belongs to.

Type:

Guild

id

The channel’s ID.

Type:

int

category_id

The category channel ID this channel belongs to, if applicable.

Type:

Optional[int]

position

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

Type:

int

bitrate

The channel’s preferred audio bitrate in bits per second.

Type:

int

user_limit

The channel’s limit for number of members that can be in a voice channel.

Type:

int

rtc_region

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

New in version 1.7.

Changed in version 2.5: No longer a VoiceRegion instance.

Type:

Optional[str]

video_quality_mode

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

Type:

VideoQualityMode

nsfw

Whether the channel is marked as “not safe for work”.

Note

To check if the channel or the guild of that channel are marked as NSFW, consider is_nsfw() instead.

New in version 2.3.

Type:

bool

slowmode_delay

The number of seconds a member must wait between sending messages in this channel. A value of 0 denotes that it is disabled. Bots, and users with manage_channels or manage_messages, bypass slowmode.

New in version 2.3.

Type:

int

last_message_id

The last message ID of the message sent to this channel. It may not point to an existing or valid message.

New in version 2.3.

Type:

Optional[int]

property type[source]

The channel’s Discord type.

This always returns ChannelType.voice.

Type:

ChannelType

await clone(*, name=None, reason=None)[source]

This function is a coroutine.

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

You must have Permissions.manage_channels permission to do this.

New in version 1.1.

Parameters:
  • name (Optional[str]) – The name of the new channel. If not provided, defaults to this channel name.

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

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

  • HTTPException – Creating the channel failed.

Returns:

The channel that was created.

Return type:

abc.GuildChannel

is_nsfw()[source]

Whether the channel is marked as NSFW.

New in version 2.3.

Return type:

bool

property last_message[source]

Gets the last message in this channel from the cache.

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

Reliable Fetching

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

New in version 2.3.

Returns:

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

Return type:

Optional[Message]

get_partial_message(message_id, /)[source]

Creates a PartialMessage from the given message ID.

This is useful if you want to work with a message and only have its ID without doing an unnecessary API call.

New in version 2.3.

Parameters:

message_id (int) – The message ID to create a partial message for.

Returns:

The partial message object.

Return type:

PartialMessage

permissions_for(obj, /, *, ignore_timeout=...)[source]

Handles permission resolution for the Member or Role.

This function takes into consideration the following cases:

  • Guild owner

  • Guild roles

  • Channel overrides

  • Member overrides

  • Timeouts

If a Role is passed, then it checks the permissions someone with that role would have, which is essentially:

  • The default role permissions

  • The permissions of the role used as a parameter

  • The default role permission overwrites

  • The permission overwrites of the role used as a parameter

Changed in version 2.0: The object passed in can now be a role object.

Parameters:
  • obj (Union[Member, Role]) – The object to resolve permissions for. This could be either a member or a role. If it’s a role then member overwrites are not computed.

  • ignore_timeout (bool) –

    Whether or not to ignore the user’s timeout. Defaults to False.

    New in version 2.4.

    Note

    This only applies to Member objects.

    Changed in version 2.6: The default was changed to False.

Raises:

TypeErrorignore_timeout is only supported for Member objects.

Returns:

The resolved permissions for the member or role.

Return type:

Permissions

await edit(*, name=..., bitrate=..., user_limit=..., position=..., sync_permissions=..., category=..., overwrites=..., rtc_region=..., video_quality_mode=..., nsfw=..., slowmode_delay=..., flags=..., reason=None, **kwargs)[source]

This function is a coroutine.

Edits the channel.

You must have manage_channels permission to do this.

Changed in version 1.3: The overwrites keyword-only parameter was added.

Changed in version 2.0: Edits are no longer in-place, the newly edited channel is returned instead.

Changed in version 2.6: Raises TypeError or ValueError instead of InvalidArgument.

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

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

  • user_limit (int) – The new channel’s user limit.

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

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

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

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

  • overwrites (Mapping) – A Mapping of target (either a role or a member) to PermissionOverwrite to apply to the channel.

  • rtc_region (Optional[Union[str, VoiceRegion]]) –

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

    New in version 1.7.

  • video_quality_mode (VideoQualityMode) –

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

    New in version 2.0.

  • nsfw (bool) –

    Whether to mark the channel as NSFW.

    New in version 2.3.

  • slowmode_delay (Optional[int]) –

    Specifies the slowmode rate limit for users in this channel, in seconds. A value of 0 disables slowmode. The maximum value possible is 21600.

    New in version 2.3.

  • flags (ChannelFlags) –

    The new flags to set for this channel. This will overwrite any existing flags set on this channel.

    New in version 2.6.

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

  • HTTPException – Editing the channel failed.

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

  • ValueError – The position is less than 0.

Returns:

The newly edited voice channel. If the edit was only positional then None is returned instead.

Return type:

Optional[VoiceChannel]

await delete_messages(messages)[source]

This function is a coroutine.

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

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

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

You must have manage_messages permission to do this.

New in version 2.5.

Parameters:

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

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

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

  • NotFound – If single delete, then the message was already deleted.

  • HTTPException – Deleting the messages failed.

await purge(*, limit=100, check=..., before=None, after=None, around=None, oldest_first=False, bulk=True)[source]

This function is a coroutine.

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

You must have manage_messages permission to delete messages even if they are your own. read_message_history permission is also needed to retrieve message history.

New in version 2.5.

Note

See TextChannel.purge() for examples.

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

  • HTTPException – Purging the messages failed.

Returns:

A list of messages that were deleted.

Return type:

List[Message]

await webhooks()[source]

This function is a coroutine.

Retrieves the list of webhooks this channel has.

You must have manage_webhooks permission to use this.

New in version 2.5.

Raises:

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

Returns:

The list of webhooks this channel has.

Return type:

List[Webhook]

await create_webhook(*, name, avatar=None, reason=None)[source]

This function is a coroutine.

Creates a webhook for this channel.

You must have manage_webhooks permission to do this.

New in version 2.5.

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

  • avatar (Optional[bytes]) – The webhook’s default avatar. This operates similarly to edit().

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

Raises:
Returns:

The newly created webhook.

Return type:

Webhook

property category[source]

The category this channel belongs to.

If there is no category then this is None.

Type:

Optional[CategoryChannel]

property changed_roles[source]

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

Type:

List[Role]

await connect(*, timeout=60.0, reconnect=True, cls=<class 'disnake.voice_client.VoiceClient'>)[source]

This function is a coroutine.

Connects to voice and creates a VoiceClient to establish your connection to the voice server.

This requires Intents.voice_states.

Parameters:
  • timeout (float) – The timeout in seconds to wait for the voice endpoint.

  • reconnect (bool) – Whether the bot should automatically attempt a reconnect if a part of the handshake fails or the gateway goes down.

  • cls (Type[VoiceProtocol]) – A type that subclasses VoiceProtocol to connect with. Defaults to VoiceClient.

Raises:
Returns:

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

Return type:

VoiceProtocol

await create_invite(*, reason=None, max_age=0, max_uses=0, temporary=False, unique=True, target_type=None, target_user=None, target_application=None, guild_scheduled_event=None)[source]

This function is a coroutine.

Creates an instant invite from a text or voice channel.

You must have Permissions.create_instant_invite permission to do this.

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

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

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

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

  • target_type (Optional[InviteTarget]) –

    The type of target for the voice channel invite, if any.

    New in version 2.0.

  • target_user (Optional[User]) –

    The user whose stream to display for this invite, required if target_type is TargetType.stream. The user must be streaming in the channel.

    New in version 2.0.

  • target_application (Optional[PartyType]) –

    The ID of the embedded application for the invite, required if target_type is TargetType.embedded_application.

    New in version 2.0.

  • guild_scheduled_event (Optional[GuildScheduledEvent]) –

    The guild scheduled event to include with the invite.

    New in version 2.3.

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

Raises:
  • HTTPException – Invite creation failed.

  • NotFound – The channel that was passed is a category or an invalid channel.

Returns:

The newly created invite.

Return type:

Invite

property created_at[source]

Returns the channel’s creation time in UTC.

Type:

datetime.datetime

await delete(*, reason=None)[source]

This function is a coroutine.

Deletes the channel.

You must have Permissions.manage_channels permission to do this.

Parameters:

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

Raises:
  • Forbidden – You do not have proper permissions to delete the channel.

  • NotFound – The channel was not found or was already deleted.

  • HTTPException – Deleting the channel failed.

await fetch_message(id, /)[source]

This function is a coroutine.

Retrieves a single Message from the destination.

Parameters:

id (int) – The message ID to look for.

Raises:
  • NotFound – The specified message was not found.

  • Forbidden – You do not have the permissions required to get a message.

  • HTTPException – Retrieving the message failed.

Returns:

The message asked for.

Return type:

Message

property flags[source]

The channel flags for this channel.

New in version 2.6.

Type:

ChannelFlags

history(*, limit=100, before=None, after=None, around=None, oldest_first=None)[source]

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

You must have Permissions.read_message_history permission to use this.

Examples

Usage

counter = 0
async for message in channel.history(limit=200):
    if message.author == client.user:
        counter += 1

Flattening into a list:

messages = await channel.history(limit=123).flatten()
# messages is now a list of Message...

All parameters are optional.

Parameters:
  • limit (Optional[int]) – The number of messages to retrieve. If None, retrieves every message in the channel. Note, however, that this would make it a slow operation.

  • before (Optional[Union[abc.Snowflake, datetime.datetime]]) – Retrieve messages before this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.

  • after (Optional[Union[abc.Snowflake, datetime.datetime]]) – Retrieve messages after this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.

  • around (Optional[Union[abc.Snowflake, datetime.datetime]]) – Retrieve messages around this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time. When using this argument, the maximum limit is 101. Note that if the limit is an even number then this will return at most limit + 1 messages.

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

Raises:
  • Forbidden – You do not have permissions to get channel message history.

  • HTTPException – The request to get message history failed.

Yields:

Message – The message with the message data parsed.

await invites()[source]

This function is a coroutine.

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

You must have Permissions.manage_channels permission to use this.

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

  • HTTPException – An error occurred while fetching the information.

Returns:

The list of invites that are currently active.

Return type:

List[Invite]

property jump_url[source]

A URL that can be used to jump to this channel.

New in version 2.4.

Note

This exists for all guild channels but may not be usable by the client for all guild channel types.

property members[source]

Returns all members that are currently inside this voice channel.

Type:

List[Member]

property mention[source]

The string that allows you to mention the channel.

Type:

str

await move(**kwargs)[source]

This function is a coroutine.

A rich interface to help move a channel relative to other channels.

If exact position movement is required, edit should be used instead.

You must have Permissions.manage_channels permission to do this.

Note

Voice channels will always be sorted below text channels. This is a Discord limitation.

New in version 1.7.

Changed in version 2.6: Raises TypeError or ValueError instead of InvalidArgument.

Parameters:
  • beginning (bool) – Whether to move the channel to the beginning of the channel list (or category if given). This is mutually exclusive with end, before, and after.

  • end (bool) – Whether to move the channel to the end of the channel list (or category if given). This is mutually exclusive with beginning, before, and after.

  • before (abc.Snowflake) – The channel that should be before our current channel. This is mutually exclusive with beginning, end, and after.

  • after (abc.Snowflake) – The channel that should be after our current channel. This is mutually exclusive with beginning, end, and before.

  • offset (int) – The number of channels to offset the move by. For example, an offset of 2 with beginning=True would move it 2 after the beginning. A positive number moves it below while a negative number moves it above. Note that this number is relative and computed after the beginning, end, before, and after parameters.

  • category (Optional[abc.Snowflake]) – The category to move this channel under. If None is given then it moves it out of the category. This parameter is ignored if moving a category channel.

  • sync_permissions (bool) – Whether to sync the permissions with the category (if given).

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

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

  • HTTPException – Moving the channel failed.

  • TypeError – A bad mix of arguments were passed.

  • ValueError – An invalid position was given.

property overwrites[source]

Returns all of the channel’s overwrites.

This is returned as a dictionary where the key contains the target which can be either a Role or a Member and the value is the overwrite as a PermissionOverwrite.

Returns:

The channel’s permission overwrites.

Return type:

Dict[Union[Role, Member], PermissionOverwrite]

overwrites_for(obj)[source]

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

Parameters:

obj (Union[Role, abc.User]) – The role or user denoting whose overwrite to get.

Returns:

The permission overwrites for this object.

Return type:

PermissionOverwrite

property permissions_synced[source]

Whether or not the permissions for this channel are synced with the category it belongs to.

If there is no category then this is False.

New in version 1.3.

Type:

bool

await pins()[source]

This function is a coroutine.

Retrieves all messages that are currently pinned in the channel.

Note

Due to a limitation with the Discord API, the Message objects returned by this method do not contain complete Message.reactions data.

Raises:

HTTPException – Retrieving the pinned messages failed.

Returns:

The messages that are currently pinned.

Return type:

List[Message]

await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, suppress_embeds=False, allowed_mentions=None, reference=None, mention_author=None, view=None, components=None)[source]

This function is a coroutine.

Sends a message to the destination with the content given.

The content must be a type that can convert to a string through str(content).

At least one of content, embed/embeds, file/files, stickers, components, or view must be provided.

To upload a single file, the file parameter should be used with a single File object. To upload multiple files, the files parameter should be used with a list of File objects. Specifying both parameters will lead to an exception.

To upload a single embed, the embed parameter should be used with a single Embed object. To upload multiple embeds, the embeds parameter should be used with a list of Embed objects. Specifying both parameters will lead to an exception.

Changed in version 2.6: Raises TypeError or ValueError instead of InvalidArgument.

Parameters:
  • content (Optional[str]) – The content of the message to send.

  • tts (bool) – Whether the message should be sent using text-to-speech.

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

  • embeds (List[Embed]) –

    A list of embeds to send with the content. Must be a maximum of 10. This cannot be mixed with the embed parameter.

    New in version 2.0.

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

  • files (List[File]) – A list of files to upload. Must be a maximum of 10. This cannot be mixed with the file parameter.

  • stickers (Sequence[Union[GuildSticker, StickerItem]]) –

    A list of stickers to upload. Must be a maximum of 3.

    New in version 2.0.

  • nonce (Union[str, int]) – The nonce to use for sending this message. If the message was successfully sent, then the message will have a nonce with this value.

  • delete_after (float) – If provided, the number of seconds to wait in the background before deleting the message we just sent. If the deletion fails, then it is silently ignored.

  • allowed_mentions (AllowedMentions) –

    Controls the mentions being processed in this message. If this is passed, then the object is merged with Client.allowed_mentions. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set in Client.allowed_mentions. If no object is passed at all then the defaults given by Client.allowed_mentions are used instead.

    New in version 1.4.

  • reference (Union[Message, MessageReference, PartialMessage]) –

    A reference to the Message to which you are replying, this can be created using Message.to_reference() or passed directly as a Message. You can control whether this mentions the author of the referenced message using the AllowedMentions.replied_user attribute of allowed_mentions or by setting mention_author.

    New in version 1.6.

  • mention_author (Optional[bool]) –

    If set, overrides the AllowedMentions.replied_user attribute of allowed_mentions.

    New in version 1.6.

  • view (ui.View) –

    A Discord UI View to add to the message. This cannot be mixed with components.

    New in version 2.0.

  • components (Union[disnake.ui.ActionRow, disnake.ui.WrappedComponent, List[Union[disnake.ui.ActionRow, disnake.ui.WrappedComponent, List[disnake.ui.WrappedComponent]]]]) –

    A list of components to include in the message. This cannot be mixed with view.

    New in version 2.4.

  • suppress_embeds (bool) –

    Whether to suppress embeds for the message. This hides all embeds from the UI if set to True.

    New in version 2.5.

Raises:
Returns:

The message that was sent.

Return type:

Message

await set_permissions(target, *, overwrite=..., reason=None, **permissions)[source]

This function is a coroutine.

Sets the channel specific permission overwrites for a target in the channel.

The target parameter should either be a Member or a Role that belongs to guild.

The overwrite parameter, if given, must either be None or PermissionOverwrite. For convenience, you can pass in keyword arguments denoting Permissions attributes. If this is done, then you cannot mix the keyword arguments with the overwrite parameter.

If the overwrite parameter is None, then the permission overwrites are deleted.

You must have Permissions.manage_roles permission to do this.

Note

This method replaces the old overwrites with the ones given.

Changed in version 2.6: Raises TypeError instead of InvalidArgument.

Examples

Setting allow and deny:

await message.channel.set_permissions(message.author, view_channel=True,
                                                      send_messages=False)

Deleting overwrites

await channel.set_permissions(member, overwrite=None)

Using PermissionOverwrite

overwrite = disnake.PermissionOverwrite()
overwrite.send_messages = False
overwrite.view_channel = True
await channel.set_permissions(member, overwrite=overwrite)
Parameters:
  • target (Union[Member, Role]) – The member or role to overwrite permissions for.

  • overwrite (Optional[PermissionOverwrite]) – The permissions to allow and deny to the target, or None to delete the overwrite.

  • **permissions – A keyword argument list of permissions to set for ease of use. Cannot be mixed with overwrite.

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

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

  • HTTPException – Editing channel specific permissions failed.

  • NotFound – The role or member being edited is not part of the guild.

  • TypeErroroverwrite is invalid, the target type was not Role or Member, both keyword arguments and overwrite were provided, or invalid permissions were provided as keyword arguments.

await trigger_typing()[source]

This function is a coroutine.

Triggers a typing indicator to the destination.

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

typing()[source]

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

This is useful for denoting long computations in your bot.

Note

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

Example Usage:

async with channel.typing():
    # simulate something heavy
    await asyncio.sleep(10)

await channel.send('done!')
property voice_states[source]

Returns a mapping of member IDs who have voice states in this channel.

New in version 1.3.

Note

This function is intentionally low level to replace members when the member cache is unavailable.

Returns:

The mapping of member ID to a voice state.

Return type:

Mapping[int, VoiceState]

StageChannel
class disnake.StageChannel[source]

Represents a Discord guild stage channel.

New in version 1.7.

x == y

Checks if two channels are equal.

x != y

Checks if two channels are not equal.

hash(x)

Returns the channel’s hash.

str(x)

Returns the channel’s name.

name

The channel’s name.

Type:

str

guild

The guild the channel belongs to.

Type:

Guild

id

The channel’s ID.

Type:

int

topic

The channel’s topic. None if it isn’t set.

Type:

Optional[str]

category_id

The category channel ID this channel belongs to, if applicable.

Type:

Optional[int]

position

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

Type:

int

bitrate

The channel’s preferred audio bitrate in bits per second.

Type:

int

user_limit

The channel’s limit for number of members that can be in a stage channel.

Type:

int

rtc_region

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

Changed in version 2.5: No longer a VoiceRegion instance.

Type:

Optional[str]

video_quality_mode

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

New in version 2.0.

Type:

VideoQualityMode

property requesting_to_speak[source]

A list of members who are requesting to speak in the stage channel.

Type:

List[Member]

property speakers[source]

A list of members who have been permitted to speak in the stage channel.

New in version 2.0.

Type:

List[Member]

property listeners[source]

A list of members who are listening in the stage channel.

New in version 2.0.

Type:

List[Member]

property moderators[source]

A list of members who are moderating the stage channel.

New in version 2.0.

Type:

List[Member]

property type[source]

The channel’s Discord type.

This always returns ChannelType.stage_voice.

Type:

ChannelType

await clone(*, name=None, reason=None)[source]

This function is a coroutine.

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

You must have Permissions.manage_channels permission to do this.

New in version 1.1.

Parameters:
  • name (Optional[str]) – The name of the new channel. If not provided, defaults to this channel name.

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

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

  • HTTPException – Creating the channel failed.

Returns:

The channel that was created.

Return type:

abc.GuildChannel

property instance[source]

The running stage instance of the stage channel.

New in version 2.0.

Type:

Optional[StageInstance]

permissions_for(obj, /, *, ignore_timeout=...)[source]

Handles permission resolution for the Member or Role.

This function takes into consideration the following cases:

  • Guild owner

  • Guild roles

  • Channel overrides

  • Member overrides

  • Timeouts

If a Role is passed, then it checks the permissions someone with that role would have, which is essentially:

  • The default role permissions

  • The permissions of the role used as a parameter

  • The default role permission overwrites

  • The permission overwrites of the role used as a parameter

Changed in version 2.0: The object passed in can now be a role object.

Parameters:
  • obj (Union[Member, Role]) – The object to resolve permissions for. This could be either a member or a role. If it’s a role then member overwrites are not computed.

  • ignore_timeout (bool) –

    Whether or not to ignore the user’s timeout. Defaults to False.

    New in version 2.4.

    Note

    This only applies to Member objects.

    Changed in version 2.6: The default was changed to False.

Raises:

TypeErrorignore_timeout is only supported for Member objects.

Returns:

The resolved permissions for the member or role.

Return type:

Permissions

await create_instance(*, topic, privacy_level=..., notify_everyone=False, reason=None)[source]

This function is a coroutine.

Creates a stage instance.

You must have manage_channels permission to do this.

New in version 2.0.

Changed in version 2.6: Raises TypeError instead of InvalidArgument.

Parameters:
  • topic (str) – The stage instance’s topic.

  • privacy_level (StagePrivacyLevel) – The stage instance’s privacy level. Defaults to StagePrivacyLevel.guild_only.

  • reason (Optional[str]) – The reason the stage instance was created. Shows up on the audit log.

  • notify_everyone (bool) –

    Whether to notify @everyone that the stage instance has started. Requires the mention_everyone permission on the stage channel. Defaults to False.

    New in version 2.5.

Raises:
  • Forbidden – You do not have permissions to create a stage instance.

  • HTTPException – Creating a stage instance failed.

  • TypeError – If the privacy_level parameter is not the proper type.

Returns:

The newly created stage instance.

Return type:

StageInstance

await fetch_instance()[source]

This function is a coroutine.

Retrieves the running StageInstance.

New in version 2.0.

Raises:
  • NotFound – The stage instance or channel could not be found.

  • HTTPException – Retrieving the stage instance failed.

Returns:

The stage instance.

Return type:

StageInstance

await edit(*, name=..., position=..., sync_permissions=..., category=..., overwrites=..., rtc_region=..., video_quality_mode=..., bitrate=..., flags=..., reason=None, **kwargs)[source]

This function is a coroutine.

Edits the channel.

You must have manage_channels permission to do this.

Changed in version 2.0: The topic parameter must now be set via create_instance.

Changed in version 2.0: Edits are no longer in-place, the newly edited channel is returned instead.

Changed in version 2.6: Raises TypeError or ValueError instead of InvalidArgument.

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

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

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

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

  • overwrites (Mapping) – A Mapping of target (either a role or a member) to PermissionOverwrite to apply to the channel.

  • rtc_region (Optional[Union[str, VoiceRegion]]) – The new region for the stage channel’s voice communication. A value of None indicates automatic voice region detection.

  • video_quality_mode (VideoQualityMode) –

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

    New in version 2.0.

  • bitrate (int) –

    The new channel’s bitrate.

    New in version 2.6.

  • flags (ChannelFlags) –

    The new flags to set for this channel. This will overwrite any existing flags set on this channel.

    New in version 2.6.

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

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

  • HTTPException – Editing the channel failed.

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

  • ValueError – The position is less than 0.

Returns:

The newly edited stage channel. If the edit was only positional then None is returned instead.

Return type:

Optional[StageChannel]

property category[source]

The category this channel belongs to.

If there is no category then this is None.

Type:

Optional[CategoryChannel]

property changed_roles[source]

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

Type:

List[Role]

await connect(*, timeout=60.0, reconnect=True, cls=<class 'disnake.voice_client.VoiceClient'>)[source]

This function is a coroutine.

Connects to voice and creates a VoiceClient to establish your connection to the voice server.

This requires Intents.voice_states.

Parameters:
  • timeout (float) – The timeout in seconds to wait for the voice endpoint.

  • reconnect (bool) – Whether the bot should automatically attempt a reconnect if a part of the handshake fails or the gateway goes down.

  • cls (Type[VoiceProtocol]) – A type that subclasses VoiceProtocol to connect with. Defaults to VoiceClient.

Raises:
Returns:

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

Return type:

VoiceProtocol

await create_invite(*, reason=None, max_age=0, max_uses=0, temporary=False, unique=True, target_type=None, target_user=None, target_application=None, guild_scheduled_event=None)[source]

This function is a coroutine.

Creates an instant invite from a text or voice channel.

You must have Permissions.create_instant_invite permission to do this.

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

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

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

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

  • target_type (Optional[InviteTarget]) –

    The type of target for the voice channel invite, if any.

    New in version 2.0.

  • target_user (Optional[User]) –

    The user whose stream to display for this invite, required if target_type is TargetType.stream. The user must be streaming in the channel.

    New in version 2.0.

  • target_application (Optional[PartyType]) –

    The ID of the embedded application for the invite, required if target_type is TargetType.embedded_application.

    New in version 2.0.

  • guild_scheduled_event (Optional[GuildScheduledEvent]) –

    The guild scheduled event to include with the invite.

    New in version 2.3.

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

Raises:
  • HTTPException – Invite creation failed.

  • NotFound – The channel that was passed is a category or an invalid channel.

Returns:

The newly created invite.

Return type:

Invite

property created_at[source]

Returns the channel’s creation time in UTC.

Type:

datetime.datetime

await delete(*, reason=None)[source]

This function is a coroutine.

Deletes the channel.

You must have Permissions.manage_channels permission to do this.

Parameters:

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

Raises:
  • Forbidden – You do not have proper permissions to delete the channel.

  • NotFound – The channel was not found or was already deleted.

  • HTTPException – Deleting the channel failed.

property flags[source]

The channel flags for this channel.

New in version 2.6.

Type:

ChannelFlags

await invites()[source]

This function is a coroutine.

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

You must have Permissions.manage_channels permission to use this.

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

  • HTTPException – An error occurred while fetching the information.

Returns:

The list of invites that are currently active.

Return type:

List[Invite]

property jump_url[source]

A URL that can be used to jump to this channel.

New in version 2.4.

Note

This exists for all guild channels but may not be usable by the client for all guild channel types.

property members[source]

Returns all members that are currently inside this voice channel.

Type:

List[Member]

property mention[source]

The string that allows you to mention the channel.

Type:

str

await move(**kwargs)[source]

This function is a coroutine.

A rich interface to help move a channel relative to other channels.

If exact position movement is required, edit should be used instead.

You must have Permissions.manage_channels permission to do this.

Note

Voice channels will always be sorted below text channels. This is a Discord limitation.

New in version 1.7.

Changed in version 2.6: Raises TypeError or ValueError instead of InvalidArgument.

Parameters:
  • beginning (bool) – Whether to move the channel to the beginning of the channel list (or category if given). This is mutually exclusive with end, before, and after.

  • end (bool) – Whether to move the channel to the end of the channel list (or category if given). This is mutually exclusive with beginning, before, and after.

  • before (abc.Snowflake) – The channel that should be before our current channel. This is mutually exclusive with beginning, end, and after.

  • after (abc.Snowflake) – The channel that should be after our current channel. This is mutually exclusive with beginning, end, and before.

  • offset (int) – The number of channels to offset the move by. For example, an offset of 2 with beginning=True would move it 2 after the beginning. A positive number moves it below while a negative number moves it above. Note that this number is relative and computed after the beginning, end, before, and after parameters.

  • category (Optional[abc.Snowflake]) – The category to move this channel under. If None is given then it moves it out of the category. This parameter is ignored if moving a category channel.

  • sync_permissions (bool) – Whether to sync the permissions with the category (if given).

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

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

  • HTTPException – Moving the channel failed.

  • TypeError – A bad mix of arguments were passed.

  • ValueError – An invalid position was given.

property overwrites[source]

Returns all of the channel’s overwrites.

This is returned as a dictionary where the key contains the target which can be either a Role or a Member and the value is the overwrite as a PermissionOverwrite.

Returns:

The channel’s permission overwrites.

Return type:

Dict[Union[Role, Member], PermissionOverwrite]

overwrites_for(obj)[source]

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

Parameters:

obj (Union[Role, abc.User]) – The role or user denoting whose overwrite to get.

Returns:

The permission overwrites for this object.

Return type:

PermissionOverwrite

property permissions_synced[source]

Whether or not the permissions for this channel are synced with the category it belongs to.

If there is no category then this is False.

New in version 1.3.

Type:

bool

await set_permissions(target, *, overwrite=..., reason=None, **permissions)[source]

This function is a coroutine.

Sets the channel specific permission overwrites for a target in the channel.

The target parameter should either be a Member or a Role that belongs to guild.

The overwrite parameter, if given, must either be None or PermissionOverwrite. For convenience, you can pass in keyword arguments denoting Permissions attributes. If this is done, then you cannot mix the keyword arguments with the overwrite parameter.

If the overwrite parameter is None, then the permission overwrites are deleted.

You must have Permissions.manage_roles permission to do this.

Note

This method replaces the old overwrites with the ones given.

Changed in version 2.6: Raises TypeError instead of InvalidArgument.

Examples

Setting allow and deny:

await message.channel.set_permissions(message.author, view_channel=True,
                                                      send_messages=False)

Deleting overwrites

await channel.set_permissions(member, overwrite=None)

Using PermissionOverwrite

overwrite = disnake.PermissionOverwrite()
overwrite.send_messages = False
overwrite.view_channel = True
await channel.set_permissions(member, overwrite=overwrite)
Parameters:
  • target (Union[Member, Role]) – The member or role to overwrite permissions for.

  • overwrite (Optional[PermissionOverwrite]) – The permissions to allow and deny to the target, or None to delete the overwrite.

  • **permissions – A keyword argument list of permissions to set for ease of use. Cannot be mixed with overwrite.

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

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

  • HTTPException – Editing channel specific permissions failed.

  • NotFound – The role or member being edited is not part of the guild.

  • TypeErroroverwrite is invalid, the target type was not Role or Member, both keyword arguments and overwrite were provided, or invalid permissions were provided as keyword arguments.

property voice_states[source]

Returns a mapping of member IDs who have voice states in this channel.

New in version 1.3.

Note

This function is intentionally low level to replace members when the member cache is unavailable.

Returns:

The mapping of member ID to a voice state.

Return type:

Mapping[int, VoiceState]

ForumChannel
class disnake.ForumChannel[source]

Represents a Discord Forum channel.

New in version 2.5.

x == y

Checks if two channels are equal.

x != y

Checks if two channels are not equal.

hash(x)

Returns the channel’s hash.

str(x)

Returns the channel’s name.

id

The channel’s ID.

Type:

int

name

The channel’s name.

Type:

str

guild

The guild the channel belongs to.

Type:

Guild

topic

The channel’s topic. None if it isn’t set.

Type:

Optional[str]

category_id

The category channel ID this channel belongs to, if applicable.

Type:

Optional[int]

position

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

Type:

int

nsfw

Whether the channel is marked as “not safe for work”.

Note

To check if the channel or the guild of that channel are marked as NSFW, consider is_nsfw() instead.

Type:

bool

last_thread_id

The ID of the last created thread in this channel. It may not point to an existing or valid thread.

Type:

Optional[int]

default_auto_archive_duration

The default auto archive duration in minutes for threads created in this channel.

Type:

int

slowmode_delay

The number of seconds a member must wait between creating threads in this channel.

A value of 0 denotes that it is disabled. Bots, and users with manage_channels or manage_messages, bypass slowmode.

See also default_thread_slowmode_delay.

Type:

int

default_thread_slowmode_delay

The default number of seconds a member must wait between sending messages in newly created threads in this channel.

A value of 0 denotes that it is disabled. Bots, and users with manage_channels or manage_messages, bypass slowmode.

New in version 2.6.

Type:

int

default_sort_order

The default sort order of threads in this channel. Members will still be able to change this locally.

New in version 2.6.

Type:

Optional[ThreadSortOrder]

async with typing()[source]

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

This is useful for denoting long computations in your bot.

Note

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

Example Usage:

async with channel.typing():
    # simulate something heavy
    await asyncio.sleep(10)

await channel.send('done!')
property type[source]

The channel’s Discord type.

This always returns ChannelType.forum.

Type:

ChannelType

permissions_for(obj, /, *, ignore_timeout=...)[source]

Handles permission resolution for the Member or Role.

This function takes into consideration the following cases:

  • Guild owner

  • Guild roles

  • Channel overrides

  • Member overrides

  • Timeouts

If a Role is passed, then it checks the permissions someone with that role would have, which is essentially:

  • The default role permissions

  • The permissions of the role used as a parameter

  • The default role permission overwrites

  • The permission overwrites of the role used as a parameter

Changed in version 2.0: The object passed in can now be a role object.

Parameters:
  • obj (Union[Member, Role]) – The object to resolve permissions for. This could be either a member or a role. If it’s a role then member overwrites are not computed.

  • ignore_timeout (bool) –

    Whether or not to ignore the user’s timeout. Defaults to False.

    New in version 2.4.

    Note

    This only applies to Member objects.

    Changed in version 2.6: The default was changed to False.

Raises:

TypeErrorignore_timeout is only supported for Member objects.

Returns:

The resolved permissions for the member or role.

Return type:

Permissions

property members[source]

Returns all members that can see this channel.

Type:

List[Member]

property threads[source]

Returns all the threads that you can see.

Type:

List[Thread]

is_nsfw()[source]

Whether the channel is marked as NSFW.

Return type:

bool

requires_tag()[source]

Whether all newly created threads in this channel are required to have a tag.

This is a shortcut to self.flags.require_tag.

New in version 2.6.

Return type:

bool

property default_reaction[source]

Optional[Union[Emoji, PartialEmoji]]: The default emoji shown for reacting to threads.

Due to a Discord limitation, this will have an empty name if it is a custom PartialEmoji.

New in version 2.6.

property last_thread[source]

Gets the last created thread in this channel from the cache.

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

Reliable Fetching

For a slightly more reliable method of fetching the last thread, use Guild.fetch_channel() with the last_thread_id attribute.

Returns:

The last created thread in this channel or None if not found.

Return type:

Optional[Thread]

property available_tags[source]

The available tags for threads in this forum channel.

To create/edit/delete tags, use edit().

New in version 2.6.

Type:

List[ForumTag]

await trigger_typing()[source]

This function is a coroutine.

Triggers a typing indicator to the desination.

Typing indicator will go away after 10 seconds.

await edit(*, name=..., topic=..., position=..., nsfw=..., sync_permissions=..., category=..., slowmode_delay=..., default_thread_slowmode_delay=..., default_auto_archive_duration=..., overwrites=..., flags=..., require_tag=..., available_tags=..., default_reaction=..., default_sort_order=..., reason=None, **kwargs)[source]

This function is a coroutine.

Edits the channel.

You must have manage_channels permission to do this.

Changed in version 2.6: Raises TypeError or ValueError instead of InvalidArgument.

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

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

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

  • nsfw (bool) – Whether to mark the channel as NSFW.

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

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

  • slowmode_delay (Optional[int]) – Specifies the slowmode rate limit at which users can create threads in this channel, in seconds. A value of 0 or None disables slowmode. The maximum value possible is 21600.

  • default_thread_slowmode_delay (Optional[int]) –

    Specifies the slowmode rate limit at which users can send messages in newly created threads in this channel, in seconds. This does not apply retroactively to existing threads. A value of 0 or None disables slowmode. The maximum value possible is 21600.

    New in version 2.6.

  • overwrites (Mapping) – A Mapping of target (either a role or a member) to PermissionOverwrite to apply to the channel.

  • default_auto_archive_duration (Optional[Union[int, ThreadArchiveDuration]]) – The new default auto archive duration in minutes for threads created in this channel. Must be one of 60, 1440, 4320, or 10080.

  • flags (ChannelFlags) –

    The new flags to set for this channel. This will overwrite any existing flags set on this channel. If parameter require_tag is provided, that will override the setting of ChannelFlags.require_tag.

    New in version 2.6.

  • require_tag (bool) –

    Whether all newly created threads are required to have a tag.

    New in version 2.6.

  • available_tags (Sequence[ForumTag]) –

    The new ForumTags available for threads in this channel. Can be used to create new tags and edit/reorder/delete existing tags. Maximum of 20.

    Note that this overwrites all tags, removing existing tags unless they’re passed as well.

    See ForumTag for examples regarding creating/editing tags.

    New in version 2.6.

  • default_reaction (Optional[Union[str, Emoji, PartialEmoji]]) –

    The new default emoji shown for reacting to threads.

    New in version 2.6.

  • default_sort_order (Optional[ThreadSortOrder]) –

    The new default sort order of threads in this channel.

    New in version 2.6.

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

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

  • HTTPException – Editing the channel failed.

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

  • ValueError – The position is less than 0.

Returns:

The newly edited forum channel. If the edit was only positional then None is returned instead.

Return type:

Optional[ForumChannel]

await clone(*, name=None, reason=None)[source]

This function is a coroutine.

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

You must have Permissions.manage_channels permission to do this.

New in version 1.1.

Parameters:
  • name (Optional[str]) – The name of the new channel. If not provided, defaults to this channel name.

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

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

  • HTTPException – Creating the channel failed.

Returns:

The channel that was created.

Return type:

abc.GuildChannel

get_thread(thread_id, /)[source]

Returns a thread with the given ID.

Parameters:

thread_id (int) – The ID to search for.

Returns:

The returned thread of None if not found.

Return type:

Optional[Thread]

await create_thread(*, name, auto_archive_duration=..., slowmode_delay=..., applied_tags=..., content=..., embed=..., embeds=..., file=..., files=..., suppress_embeds=..., stickers=..., allowed_mentions=..., view=..., components=..., reason=None)[source]

This function is a coroutine.

Creates a thread in this forum channel.

You must have the create_forum_threads permission to do this.

At least one of content, embed/embeds, file/files, stickers, components, or view must be provided.

Changed in version 2.6: Raises TypeError or ValueError instead of InvalidArgument.

Changed in version 2.6: The content parameter is no longer required.

Parameters:
  • name (str) – The name of the thread.

  • auto_archive_duration (Union[int, ThreadArchiveDuration]) – The duration in minutes before the thread is automatically archived for inactivity. If not provided, the channel’s default auto archive duration is used. Must be one of 60, 1440, 4320, or 10080.

  • slowmode_delay (int) – Specifies the slowmode rate limit for users in this thread, in seconds. A value of 0 disables slowmode. The maximum value possible is 21600. If not provided, slowmode is inherited from the parent’s default_thread_slowmode_delay.

  • applied_tags (Sequence[abc.Snowflake]) –

    The tags to apply to the new thread. Maximum of 5.

    New in version 2.6.

  • content (str) – The content of the message to send.

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

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

  • suppress_embeds (bool) – Whether to suppress embeds for the message. This hides all embeds from the UI if set to True.

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

  • files (List[File]) – A list of files to upload. Must be a maximum of 10. This cannot be mixed with the file parameter.

  • stickers (Sequence[Union[GuildSticker, StickerItem]]) – A list of stickers to upload. Must be a maximum of 3.

  • allowed_mentions (AllowedMentions) – Controls the mentions being processed in this message. If this is passed, then the object is merged with Client.allowed_mentions. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set in Client.allowed_mentions. If no object is passed at all then the defaults given by Client.allowed_mentions are used instead.

  • view (ui.View) – A Discord UI View to add to the message. This cannot be mixed with components.

  • components (Union[disnake.ui.ActionRow, disnake.ui.WrappedComponent, List[Union[disnake.ui.ActionRow, disnake.ui.WrappedComponent, List[disnake.ui.WrappedComponent]]]]) – A list of components to include in the message. This cannot be mixed with view.

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

Raises:
  • Forbidden – You do not have permissions to create a thread.

  • HTTPException – Starting the thread failed.

  • TypeError – Specified both file and files, or you specified both embed and embeds, or you specified both view and components. or you have passed an object that is not File to file or files.

  • ValueError – Specified more than 10 embeds, or more than 10 files.

Returns:

A NamedTuple with the newly created thread and the message sent in it.

These values can also be accessed through the thread and message fields.

Return type:

Tuple[Thread, Message]

archived_threads(*, limit=50, before=None)[source]

Returns an AsyncIterator that iterates over all archived threads in the channel.

You must have read_message_history permission to use this.

Parameters:
  • limit (Optional[int]) – The number of threads to retrieve. If None, retrieves every archived thread in the channel. Note, however, that this would make it a slow operation.

  • before (Optional[Union[abc.Snowflake, datetime.datetime]]) – Retrieve archived channels before the given date or ID.

Raises:
  • Forbidden – You do not have permissions to get archived threads.

  • HTTPException – The request to get the archived threads failed.

Yields:

Thread – The archived threads.

await webhooks()[source]

This function is a coroutine.

Retrieves the list of webhooks this channel has.

You must have manage_webhooks permission to use this.

New in version 2.6.

Raises:

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

Returns:

The list of webhooks this channel has.

Return type:

List[Webhook]

await create_webhook(*, name, avatar=None, reason=None)[source]

This function is a coroutine.

Creates a webhook for this channel.

You must have manage_webhooks permission to do this.

New in version 2.6.

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

  • avatar (Optional[bytes]) – The webhook’s default avatar. This operates similarly to edit().

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

Raises:
Returns:

The newly created webhook.

Return type:

Webhook

get_tag(tag_id, /)[source]

Returns a thread tag with the given ID.

New in version 2.6.

Parameters:

tag_id (int) – The ID to search for.

Returns:

The tag with the given ID, or None if not found.

Return type:

Optional[ForumTag]

get_tag_by_name(name, /)[source]

Returns a thread tag with the given name.

Tags can be uniquely identified based on the name, as tag names in a forum channel must be unique.

New in version 2.6.

Parameters:

name (str) – The name to search for.

Returns:

The tag with the given name, or None if not found.

Return type:

Optional[ForumTag]

property category[source]

The category this channel belongs to.

If there is no category then this is None.

Type:

Optional[CategoryChannel]

property changed_roles[source]

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

Type:

List[Role]

await create_invite(*, reason=None, max_age=0, max_uses=0, temporary=False, unique=True, target_type=None, target_user=None, target_application=None, guild_scheduled_event=None)[source]

This function is a coroutine.

Creates an instant invite from a text or voice channel.

You must have Permissions.create_instant_invite permission to do this.

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

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

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

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

  • target_type (Optional[InviteTarget]) –

    The type of target for the voice channel invite, if any.

    New in version 2.0.

  • target_user (Optional[User]) –

    The user whose stream to display for this invite, required if target_type is TargetType.stream. The user must be streaming in the channel.

    New in version 2.0.

  • target_application (Optional[PartyType]) –

    The ID of the embedded application for the invite, required if target_type is TargetType.embedded_application.

    New in version 2.0.

  • guild_scheduled_event (Optional[GuildScheduledEvent]) –

    The guild scheduled event to include with the invite.

    New in version 2.3.

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

Raises:
  • HTTPException – Invite creation failed.

  • NotFound – The channel that was passed is a category or an invalid channel.

Returns:

The newly created invite.

Return type:

Invite

property created_at[source]

Returns the channel’s creation time in UTC.

Type:

datetime.datetime

await delete(*, reason=None)[source]

This function is a coroutine.

Deletes the channel.

You must have Permissions.manage_channels permission to do this.

Parameters:

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

Raises:
  • Forbidden – You do not have proper permissions to delete the channel.

  • NotFound – The channel was not found or was already deleted.

  • HTTPException – Deleting the channel failed.

property flags[source]

The channel flags for this channel.

New in version 2.6.

Type:

ChannelFlags

await invites()[source]

This function is a coroutine.

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

You must have Permissions.manage_channels permission to use this.

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

  • HTTPException – An error occurred while fetching the information.

Returns:

The list of invites that are currently active.

Return type:

List[Invite]

property jump_url[source]

A URL that can be used to jump to this channel.

New in version 2.4.

Note

This exists for all guild channels but may not be usable by the client for all guild channel types.

property mention[source]

The string that allows you to mention the channel.

Type:

str

await move(**kwargs)[source]

This function is a coroutine.

A rich interface to help move a channel relative to other channels.

If exact position movement is required, edit should be used instead.

You must have Permissions.manage_channels permission to do this.

Note

Voice channels will always be sorted below text channels. This is a Discord limitation.

New in version 1.7.

Changed in version 2.6: Raises TypeError or ValueError instead of InvalidArgument.

Parameters:
  • beginning (bool) – Whether to move the channel to the beginning of the channel list (or category if given). This is mutually exclusive with end, before, and after.

  • end (bool) – Whether to move the channel to the end of the channel list (or category if given). This is mutually exclusive with beginning, before, and after.

  • before (abc.Snowflake) – The channel that should be before our current channel. This is mutually exclusive with beginning, end, and after.

  • after (abc.Snowflake) – The channel that should be after our current channel. This is mutually exclusive with beginning, end, and before.

  • offset (int) – The number of channels to offset the move by. For example, an offset of 2 with beginning=True would move it 2 after the beginning. A positive number moves it below while a negative number moves it above. Note that this number is relative and computed after the beginning, end, before, and after parameters.

  • category (Optional[abc.Snowflake]) – The category to move this channel under. If None is given then it moves it out of the category. This parameter is ignored if moving a category channel.

  • sync_permissions (bool) – Whether to sync the permissions with the category (if given).

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

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

  • HTTPException – Moving the channel failed.

  • TypeError – A bad mix of arguments were passed.

  • ValueError – An invalid position was given.

property overwrites[source]

Returns all of the channel’s overwrites.

This is returned as a dictionary where the key contains the target which can be either a Role or a Member and the value is the overwrite as a PermissionOverwrite.

Returns:

The channel’s permission overwrites.

Return type:

Dict[Union[Role, Member], PermissionOverwrite]

overwrites_for(obj)[source]

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

Parameters:

obj (Union[Role, abc.User]) – The role or user denoting whose overwrite to get.

Returns:

The permission overwrites for this object.

Return type:

PermissionOverwrite

property permissions_synced[source]

Whether or not the permissions for this channel are synced with the category it belongs to.

If there is no category then this is False.

New in version 1.3.

Type:

bool

await set_permissions(target, *, overwrite=..., reason=None, **permissions)[source]

This function is a coroutine.

Sets the channel specific permission overwrites for a target in the channel.

The target parameter should either be a Member or a Role that belongs to guild.

The overwrite parameter, if given, must either be None or PermissionOverwrite. For convenience, you can pass in keyword arguments denoting Permissions attributes. If this is done, then you cannot mix the keyword arguments with the overwrite parameter.

If the overwrite parameter is None, then the permission overwrites are deleted.

You must have Permissions.manage_roles permission to do this.

Note

This method replaces the old overwrites with the ones given.

Changed in version 2.6: Raises TypeError instead of InvalidArgument.

Examples

Setting allow and deny:

await message.channel.set_permissions(message.author, view_channel=True,
                                                      send_messages=False)

Deleting overwrites

await channel.set_permissions(member, overwrite=None)

Using PermissionOverwrite

overwrite = disnake.PermissionOverwrite()
overwrite.send_messages = False
overwrite.view_channel = True
await channel.set_permissions(member, overwrite=overwrite)
Parameters:
  • target (Union[Member, Role]) – The member or role to overwrite permissions for.

  • overwrite (Optional[PermissionOverwrite]) – The permissions to allow and deny to the target, or None to delete the overwrite.

  • **permissions – A keyword argument list of permissions to set for ease of use. Cannot be mixed with overwrite.

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

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

  • HTTPException – Editing channel specific permissions failed.

  • NotFound – The role or member being edited is not part of the guild.

  • TypeErroroverwrite is invalid, the target type was not Role or Member, both keyword arguments and overwrite were provided, or invalid permissions were provided as keyword arguments.

StageInstance
class disnake.StageInstance[source]

Represents a stage instance of a stage channel in a guild.

New in version 2.0.

x == y

Checks if two stage instances are equal.

x != y

Checks if two stage instances are not equal.

hash(x)

Returns the stage instance’s hash.

id

The stage instance’s ID.

Type:

int

guild

The guild that the stage instance is running in.

Type:

Guild

channel_id

The ID of the channel that the stage instance is running in.

Type:

int

topic

The topic of the stage instance.

Type:

str

privacy_level

The privacy level of the stage instance.

Type:

StagePrivacyLevel

guild_scheduled_event_id

The ID of the stage instance’s associated scheduled event, if applicable. See also guild_scheduled_event.

Type:

Optional[int]

channel

The channel that stage instance is running in.

Type:

Optional[StageChannel]

property discoverable_disabled[source]

Whether discoverability for the stage instance is disabled.

Deprecated since version 2.5: Stages can no longer be discoverable.

Type:

bool

is_public()[source]

Whether the stage instance is public.

Deprecated since version 2.5: Stages can no longer be public.

Return type:

bool

property guild_scheduled_event[source]

The stage instance’s scheduled event.

This is only set if this stage instance has an associated scheduled event, and requires that event to be cached (which requires the guild_scheduled_events intent).

Type:

Optional[GuildScheduledEvent]

await edit(*, topic=..., privacy_level=..., reason=None)[source]

This function is a coroutine.

Edits the stage instance.

You must have the manage_channels permission to use this.

Changed in version 2.6: Raises TypeError instead of InvalidArgument.

Parameters:
  • topic (str) – The stage instance’s new topic.

  • privacy_level (StagePrivacyLevel) – The stage instance’s new privacy level.

  • reason (Optional[str]) – The reason the stage instance was edited. Shows up on the audit log.

Raises:
  • TypeError – If the privacy_level parameter is not the proper type.

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

  • HTTPException – Editing a stage instance failed.

await delete(*, reason=None)[source]

This function is a coroutine.

Deletes the stage instance.

You must have the manage_channels permission to use this.

Parameters:

reason (Optional[str]) – The reason the stage instance was deleted. Shows up on the audit log.

Raises:
  • Forbidden – You do not have permissions to delete the stage instance.

  • HTTPException – Deleting the stage instance failed.

CategoryChannel
class disnake.CategoryChannel[source]

Represents a Discord channel category.

These are useful to group channels to logical compartments.

x == y

Checks if two channels are equal.

x != y

Checks if two channels are not equal.

hash(x)

Returns the category’s hash.

str(x)

Returns the category’s name.

name

The category name.

Type:

str

guild

The guild the category belongs to.

Type:

Guild

id

The category channel ID.

Type:

int

position

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

Type:

int

nsfw

If the channel is marked as “not safe for work”.

Note

To check if the channel or the guild of that channel are marked as NSFW, consider is_nsfw() instead.

Type:

bool

property type[source]

The channel’s Discord type.

This always returns ChannelType.category.

Type:

ChannelType

is_nsfw()[source]

Whether the category is marked as NSFW.

Return type:

bool

await clone(*, name=None, reason=None)[source]

This function is a coroutine.

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

You must have Permissions.manage_channels permission to do this.

New in version 1.1.

Parameters:
  • name (Optional[str]) – The name of the new channel. If not provided, defaults to this channel name.

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

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

  • HTTPException – Creating the channel failed.

Returns:

The channel that was created.

Return type:

abc.GuildChannel

await edit(*, name=..., position=..., nsfw=..., overwrites=..., flags=..., reason=None, **kwargs)[source]

This function is a coroutine.

Edits the category.

You must have manage_channels permission to do this.

Changed in version 1.3: The overwrites keyword-only parameter was added.

Changed in version 2.0: Edits are no longer in-place, the newly edited channel is returned instead.

Changed in version 2.6: Raises TypeError or ValueError instead of InvalidArgument.

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

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

  • nsfw (bool) – Whether to mark the category as NSFW.

  • overwrites (Mapping) – A Mapping of target (either a role or a member) to PermissionOverwrite to apply to the category.

  • flags (ChannelFlags) –

    The new flags to set for this channel. This will overwrite any existing flags set on this channel.

    New in version 2.6.

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

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

  • HTTPException – Editing the category failed.

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

  • ValueError – The position is less than 0.

Returns:

The newly edited category channel. If the edit was only positional then None is returned instead.

Return type:

Optional[CategoryChannel]

await move(**kwargs)[source]

This function is a coroutine.

A rich interface to help move a channel relative to other channels.

If exact position movement is required, edit should be used instead.

You must have Permissions.manage_channels permission to do this.

Note

Voice channels will always be sorted below text channels. This is a Discord limitation.

New in version 1.7.

Changed in version 2.6: Raises TypeError or ValueError instead of InvalidArgument.

Parameters:
  • beginning (bool) – Whether to move the channel to the beginning of the channel list (or category if given). This is mutually exclusive with end, before, and after.

  • end (bool) – Whether to move the channel to the end of the channel list (or category if given). This is mutually exclusive with beginning, before, and after.

  • before (abc.Snowflake) – The channel that should be before our current channel. This is mutually exclusive with beginning, end, and after.

  • after (abc.Snowflake) – The channel that should be after our current channel. This is mutually exclusive with beginning, end, and before.

  • offset (int) – The number of channels to offset the move by. For example, an offset of 2 with beginning=True would move it 2 after the beginning. A positive number moves it below while a negative number moves it above. Note that this number is relative and computed after the beginning, end, before, and after parameters.

  • category (Optional[abc.Snowflake]) – The category to move this channel under. If None is given then it moves it out of the category. This parameter is ignored if moving a category channel.

  • sync_permissions (bool) – Whether to sync the permissions with the category (if given).

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

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

  • HTTPException – Moving the channel failed.

  • TypeError – A bad mix of arguments were passed.

  • ValueError – An invalid position was given.

property channels[source]

Returns the channels that are under this category.

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

Type:

List[abc.GuildChannel]

property text_channels[source]

Returns the text channels that are under this category.

Type:

List[TextChannel]

property voice_channels[source]

Returns the voice channels that are under this category.

Type:

List[VoiceChannel]

property stage_channels[source]

Returns the stage channels that are under this category.

New in version 1.7.

Type:

List[StageChannel]

property forum_channels[source]

Returns the forum channels that are under this category.

New in version 2.5.

Type:

List[ForumChannel]

await create_text_channel(name, **options)[source]

This function is a coroutine.

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

Returns:

The newly created text channel.

Return type:

TextChannel

await create_voice_channel(name, **options)[source]

This function is a coroutine.

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

Returns:

The newly created voice channel.

Return type:

VoiceChannel

await create_stage_channel(name, **options)[source]

This function is a coroutine.

A shortcut method to Guild.create_stage_channel() to create a StageChannel in the category.

New in version 1.7.

Returns:

The newly created stage channel.

Return type:

StageChannel

await create_forum_channel(name, **options)[source]

This function is a coroutine.

A shortcut method to Guild.create_forum_channel() to create a ForumChannel in the category.

New in version 2.5.

Returns:

The newly created forum channel.

Return type:

ForumChannel

property category[source]

The category this channel belongs to.

If there is no category then this is None.

Type:

Optional[CategoryChannel]

property changed_roles[source]

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

Type:

List[Role]

await create_invite(*, reason=None, max_age=0, max_uses=0, temporary=False, unique=True, target_type=None, target_user=None, target_application=None, guild_scheduled_event=None)[source]

This function is a coroutine.

Creates an instant invite from a text or voice channel.

You must have Permissions.create_instant_invite permission to do this.

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

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

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

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

  • target_type (Optional[InviteTarget]) –

    The type of target for the voice channel invite, if any.

    New in version 2.0.

  • target_user (Optional[User]) –

    The user whose stream to display for this invite, required if target_type is TargetType.stream. The user must be streaming in the channel.

    New in version 2.0.

  • target_application (Optional[PartyType]) –

    The ID of the embedded application for the invite, required if target_type is TargetType.embedded_application.

    New in version 2.0.

  • guild_scheduled_event (Optional[GuildScheduledEvent]) –

    The guild scheduled event to include with the invite.

    New in version 2.3.

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

Raises:
  • HTTPException – Invite creation failed.

  • NotFound – The channel that was passed is a category or an invalid channel.

Returns:

The newly created invite.

Return type:

Invite

property created_at[source]

Returns the channel’s creation time in UTC.

Type:

datetime.datetime

await delete(*, reason=None)[source]

This function is a coroutine.

Deletes the channel.

You must have Permissions.manage_channels permission to do this.

Parameters:

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

Raises:
  • Forbidden – You do not have proper permissions to delete the channel.

  • NotFound – The channel was not found or was already deleted.

  • HTTPException – Deleting the channel failed.

property flags[source]

The channel flags for this channel.

New in version 2.6.

Type:

ChannelFlags

await invites()[source]

This function is a coroutine.

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

You must have Permissions.manage_channels permission to use this.

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

  • HTTPException – An error occurred while fetching the information.

Returns:

The list of invites that are currently active.

Return type:

List[Invite]

property jump_url[source]

A URL that can be used to jump to this channel.

New in version 2.4.

Note

This exists for all guild channels but may not be usable by the client for all guild channel types.

property mention[source]

The string that allows you to mention the channel.

Type:

str

property overwrites[source]

Returns all of the channel’s overwrites.

This is returned as a dictionary where the key contains the target which can be either a Role or a Member and the value is the overwrite as a PermissionOverwrite.

Returns:

The channel’s permission overwrites.

Return type:

Dict[Union[Role, Member], PermissionOverwrite]

overwrites_for(obj)[source]

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

Parameters:

obj (Union[Role, abc.User]) – The role or user denoting whose overwrite to get.

Returns:

The permission overwrites for this object.

Return type:

PermissionOverwrite

permissions_for(obj, /, *, ignore_timeout=...)[source]

Handles permission resolution for the Member or Role.

This function takes into consideration the following cases:

  • Guild owner

  • Guild roles

  • Channel overrides

  • Member overrides

  • Timeouts

If a Role is passed, then it checks the permissions someone with that role would have, which is essentially:

  • The default role permissions

  • The permissions of the role used as a parameter

  • The default role permission overwrites

  • The permission overwrites of the role used as a parameter

Changed in version 2.0: The object passed in can now be a role object.

Parameters:
  • obj (Union[Member, Role]) – The object to resolve permissions for. This could be either a member or a role. If it’s a role then member overwrites are not computed.

  • ignore_timeout (bool) –

    Whether or not to ignore the user’s timeout. Defaults to False.

    New in version 2.4.

    Note

    This only applies to Member objects.

    Changed in version 2.6: The default was changed to False.

Raises:

TypeErrorignore_timeout is only supported for Member objects.

Returns:

The resolved permissions for the member or role.

Return type:

Permissions

property permissions_synced[source]

Whether or not the permissions for this channel are synced with the category it belongs to.

If there is no category then this is False.

New in version 1.3.

Type:

bool

await set_permissions(target, *, overwrite=..., reason=None, **permissions)[source]

This function is a coroutine.

Sets the channel specific permission overwrites for a target in the channel.

The target parameter should either be a Member or a Role that belongs to guild.

The overwrite parameter, if given, must either be None or PermissionOverwrite. For convenience, you can pass in keyword arguments denoting Permissions attributes. If this is done, then you cannot mix the keyword arguments with the overwrite parameter.

If the overwrite parameter is None, then the permission overwrites are deleted.

You must have Permissions.manage_roles permission to do this.

Note

This method replaces the old overwrites with the ones given.

Changed in version 2.6: Raises TypeError instead of InvalidArgument.

Examples

Setting allow and deny:

await message.channel.set_permissions(message.author, view_channel=True,
                                                      send_messages=False)

Deleting overwrites

await channel.set_permissions(member, overwrite=None)

Using PermissionOverwrite

overwrite = disnake.PermissionOverwrite()
overwrite.send_messages = False
overwrite.view_channel = True
await channel.set_permissions(member, overwrite=overwrite)
Parameters:
  • target (Union[Member, Role]) – The member or role to overwrite permissions for.

  • overwrite (Optional[PermissionOverwrite]) – The permissions to allow and deny to the target, or None to delete the overwrite.

  • **permissions – A keyword argument list of permissions to set for ease of use. Cannot be mixed with overwrite.

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

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

  • HTTPException – Editing channel specific permissions failed.

  • NotFound – The role or member being edited is not part of the guild.

  • TypeErroroverwrite is invalid, the target type was not Role or Member, both keyword arguments and overwrite were provided, or invalid permissions were provided as keyword arguments.

DMChannel
class disnake.DMChannel[source]

Represents a Discord direct message channel.

x == y

Checks if two channels are equal.

x != y

Checks if two channels are not equal.

hash(x)

Returns the channel’s hash.

str(x)

Returns a string representation of the channel

recipient

The user you are participating with in the direct message channel. If this channel is received through the gateway, the recipient information may not be always available.

Type:

Optional[User]

me

The user presenting yourself.

Type:

ClientUser

id

The direct message channel ID.

Type:

int

last_pin_timestamp

The time the most recent message was pinned, or None if no message is currently pinned.

New in version 2.5.

Type:

Optional[datetime.datetime]

async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)[source]

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

You must have Permissions.read_message_history permission to use this.

Examples

Usage

counter = 0
async for message in channel.history(limit=200):
    if message.author == client.user:
        counter += 1

Flattening into a list:

messages = await channel.history(limit=123).flatten()
# messages is now a list of Message...

All parameters are optional.

Parameters:
  • limit (Optional[int]) – The number of messages to retrieve. If None, retrieves every message in the channel. Note, however, that this would make it a slow operation.

  • before (Optional[Union[abc.Snowflake, datetime.datetime]]) – Retrieve messages before this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.

  • after (Optional[Union[abc.Snowflake, datetime.datetime]]) – Retrieve messages after this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.

  • around (Optional[Union[abc.Snowflake, datetime.datetime]]) – Retrieve messages around this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time. When using this argument, the maximum limit is 101. Note that if the limit is an even number then this will return at most limit + 1 messages.

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

Raises:
  • Forbidden – You do not have permissions to get channel message history.

  • HTTPException – The request to get message history failed.

Yields:

Message – The message with the message data parsed.

async with typing()[source]

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

This is useful for denoting long computations in your bot.

Note

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

Example Usage:

async with channel.typing():
    # simulate something heavy
    await asyncio.sleep(10)

await channel.send('done!')
property type[source]

The channel’s Discord type.

This always returns ChannelType.private.

Type:

ChannelType

property created_at[source]

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

Type:

datetime.datetime

property jump_url[source]

A URL that can be used to jump to this channel.

New in version 2.4.

property flags[source]

The channel flags for this channel.

New in version 2.6.

Type:

ChannelFlags

permissions_for(obj=None, /, *, ignore_timeout=...)[source]

Handles permission resolution for a User.

This function is there for compatibility with other channel types.

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

This returns all the Permissions.private_channel() permissions set to True.

Parameters:
  • obj (User) – The user to check permissions for. This parameter is ignored but kept for compatibility with other permissions_for methods.

  • ignore_timeout (bool) – Whether to ignore the guild timeout when checking permsisions. This parameter is ignored but kept for compatibility with other permissions_for methods.

Returns:

The resolved permissions.

Return type:

Permissions

get_partial_message(message_id, /)[source]

Creates a PartialMessage from the given message ID.

This is useful if you want to work with a message and only have its ID without doing an unnecessary API call.

New in version 1.6.

Parameters:

message_id (int) – The message ID to create a partial message for.

Returns:

The partial message object.

Return type:

PartialMessage

await fetch_message(id, /)[source]

This function is a coroutine.

Retrieves a single Message from the destination.

Parameters:

id (int) – The message ID to look for.

Raises:
  • NotFound – The specified message was not found.

  • Forbidden – You do not have the permissions required to get a message.

  • HTTPException – Retrieving the message failed.

Returns:

The message asked for.

Return type:

Message

await pins()[source]

This function is a coroutine.

Retrieves all messages that are currently pinned in the channel.

Note

Due to a limitation with the Discord API, the Message objects returned by this method do not contain complete Message.reactions data.

Raises:

HTTPException – Retrieving the pinned messages failed.

Returns:

The messages that are currently pinned.

Return type:

List[Message]

await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, suppress_embeds=False, allowed_mentions=None, reference=None, mention_author=None, view=None, components=None)[source]

This function is a coroutine.

Sends a message to the destination with the content given.

The content must be a type that can convert to a string through str(content).

At least one of content, embed/embeds, file/files, stickers, components, or view must be provided.

To upload a single file, the file parameter should be used with a single File object. To upload multiple files, the files parameter should be used with a list of File objects. Specifying both parameters will lead to an exception.

To upload a single embed, the embed parameter should be used with a single Embed object. To upload multiple embeds, the embeds parameter should be used with a list of Embed objects. Specifying both parameters will lead to an exception.

Changed in version 2.6: Raises TypeError or ValueError instead of InvalidArgument.

Parameters:
  • content (Optional[str]) – The content of the message to send.

  • tts (bool) – Whether the message should be sent using text-to-speech.

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

  • embeds (List[Embed]) –

    A list of embeds to send with the content. Must be a maximum of 10. This cannot be mixed with the embed parameter.

    New in version 2.0.

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

  • files (List[File]) – A list of files to upload. Must be a maximum of 10. This cannot be mixed with the file parameter.

  • stickers (Sequence[Union[GuildSticker, StickerItem]]) –

    A list of stickers to upload. Must be a maximum of 3.

    New in version 2.0.

  • nonce (Union[str, int]) – The nonce to use for sending this message. If the message was successfully sent, then the message will have a nonce with this value.

  • delete_after (float) – If provided, the number of seconds to wait in the background before deleting the message we just sent. If the deletion fails, then it is silently ignored.

  • allowed_mentions (AllowedMentions) –

    Controls the mentions being processed in this message. If this is passed, then the object is merged with Client.allowed_mentions. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set in Client.allowed_mentions. If no object is passed at all then the defaults given by Client.allowed_mentions are used instead.

    New in version 1.4.

  • reference (Union[Message, MessageReference, PartialMessage]) –

    A reference to the Message to which you are replying, this can be created using Message.to_reference() or passed directly as a Message. You can control whether this mentions the author of the referenced message using the AllowedMentions.replied_user attribute of allowed_mentions or by setting mention_author.

    New in version 1.6.

  • mention_author (Optional[bool]) –

    If set, overrides the AllowedMentions.replied_user attribute of allowed_mentions.

    New in version 1.6.

  • view (ui.View) –

    A Discord UI View to add to the message. This cannot be mixed with components.

    New in version 2.0.

  • components (Union[disnake.ui.ActionRow, disnake.ui.WrappedComponent, List[Union[disnake.ui.ActionRow, disnake.ui.WrappedComponent, List[disnake.ui.WrappedComponent]]]]) –

    A list of components to include in the message. This cannot be mixed with view.

    New in version 2.4.

  • suppress_embeds (bool) –

    Whether to suppress embeds for the message. This hides all embeds from the UI if set to True.

    New in version 2.5.

Raises:
Returns:

The message that was sent.

Return type:

Message

await trigger_typing()[source]

This function is a coroutine.

Triggers a typing indicator to the destination.

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

GroupChannel
class disnake.GroupChannel[source]

Represents a Discord group channel.

x == y

Checks if two channels are equal.

x != y

Checks if two channels are not equal.

hash(x)

Returns the channel’s hash.

str(x)

Returns a string representation of the channel

recipients

The users you are participating with in the group channel.

Type:

List[User]

me

The user presenting yourself.

Type:

ClientUser

id

The group channel ID.

Type:

int

owner

The user that owns the group channel.

Type:

Optional[User]

owner_id

The owner ID that owns the group channel.

New in version 2.0.

Type:

int

name

The group channel’s name if provided.

Type:

Optional[str]

async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)[source]

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

You must have Permissions.read_message_history permission to use this.

Examples

Usage

counter = 0
async for message in channel.history(limit=200):
    if message.author == client.user:
        counter += 1

Flattening into a list:

messages = await channel.history(limit=123).flatten()
# messages is now a list of Message...

All parameters are optional.

Parameters:
  • limit (Optional[int]) – The number of messages to retrieve. If None, retrieves every message in the channel. Note, however, that this would make it a slow operation.

  • before (Optional[Union[abc.Snowflake, datetime.datetime]]) – Retrieve messages before this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.

  • after (Optional[Union[abc.Snowflake, datetime.datetime]]) – Retrieve messages after this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.

  • around (Optional[Union[abc.Snowflake, datetime.datetime]]) – Retrieve messages around this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time. When using this argument, the maximum limit is 101. Note that if the limit is an even number then this will return at most limit + 1 messages.

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

Raises:
  • Forbidden – You do not have permissions to get channel message history.

  • HTTPException – The request to get message history failed.

Yields:

Message – The message with the message data parsed.

async with typing()[source]

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

This is useful for denoting long computations in your bot.

Note

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

Example Usage:

async with channel.typing():
    # simulate something heavy
    await asyncio.sleep(10)

await channel.send('done!')
await fetch_message(id, /)[source]

This function is a coroutine.

Retrieves a single Message from the destination.

Parameters:

id (int) – The message ID to look for.

Raises:
  • NotFound – The specified message was not found.

  • Forbidden – You do not have the permissions required to get a message.

  • HTTPException – Retrieving the message failed.

Returns:

The message asked for.

Return type:

Message

await pins()[source]

This function is a coroutine.

Retrieves all messages that are currently pinned in the channel.

Note

Due to a limitation with the Discord API, the Message objects returned by this method do not contain complete Message.reactions data.

Raises:

HTTPException – Retrieving the pinned messages failed.

Returns:

The messages that are currently pinned.

Return type:

List[Message]

await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, suppress_embeds=False, allowed_mentions=None, reference=None, mention_author=None, view=None, components=None)[source]

This function is a coroutine.

Sends a message to the destination with the content given.

The content must be a type that can convert to a string through str(content).

At least one of content, embed/embeds, file/files, stickers, components, or view must be provided.

To upload a single file, the file parameter should be used with a single File object. To upload multiple files, the files parameter should be used with a list of File objects. Specifying both parameters will lead to an exception.

To upload a single embed, the embed parameter should be used with a single Embed object. To upload multiple embeds, the embeds parameter should be used with a list of Embed objects. Specifying both parameters will lead to an exception.

Changed in version 2.6: Raises TypeError or ValueError instead of InvalidArgument.

Parameters:
  • content (Optional[str]) – The content of the message to send.

  • tts (bool) – Whether the message should be sent using text-to-speech.

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

  • embeds (List[Embed]) –

    A list of embeds to send with the content. Must be a maximum of 10. This cannot be mixed with the embed parameter.

    New in version 2.0.

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

  • files (List[File]) – A list of files to upload. Must be a maximum of 10. This cannot be mixed with the file parameter.

  • stickers (Sequence[Union[GuildSticker, StickerItem]]) –

    A list of stickers to upload. Must be a maximum of 3.

    New in version 2.0.

  • nonce (Union[str, int]) – The nonce to use for sending this message. If the message was successfully sent, then the message will have a nonce with this value.

  • delete_after (float) – If provided, the number of seconds to wait in the background before deleting the message we just sent. If the deletion fails, then it is silently ignored.

  • allowed_mentions (AllowedMentions) –

    Controls the mentions being processed in this message. If this is passed, then the object is merged with Client.allowed_mentions. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set in Client.allowed_mentions. If no object is passed at all then the defaults given by Client.allowed_mentions are used instead.

    New in version 1.4.

  • reference (Union[Message, MessageReference, PartialMessage]) –

    A reference to the Message to which you are replying, this can be created using Message.to_reference() or passed directly as a Message. You can control whether this mentions the author of the referenced message using the AllowedMentions.replied_user attribute of allowed_mentions or by setting mention_author.

    New in version 1.6.

  • mention_author (Optional[bool]) –

    If set, overrides the AllowedMentions.replied_user attribute of allowed_mentions.

    New in version 1.6.

  • view (ui.View) –

    A Discord UI View to add to the message. This cannot be mixed with components.

    New in version 2.0.

  • components (Union[disnake.ui.ActionRow, disnake.ui.WrappedComponent, List[Union[disnake.ui.ActionRow, disnake.ui.WrappedComponent, List[disnake.ui.WrappedComponent]]]]) –

    A list of components to include in the message. This cannot be mixed with view.

    New in version 2.4.

  • suppress_embeds (bool) –

    Whether to suppress embeds for the message. This hides all embeds from the UI if set to True.

    New in version 2.5.

Raises:
Returns:

The message that was sent.

Return type:

Message

await trigger_typing()[source]

This function is a coroutine.

Triggers a typing indicator to the destination.

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

property type[source]

The channel’s Discord type.

This always returns ChannelType.group.

Type:

ChannelType

property icon[source]

Returns the channel’s icon asset if available.

Type:

Optional[Asset]

property created_at[source]

Returns the channel’s creation time in UTC.

Type:

datetime.datetime

permissions_for(obj, /, *, ignore_timeout=...)[source]

Handles permission resolution for a User.

This function is there for compatibility with other channel types.

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

This returns all the Permissions.private_channel() permissions set to True.

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

Parameters:
  • obj (Snowflake) – The user to check permissions for.

  • ignore_timeout (bool) – Whether to ignore the guild timeout when checking permsisions. This parameter is ignored but kept for compatibility with other permissions_for methods.

Returns:

The resolved permissions for the user.

Return type:

Permissions

await leave()[source]

This function is a coroutine.

Leaves the group.

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

Raises:

HTTPException – Leaving the group failed.

PartialInviteGuild
class disnake.PartialInviteGuild[source]

Represents a “partial” invite guild.

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

x == y

Checks if two partial guilds are the same.

x != y

Checks if two partial guilds are not the same.

hash(x)

Return the partial guild’s hash.

str(x)

Returns the partial guild’s name.

name

The partial guild’s name.

Type:

str

id

The partial guild’s ID.

Type:

int

description

The partial guild’s description.

Type:

Optional[str]

features

A list of features the partial guild has. See Guild.features for more information.

Type:

List[str]

nsfw_level

The partial guild’s nsfw level.

New in version 2.4.

Type:

NSFWLevel

vanity_url_code

The partial guild’s vanity url code, if any.

New in version 2.4.

Type:

Optional[str]

verification_level

The partial guild’s verification level.

Type:

VerificationLevel

premium_subscription_count

The number of “boosts” this guild currently has.

New in version 2.5.

Type:

int

property created_at[source]

Returns the guild’s creation time in UTC.

Type:

datetime.datetime

property icon[source]

Returns the guild’s icon asset, if available.

Type:

Optional[Asset]

property banner[source]

Returns the guild’s banner asset, if available.

Type:

Optional[Asset]

property splash[source]

Returns the guild’s invite splash asset, if available.

Type:

Optional[Asset]

PartialInviteChannel
class disnake.PartialInviteChannel[source]

Represents a “partial” invite channel.

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

x == y

Checks if two partial channels are the same.

x != y

Checks if two partial channels are not the same.

hash(x)

Return the partial channel’s hash.

str(x)

Returns the partial channel’s name.

Changed in version 2.5: if the channel is of type ChannelType.group, returns the name that’s rendered by the official client.

name

The partial channel’s name.

Type:

Optional[str]

id

The partial channel’s ID.

Type:

int

type

The partial channel’s type.

Type:

ChannelType

property mention[source]

The string that allows you to mention the channel.

Type:

str

property created_at[source]

Returns the channel’s creation time in UTC.

Type:

datetime.datetime

property icon[source]

Returns the channel’s icon asset if available.

New in version 2.6.

Type:

Optional[Asset]

Invite
class disnake.Invite[source]

Represents a Discord Guild or abc.GuildChannel invite.

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

x == y

Checks if two invites are equal.

x != y

Checks if two invites are not equal.

hash(x)

Returns the invite hash.

str(x)

Returns the invite URL.

The following table illustrates what methods will obtain the attributes:

If it’s not in the table above then it is available by all methods.

max_age

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

Type:

int

code

The URL fragment used for the invite.

Type:

str

guild

The guild the invite is for. Can be None if it’s from a group direct message.

Type:

Optional[Union[Guild, Object, PartialInviteGuild]]

created_at

An aware UTC datetime object denoting the time the invite was created.

Type:

datetime.datetime

temporary

Whether the invite grants temporary membership. If True, members who joined via this invite will be kicked upon disconnect.

Type:

bool

uses

How many times the invite has been used.

Type:

int

max_uses

How many times the invite can be used. A value of 0 indicates that it has unlimited uses.

Type:

int

inviter

The user who created the invite.

Type:

Optional[User]

approximate_member_count

The approximate number of members in the guild.

Type:

Optional[int]

approximate_presence_count

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

Type:

Optional[int]

expires_at

The expiration date of the invite. If the value is None when received through Client.fetch_invite with with_expiration enabled, the invite will never expire.

New in version 2.0.

Type:

Optional[datetime.datetime]

channel

The channel the invite is for.

Type:

Optional[Union[abc.GuildChannel, Object, PartialInviteChannel]]

target_type

The type of target for the voice channel invite.

New in version 2.0.

Type:

InviteTarget

target_user

The user whose stream to display for this invite, if any.

New in version 2.0.

Type:

Optional[User]

target_application

The embedded application the invite targets, if any.

New in version 2.0.

Type:

Optional[PartialAppInfo]

guild_scheduled_event

The guild scheduled event included in the invite, if any.

New in version 2.3.

Type:

Optional[GuildScheduledEvent]

guild_welcome_screen

The partial guild’s welcome screen, if any.

New in version 2.5.

Type:

Optional[WelcomeScreen]

property id[source]

Returns the proper code portion of the invite.

Type:

str

property url[source]

A property that retrieves the invite URL.

Type:

str

await delete(*, reason=None)[source]

This function is a coroutine.

Revokes the instant invite.

You must have manage_channels permission to do this.

Parameters:

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

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

  • NotFound – The invite is invalid or expired.

  • HTTPException – Revoking the invite failed.

Template
class disnake.Template[source]

Represents a Discord template.

New in version 1.4.

code

The template code.

Type:

str

uses

How many times the template has been used.

Type:

int

name

The name of the template.

Type:

str

description

The description of the template.

Type:

str

creator

The creator of the template.

Type:

User

created_at

An aware datetime in UTC representing when the template was created.

Type:

datetime.datetime

updated_at

An aware datetime in UTC representing when the template was last updated. This is referred to as “last synced” in the official Discord client.

Type:

datetime.datetime

source_guild

The source guild.

Type:

Guild

is_dirty

Whether the template has unsynced changes.

New in version 2.0.

Type:

Optional[bool]

await create_guild(name, icon=None)[source]

This function is a coroutine.

Creates a Guild using the template.

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

Changed in version 2.5: Removed the region parameter.

Changed in version 2.6: Raises ValueError instead of InvalidArgument.

Parameters:
Raises:
Returns:

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

Return type:

Guild

await sync()[source]

This function is a coroutine.

Syncs the template to the guild’s current state.

You must have the manage_guild permission in the source guild to do this.

New in version 1.7.

Changed in version 2.0: The template is no longer edited in-place, instead it is returned.

Raises:
  • HTTPException – Editing the template failed.

  • Forbidden – You don’t have permissions to edit the template.

  • NotFound – This template does not exist.

Returns:

The newly edited template.

Return type:

Template

await edit(*, name=..., description=...)[source]

This function is a coroutine.

Edits the template metadata.

You must have the manage_guild permission in the source guild to do this.

New in version 1.7.

Changed in version 2.0: The template is no longer edited in-place, instead it is returned.

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

  • description (Optional[str]) – The template’s new description.

Raises:
  • HTTPException – Editing the template failed.

  • Forbidden – You don’t have permissions to edit the template.

  • NotFound – This template does not exist.

Returns:

The newly edited template.

Return type:

Template

await delete()[source]

This function is a coroutine.

Deletes the template.

You must have the manage_guild permission in the source guild to do this.

New in version 1.7.

Raises:
  • HTTPException – Editing the template failed.

  • Forbidden – You don’t have permissions to edit the template.

  • NotFound – This template does not exist.

property url[source]

The template url.

New in version 2.0.

Type:

str

WidgetChannel
class disnake.WidgetChannel[source]

Represents a “partial” widget channel.

x == y

Checks if two partial channels are the same.

x != y

Checks if two partial channels are not the same.

hash(x)

Return the partial channel’s hash.

str(x)

Returns the partial channel’s name.

id

The channel’s ID.

Type:

int

name

The channel’s name.

Type:

str

position

The channel’s position

Type:

int

property mention[source]

The string that allows you to mention the channel.

Type:

str

property created_at[source]

Returns the channel’s creation time in UTC.

Type:

datetime.datetime

WidgetMember
class disnake.WidgetMember[source]

Represents a “partial” member of the widget’s guild.

x == y

Checks if two widget members are the same.

x != y

Checks if two widget members are not the same.

hash(x)

Return the widget member’s hash.

str(x)

Returns the widget member’s name#discriminator.

id

The member’s anonymized ID.

Type:

int

name

The member’s nickname (if set in the guild) or username.

Type:

str

discriminator

The member’s anonymized discriminator.

Type:

str

status

The member’s status.

Type:

Status

activity

The member’s activity. This generally only has the name set.

Type:

Optional[Union[BaseActivity, Spotify]]

deafened

Whether the member is currently deafened.

Type:

Optional[bool]

muted

Whether the member is currently muted.

Type:

Optional[bool]

suppress

Whether the member is currently being suppressed.

Type:

Optional[bool]

connected_channel

Which channel the member is connected to.

Type:

Optional[WidgetChannel]

property avatar[source]

The user’s avatar. The size can be chosen using Asset.with_size(), however the format is always static and cannot be changed through Asset.with_format() or similar methods.

Type:

Optional[Asset]

property display_name[source]

Returns the member’s name.

Type:

str

property display_avatar[source]

Returns the user’s display avatar.

For regular users this is just their default avatar or uploaded avatar.

New in version 2.0.

Type:

Asset

WidgetSettings
Methods
class disnake.WidgetSettings[source]

Represents a Guild’s widget settings.

New in version 2.5.

guild

The widget’s guild.

Type:

Guild

enabled

Whether the widget is enabled.

Type:

bool

channel_id

The widget channel ID. If set, an invite link for this channel will be generated, which allows users to join the guild from the widget.

Type:

Optional[int]

property channel[source]

The widget channel, if set.

Type:

Optional[abc.GuildChannel]

await edit(*, enabled=..., channel=..., reason=None)[source]

This function is a coroutine.

Edits the widget.

You must have manage_guild permission to do this.

Parameters:
  • enabled (bool) – Whether to enable the widget.

  • channel (Optional[Snowflake]) – The new widget channel. Pass None to remove the widget channel. If set, an invite link for this channel will be generated, which allows users to join the guild from the widget.

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

Raises:
Returns:

The new widget settings.

Return type:

WidgetSettings

Widget
class disnake.Widget[source]

Represents a Guild widget.

x == y

Checks if two widgets are the same.

x != y

Checks if two widgets are not the same.

str(x)

Returns the widget’s JSON URL.

id

The guild’s ID.

Type:

int

name

The guild’s name.

Type:

str

channels

The publicly accessible voice and stage channels in the guild.

Type:

List[WidgetChannel]

members

The online members in the server. Offline members do not appear in the widget.

Note

Due to a Discord limitation, if this data is available the users will be “anonymized” with linear IDs and discriminator information being incorrect. Likewise, the number of members retrieved is capped.

Type:

List[WidgetMember]

presence_count

The number of online members in the server.

New in version 2.6.

Type:

int

property created_at[source]

Returns the member’s creation time in UTC.

Type:

datetime.datetime

property json_url[source]

The JSON URL of the widget.

Type:

str

property invite_url[source]

The invite URL for the guild, if available.

Type:

Optional[str]

await fetch_invite(*, with_counts=True)[source]

This function is a coroutine.

Retrieves an Invite from the widget’s invite URL. This is the same as Client.fetch_invite(); the invite code is abstracted away.

Changed in version 2.6: This may now return None if the widget does not have an attached invite URL.

Parameters:

with_counts (bool) – Whether to include count information in the invite. This fills the Invite.approximate_member_count and Invite.approximate_presence_count fields.

Returns:

The invite from the widget’s invite URL, if available.

Return type:

Optional[Invite]

await edit(*, enabled=..., channel=..., reason=None)[source]

This function is a coroutine.

Edits the widget.

You must have manage_guild permission to do this

New in version 2.4.

Parameters:
  • enabled (bool) – Whether to enable the widget.

  • channel (Optional[Snowflake]) – The new widget channel. Pass None to remove the widget channel.

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

Raises:
image_url(style=<WidgetStyle.shield: 'shield'>)[source]

Returns an URL to the widget’s .png image.

New in version 2.5.

Parameters:

style (WidgetStyle) – The widget style.

Returns:

The widget image URL.

Return type:

str

WelcomeScreen
Methods
class disnake.WelcomeScreen[source]

Represents a Discord welcome screen for a Guild.

New in version 2.5.

description

The guild description in the welcome screen.

Type:

Optional[str]

channels

The welcome screen’s channels.

Type:

List[WelcomeScreenChannel]

property enabled[source]

Whether the welcome screen is displayed to users. This is equivalent to checking if WELCOME_SCREEN_ENABLED is present in Guild.features.

Type:

bool

await edit(*, enabled=..., description=..., channels=..., reason=None)[source]

This function is a coroutine.

Edits the welcome screen.

You must have the manage_guild permission to use this.

This requires ‘COMMUNITY’ in Guild.features.

Parameters:
  • enabled (bool) – Whether the welcome screen is enabled.

  • description (Optional[str]) – The new guild description in the welcome screen.

  • channels (Optional[List[WelcomeScreenChannel]]) – The new welcome channels.

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

Raises:
Returns:

The newly edited welcome screen.

Return type:

WelcomeScreen

WelcomeScreenChannel
Attributes
class disnake.WelcomeScreenChannel[source]

Represents a Discord welcome screen channel.

New in version 2.5.

id

The ID of the guild channel this welcome screen channel represents.

Type:

int

description

The description of this channel in the official UI.

Type:

str

emoji

The emoji associated with this channel’s welcome message, if any.

Type:

Optional[Union[Emoji, PartialEmoji]]

VoiceRegion
class disnake.VoiceRegion[source]

Represents a Discord voice region.

New in version 2.5.

id

Unique ID for the region.

Type:

str

name

The name of the region.

Type:

str

optimal

True for a single region that is closest to your client.

Type:

bool

deprecated

Whether this is a deprecated voice region (avoid switching to these).

Type:

bool

custom

Whether this is a custom voice region (used for events/etc)

Type:

bool

StickerPack
class disnake.StickerPack[source]

Represents a sticker pack.

New in version 2.0.

str(x)

Returns the name of the sticker pack.

x == y

Checks if the sticker pack is equal to another sticker pack.

x != y

Checks if the sticker pack is not equal to another sticker pack.

name

The name of the sticker pack.

Type:

str

description

The description of the sticker pack.

Type:

str

id

The id of the sticker pack.

Type:

int

stickers

The stickers of this sticker pack.

Type:

List[StandardSticker]

sku_id

The SKU ID of the sticker pack.

Type:

int

cover_sticker_id

The ID of the sticker used for the cover of the sticker pack.

Type:

int

cover_sticker

The sticker used for the cover of the sticker pack.

Type:

StandardSticker

property banner[source]

The banner asset of the sticker pack.

Type:

Asset

StickerItem
Attributes
Methods
class disnake.StickerItem[source]

Represents a sticker item.

New in version 2.0.

str(x)

Returns the name of the sticker item.

x == y

Checks if the sticker item is equal to another sticker item.

x != y

Checks if the sticker item is not equal to another sticker item.

name

The sticker’s name.

Type:

str

id

The ID of the sticker.

Type:

int

format

The format for the sticker’s image.

Type:

StickerFormatType

await fetch()[source]

This function is a coroutine.

Attempts to retrieve the full sticker data of the sticker item.

Raises:

HTTPException – Retrieving the sticker failed.

Returns:

The retrieved sticker.

Return type:

Union[StandardSticker, GuildSticker]

await read()[source]

This function is a coroutine.

Retrieves the content of this sticker as a bytes object.

Note

Stickers that use the StickerFormatType.lottie format cannot be read.

Raises:
Returns:

The content of the asset.

Return type:

bytes

await save(fp, *, seek_begin=True)[source]

This function is a coroutine.

Saves this asset into a file-like object.

Parameters:
  • fp (Union[io.BufferedIOBase, os.PathLike]) – The file-like object to save this asset to or the filename to use. If a filename is passed then a file is created with that filename and used instead.

  • seek_begin (bool) – Whether to seek to the beginning of the file after saving is successfully done.

Raises:
Returns:

The number of bytes written.

Return type:

int

await to_file(*, spoiler=False, filename=None, description=None)[source]

This function is a coroutine.

Converts the asset into a File suitable for sending via abc.Messageable.send().

New in version 2.5.

Changed in version 2.6: Raises TypeError instead of InvalidArgument.

Parameters:
  • spoiler (bool) – Whether the file is a spoiler.

  • filename (Optional[str]) – The filename to display when uploading to Discord. If this is not given, it defaults to the name of the asset’s URL.

  • description (Optional[str]) – The file’s description.

Raises:
Returns:

The asset as a file suitable for sending.

Return type:

File

property url[source]

The url for the sticker’s image.

Type:

str

Sticker
Methods
class disnake.Sticker[source]

Represents a sticker.

New in version 1.6.

str(x)

Returns the name of the sticker.

x == y

Checks if the sticker is equal to another sticker.

x != y

Checks if the sticker is not equal to another sticker.

name

The sticker’s name.

Type:

str

id

The ID of the sticker.

Type:

int

description

The description of the sticker.

Type:

str

pack_id

The ID of the sticker’s pack.

Type:

int

format

The format for the sticker’s image.

Type:

StickerFormatType

property created_at[source]

Returns the sticker’s creation time in UTC.

Type:

datetime.datetime

await read()[source]

This function is a coroutine.

Retrieves the content of this sticker as a bytes object.

Note

Stickers that use the StickerFormatType.lottie format cannot be read.

Raises:
Returns:

The content of the asset.

Return type:

bytes

await save(fp, *, seek_begin=True)[source]

This function is a coroutine.

Saves this asset into a file-like object.

Parameters:
  • fp (Union[io.BufferedIOBase, os.PathLike]) – The file-like object to save this asset to or the filename to use. If a filename is passed then a file is created with that filename and used instead.

  • seek_begin (bool) – Whether to seek to the beginning of the file after saving is successfully done.

Raises:
Returns:

The number of bytes written.

Return type:

int

await to_file(*, spoiler=False, filename=None, description=None)[source]

This function is a coroutine.

Converts the asset into a File suitable for sending via abc.Messageable.send().

New in version 2.5.

Changed in version 2.6: Raises TypeError instead of InvalidArgument.

Parameters:
  • spoiler (bool) – Whether the file is a spoiler.

  • filename (Optional[str]) – The filename to display when uploading to Discord. If this is not given, it defaults to the name of the asset’s URL.

  • description (Optional[str]) – The file’s description.

Raises:
Returns:

The asset as a file suitable for sending.

Return type:

File

property url[source]

The url for the sticker’s image.

Type:

str

StandardSticker
Methods
class disnake.StandardSticker[source]

Represents a sticker that is found in a standard sticker pack.

New in version 2.0.

str(x)

Returns the name of the sticker.

x == y

Checks if the sticker is equal to another sticker.

x != y

Checks if the sticker is not equal to another sticker.

name

The sticker’s name.

Type:

str

id

The ID of the sticker.

Type:

int

description

The description of the sticker.

Type:

str

pack_id

The ID of the sticker’s pack.

Type:

int

format

The format for the sticker’s image.

Type:

StickerFormatType

tags

A list of tags for the sticker.

Type:

List[str]

sort_value

The sticker’s sort order within its pack.

Type:

int

await pack()[source]

This function is a coroutine.

Retrieves the sticker pack that this sticker belongs to.

Raises:
Returns:

The retrieved sticker pack.

Return type:

StickerPack

property created_at[source]

Returns the sticker’s creation time in UTC.

Type:

datetime.datetime

await read()[source]

This function is a coroutine.

Retrieves the content of this sticker as a bytes object.

Note

Stickers that use the StickerFormatType.lottie format cannot be read.

Raises:
Returns:

The content of the asset.

Return type:

bytes

await save(fp, *, seek_begin=True)[source]

This function is a coroutine.

Saves this asset into a file-like object.

Parameters:
  • fp (Union[io.BufferedIOBase, os.PathLike]) – The file-like object to save this asset to or the filename to use. If a filename is passed then a file is created with that filename and used instead.

  • seek_begin (bool) – Whether to seek to the beginning of the file after saving is successfully done.

Raises:
Returns:

The number of bytes written.

Return type:

int

await to_file(*, spoiler=False, filename=None, description=None)[source]

This function is a coroutine.

Converts the asset into a File suitable for sending via abc.Messageable.send().

New in version 2.5.

Changed in version 2.6: Raises TypeError instead of InvalidArgument.

Parameters:
  • spoiler (bool) – Whether the file is a spoiler.

  • filename (Optional[str]) – The filename to display when uploading to Discord. If this is not given, it defaults to the name of the asset’s URL.

  • description (Optional[str]) – The file’s description.

Raises:
Returns:

The asset as a file suitable for sending.

Return type:

File

property url[source]

The url for the sticker’s image.

Type:

str

GuildSticker
class disnake.GuildSticker[source]

Represents a sticker that belongs to a guild.

New in version 2.0.

str(x)

Returns the name of the sticker.

x == y

Checks if the sticker is equal to another sticker.

x != y

Checks if the sticker is not equal to another sticker.

name

The sticker’s name.

Type:

str

id

The ID of the sticker.

Type:

int

description

The description of the sticker.

Type:

str

format

The format for the sticker’s image.

Type:

StickerFormatType

available

Whether this sticker is available for use.

Type:

bool

guild_id

The ID of the guild that this sticker is from.

Type:

int

user

The user that created this sticker. This can only be retrieved using Guild.fetch_sticker() and having the manage_emojis_and_stickers permission.

Type:

Optional[User]

emoji

The name of a unicode emoji that represents this sticker.

Type:

str

guild

The guild that this sticker is from. Could be None if the bot is not in the guild.

New in version 2.0.

Type:

Optional[Guild]

await edit(*, name=..., description=..., emoji=..., reason=None)[source]

This function is a coroutine.

Edits a GuildSticker for the guild.

Parameters:
  • name (str) – The sticker’s new name. Must be at least 2 characters.

  • description (Optional[str]) – The sticker’s new description. Can be None.

  • emoji (str) – The name of a unicode emoji that represents the sticker’s expression.

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

Raises:
  • Forbidden – You are not allowed to edit stickers.

  • HTTPException – An error occurred editing the sticker.

Returns:

The newly modified sticker.

Return type:

GuildSticker

await delete(*, reason=None)[source]

This function is a coroutine.

Deletes the custom Sticker from the guild.

You must have manage_emojis_and_stickers permission to do this.

Parameters:

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

Raises:
  • Forbidden – You are not allowed to delete stickers.

  • HTTPException – An error occurred deleting the sticker.

property created_at[source]

Returns the sticker’s creation time in UTC.

Type:

datetime.datetime

await read()[source]

This function is a coroutine.

Retrieves the content of this sticker as a bytes object.

Note

Stickers that use the StickerFormatType.lottie format cannot be read.

Raises:
Returns:

The content of the asset.

Return type:

bytes

await save(fp, *, seek_begin=True)[source]

This function is a coroutine.

Saves this asset into a file-like object.

Parameters:
  • fp (Union[io.BufferedIOBase, os.PathLike]) – The file-like object to save this asset to or the filename to use. If a filename is passed then a file is created with that filename and used instead.

  • seek_begin (bool) – Whether to seek to the beginning of the file after saving is successfully done.

Raises:
Returns:

The number of bytes written.

Return type:

int

await to_file(*, spoiler=False, filename=None, description=None)[source]

This function is a coroutine.

Converts the asset into a File suitable for sending via abc.Messageable.send().

New in version 2.5.

Changed in version 2.6: Raises TypeError instead of InvalidArgument.

Parameters:
  • spoiler (bool) – Whether the file is a spoiler.

  • filename (Optional[str]) – The filename to display when uploading to Discord. If this is not given, it defaults to the name of the asset’s URL.

  • description (Optional[str]) – The file’s description.

Raises:
Returns:

The asset as a file suitable for sending.

Return type:

File

property url[source]

The url for the sticker’s image.

Type:

str

AutoModRule
class disnake.AutoModRule[source]

Represents an auto moderation rule.

New in version 2.6.

id

The rule ID.

Type:

int

name

The rule name.

Type:

str

enabled

Whether this rule is enabled.

Type:

bool

guild

The guild of the rule.

Type:

Guild

creator_id

The rule creator’s ID. See also creator.

Type:

int

event_type

The event type this rule is applied to.

Type:

AutoModEventType

trigger_type

The type of trigger that determines whether this rule’s actions should run for a specific event.

Type:

AutoModTriggerType

trigger_metadata

Additional metadata associated with this rule’s trigger_type.

Type:

AutoModTriggerMetadata

exempt_role_ids

The role IDs that are exempt from this rule.

Type:

FrozenSet[int]

exempt_channel_ids

The channel IDs that are exempt from this rule.

Type:

FrozenSet[int]

property actions[source]

List[Union[AutoModBlockMessageAction, AutoModSendAlertAction, AutoModTimeoutAction, AutoModAction]]: The list of actions that will execute if a matching event triggered this rule.

property creator[source]

The guild member that created this rule. May be None if the member cannot be found. See also creator_id.

Type:

Optional[Member]

property exempt_roles[source]

The list of roles that are exempt from this rule.

Type:

List[Role]

property exempt_channels[source]

The list of channels that are exempt from this rule.

Type:

List[abc.GuildChannel]

await edit(*, name=..., event_type=..., trigger_metadata=..., actions=..., enabled=..., exempt_roles=..., exempt_channels=..., reason=None)[source]

This function is a coroutine.

Edits the auto moderation rule.

You must have Permissions.manage_guild permission to do this.

All fields are optional.

Examples

Edit name and enable rule:

await rule.edit(name="cool new rule", enabled=True)

Add an action:

await rule.edit(
    actions=rule.actions + [AutoModTimeoutAction(3600)],
)

Add a keyword to a keyword filter rule:

meta = rule.trigger_metadata
await rule.edit(
    trigger_metadata=meta.with_edits(
        keyword_filter=meta.keyword_filter + ["stuff"],
    ),
)
Parameters:
  • name (str) – The rule’s new name.

  • event_type (AutoModEventType) – The rule’s new event type.

  • trigger_metadata (AutoModTriggerMetadata) – The rule’s new associated trigger metadata.

  • actions (Sequence[Union[AutoModBlockMessageAction, AutoModSendAlertAction, AutoModTimeoutAction, AutoModAction]]) – The rule’s new actions. If provided, must contain at least one action.

  • enabled (bool) – Whether to enable the rule.

  • exempt_roles (Optional[Iterable[abc.Snowflake]]) – The rule’s new exempt roles, up to 20. If [] or None is passed then all role exemptions are removed.

  • exempt_channels (Optional[Iterable[abc.Snowflake]]) – The rule’s new exempt channels, up to 50. Can also include categories, in which case all channels inside that category will be exempt. If [] or None is passed then all channel exemptions are removed.

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

Raises:
  • ValueError – When editing the list of actions, at least one action must be provided.

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

  • NotFound – The rule does not exist.

  • HTTPException – Editing the rule failed.

Returns:

The newly updated auto moderation rule.

Return type:

AutoModRule

await delete(*, reason=None)[source]

This function is a coroutine.

Deletes the auto moderation rule.

You must have Permissions.manage_guild permission to do this.

Parameters:

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

Raises:
  • Forbidden – You do not have proper permissions to delete the rule.

  • NotFound – The rule does not exist.

  • HTTPException – Deleting the rule failed.

AutoModActionExecution
class disnake.AutoModActionExecution[source]

Represents the data for an on_automod_action_execution() event.

New in version 2.6.

action

The action that was executed.

Type:

Union[AutoModBlockMessageAction, AutoModSendAlertAction, AutoModTimeoutAction, AutoModAction]

guild

The guild this action was executed in.

Type:

Guild

rule_id

The ID of the rule that matched.

Type:

int

rule_trigger_type

The trigger type of the rule that matched.

Type:

AutoModTriggerType

user_id

The ID of the user that triggered this action. See also user.

Type:

int

channel_id

The channel or thread ID in which the event occurred, if any. See also channel.

Type:

Optional[int]

message_id

The ID of the message that matched. None if the message was blocked, or if the content was not part of a message. See also message.

Type:

Optional[int]

alert_message_id

The ID of the alert message sent as a result of this action, if any. See also alert_message.

Type:

Optional[int]

content

The content that matched.

Requires Intents.message_content to be enabled, otherwise this field will be empty.

Type:

str

matched_keyword

The keyword that matched.

Type:

Optional[str]

matched_content

The substring of content that matched the rule/keyword.

Requires Intents.message_content to be enabled, otherwise this field will be empty.

Type:

Optional[str]

property user[source]

The guild member that triggered this action. May be None if the member cannot be found. See also user_id.

Type:

Optional[Member]

property channel[source]

Optional[Union[abc.GuildChannel, Thread]]: The channel or thread in which the event occurred, if any.

property message[source]

The message that matched, if any. Not available if the message was blocked, if the content was not part of a message, or if the message was not found in the message cache.

Type:

Optional[Message]

property alert_message[source]

The alert message sent as a result of this action, if any. Only available if action.type is send_alert_message and the message was found in the message cache.

Type:

Optional[Message]

RawMessageDeleteEvent
class disnake.RawMessageDeleteEvent[source]

Represents the event payload for an on_raw_message_delete() event.

channel_id

The channel ID where the deletion took place.

Type:

int

guild_id

The guild ID where the deletion took place, if applicable.

Type:

Optional[int]

message_id

The message ID that got deleted.

Type:

int

cached_message

The cached message, if found in the internal message cache.

Type:

Optional[Message]

RawBulkMessageDeleteEvent
class disnake.RawBulkMessageDeleteEvent[source]

Represents the event payload for an on_raw_bulk_message_delete() event.

message_ids

A set of the message IDs that were deleted.

Type:

Set[int]

channel_id

The channel ID where the deletion took place.

Type:

int

guild_id

The guild ID where the deletion took place, if applicable.

Type:

Optional[int]

cached_messages

The cached messages, if found in the internal message cache.

Type:

List[Message]

RawMessageUpdateEvent
class disnake.RawMessageUpdateEvent[source]

Represents the event payload for an on_raw_message_edit() event.

message_id

The message ID that got updated.

Type:

int

channel_id

The channel ID where the update took place.

New in version 1.3.

Type:

int

guild_id

The guild ID where the update took place, if applicable.

New in version 1.7.

Type:

Optional[int]

data

The raw data given by the gateway

Type:

dict

cached_message

The cached message, if found in the internal message cache. Represents the message before it is modified by the data in RawMessageUpdateEvent.data.

Type:

Optional[Message]

RawReactionActionEvent
class disnake.RawReactionActionEvent[source]

Represents the event payload for on_raw_reaction_add() and on_raw_reaction_remove() events.

message_id

The message ID that got or lost a reaction.

Type:

int

user_id

The user ID who added the reaction or whose reaction was removed.

Type:

int

channel_id

The channel ID where the reaction addition or removal took place.

Type:

int

guild_id

The guild ID where the reaction addition or removal took place, if applicable.

Type:

Optional[int]

emoji

The custom or unicode emoji being used.

Type:

PartialEmoji

member

The member who added the reaction. Only available if event_type is REACTION_ADD and the reaction is inside a guild.

New in version 1.3.

Type:

Optional[Member]

event_type

The event type that triggered this action. Can be REACTION_ADD for reaction addition or REACTION_REMOVE for reaction removal.

New in version 1.3.

Type:

str

RawReactionClearEvent
class disnake.RawReactionClearEvent[source]

Represents the event payload for an on_raw_reaction_clear() event.

message_id

The message ID that got its reactions cleared.

Type:

int

channel_id

The channel ID where the reaction clear took place.

Type:

int

guild_id

The guild ID where the reaction clear took place, if applicable.

Type:

Optional[int]

RawReactionClearEmojiEvent
class disnake.RawReactionClearEmojiEvent[source]

Represents the event payload for an on_raw_reaction_clear_emoji() event.

New in version 1.3.

message_id

The message ID that got its reactions cleared.

Type:

int

channel_id

The channel ID where the reaction clear took place.

Type:

int

guild_id

The guild ID where the reaction clear took place, if applicable.

Type:

Optional[int]

emoji

The custom or unicode emoji being removed.

Type:

PartialEmoji

RawIntegrationDeleteEvent
class disnake.RawIntegrationDeleteEvent[source]

Represents the event payload for an on_raw_integration_delete() event.

New in version 2.0.

integration_id

The ID of the integration that got deleted.

Type:

int

application_id

The ID of the bot/OAuth2 application for this deleted integration.

Type:

Optional[int]

guild_id

The guild ID where the integration deletion took place.

Type:

int

RawGuildScheduledEventUserActionEvent
class disnake.RawGuildScheduledEventUserActionEvent[source]

Represents the event payload for an on_raw_guild_scheduled_event_subscribe() and on_raw_guild_scheduled_event_unsubscribe() events.

New in version 2.3.

event_id

The ID of the guild scheduled event that the user subscribed to or unsubscribed from.

Type:

int

user_id

The ID of the user doing the action.

Type:

int

guild_id

The guild ID where the guild scheduled event is located.

Type:

int

RawThreadDeleteEvent
class disnake.RawThreadDeleteEvent[source]

Represents the payload for a on_raw_thread_delete() event.

New in version 2.5.

thread_id

The ID of the thread that was deleted.

Type:

int

guild_id

The ID of the guild the thread was deleted in.

Type:

int

thread_type

The type of the deleted thread.

Type:

ChannelType

parent_id

The ID of the channel the thread belonged to.

Type:

int

thread

The thread, if it could be found in the internal cache.

Type:

Optional[Thread]

RawThreadMemberRemoveEvent
class disnake.RawThreadMemberRemoveEvent[source]

Represents the event payload for an on_raw_thread_member_remove() event.

New in version 2.5.

thread

The Thread that the member was removed from

Type:

Thread

member_id

The ID of the removed member.

Type:

int

cached_member

The member, if they could be found in the internal cache.

Type:

Optional[ThreadMember]

RawTypingEvent
class disnake.RawTypingEvent[source]

Represents the event payload for an on_raw_typing() event.

New in version 2.3.

user_id

The ID of the user who started typing.

Type:

int

channel_id

The ID of the channel where the user started typing.

Type:

int

guild_id

The ID of the guild where the user started typing or None if it was in a DM.

Type:

Optional[int]

member

The member object of the user who started typing or None if it was in a DM.

Type:

Optional[Member]

timestamp

The UTC datetime when the user started typing.

Type:

datetime.datetime

RawGuildMemberRemoveEvent
Attributes
class disnake.RawGuildMemberRemoveEvent[source]

Represents the event payload for an on_raw_member_remove() event.

New in version 2.6.

guild_id

The ID of the guild where the member was removed from.

Type:

int

user

The user object of the member that was removed.

Type:

Union[User, Member]

PartialWebhookGuild
Attributes
class disnake.PartialWebhookGuild[source]

Represents a partial guild for webhooks.

These are typically given for channel follower webhooks.

New in version 2.0.

id

The partial guild’s ID.

Type:

int

name

The partial guild’s name.

Type:

str

property icon[source]

Returns the guild’s icon asset, if available.

Type:

Optional[Asset]

PartialWebhookChannel
Attributes
class disnake.PartialWebhookChannel[source]

Represents a partial channel for webhooks.

These are typically given for channel follower webhooks.

New in version 2.0.

id

The partial channel’s ID.

Type:

int

name

The partial channel’s name.

Type:

str

Data Classes

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

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

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

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

Object
Attributes
class disnake.Object(id)[source]

Represents a generic Discord object.

The purpose of this class is to allow you to create ‘miniature’ versions of data classes if you want to pass in just an ID. Most functions that take in a specific data class with an ID can also take in this class as a substitute instead. Note that even though this is the case, not all objects (if any) actually inherit from this class.

There are also some cases where some websocket events are received in strange order and when such events happened you would receive this class rather than the actual data class. These cases are extremely rare.

x == y

Checks if two objects are equal.

x != y

Checks if two objects are not equal.

hash(x)

Returns the object’s hash.

id

The ID of the object.

Type:

int

property created_at[source]

Returns the snowflake’s creation time in UTC.

Type:

datetime.datetime

Embed
class disnake.Embed(*, title=None, type='rich', description=None, url=None, timestamp=None, colour=..., color=...)[source]

Represents a Discord embed.

x == y

Checks if two embeds are equal.

New in version 2.6.

x != y

Checks if two embeds are not equal.

New in version 2.6.

len(x)

Returns the total size of the embed. Useful for checking if it’s within the 6000 character limit. Check if all aspects of the embed are within the limits with Embed.check_limits().

bool(b)

Returns whether the embed has any data set.

New in version 2.0.

Certain properties return an EmbedProxy, a type that acts similar to a regular dict except using dotted access, e.g. embed.author.icon_url.

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

title

The title of the embed.

Type:

Optional[str]

type

The type of embed. Usually “rich”. Possible strings for embed types can be found on Discord’s api docs.

Type:

Optional[str]

description

The description of the embed.

Type:

Optional[str]

url

The URL of the embed.

Type:

Optional[str]

timestamp[source]

The timestamp of the embed content. This is an aware datetime. If a naive datetime is passed, it is converted to an aware datetime with the local timezone.

Type:

Optional[datetime.datetime]

colour[source]

The colour code of the embed. Aliased to color as well. In addition to Colour, int can also be assigned to it, in which case the value will be converted to a Colour object.

Type:

Optional[Colour]

classmethod from_dict(data)[source]

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

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

Parameters:

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

copy()[source]

Returns a shallow copy of the embed.

property footer[source]

Returns an EmbedProxy denoting the footer contents.

Possible attributes you can access are:

  • text

  • icon_url

  • proxy_icon_url

If an attribute is not set, it will be None.

Sets the footer for the embed content.

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

Parameters:
  • text (str) –

    The footer text.

    Changed in version 2.6: No longer optional, must be set to a valid string.

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

Clears embed’s footer information.

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

New in version 2.0.

property image[source]

Returns an EmbedProxy denoting the image contents.

Possible attributes you can access are:

  • url

  • proxy_url

  • width

  • height

If an attribute is not set, it will be None.

set_image(url=..., *, file=...)[source]

Sets the image for the embed content.

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

Exactly one of url or file must be passed.

Changed in version 1.4: Passing None removes the image.

Parameters:
  • url (Optional[str]) – The source URL for the image. Only HTTP(S) is supported.

  • file (File) –

    The file to use as the image.

    New in version 2.2.

property thumbnail[source]

Returns an EmbedProxy denoting the thumbnail contents.

Possible attributes you can access are:

  • url

  • proxy_url

  • width

  • height

If an attribute is not set, it will be None.

set_thumbnail(url=..., *, file=...)[source]

Sets the thumbnail for the embed content.

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

Exactly one of url or file must be passed.

Changed in version 1.4: Passing None removes the thumbnail.

Parameters:
  • url (Optional[str]) – The source URL for the thumbnail. Only HTTP(S) is supported.

  • file (File) –

    The file to use as the image.

    New in version 2.2.

property video[source]

Returns an EmbedProxy denoting the video contents.

Possible attributes include:

  • url for the video URL.

  • proxy_url for the proxied video URL.

  • height for the video height.

  • width for the video width.

If an attribute is not set, it will be None.

property provider[source]

Returns an EmbedProxy denoting the provider contents.

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

If an attribute is not set, it will be None.

property author[source]

Returns an EmbedProxy denoting the author contents.

See set_author() for possible values you can access.

If an attribute is not set, it will be None.

set_author(*, name, url=None, icon_url=None)[source]

Sets the author for the embed content.

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

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

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

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

remove_author()[source]

Clears embed’s author information.

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

New in version 1.4.

property fields[source]

Returns a list of EmbedProxy denoting the field contents.

See add_field() for possible values you can access.

If an attribute is not set, it will be None.

Type:

List[EmbedProxy]

add_field(name, value, *, inline=True)[source]

Adds a field to the embed object.

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

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

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

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

insert_field_at(index, name, value, *, inline=True)[source]

Inserts a field before a specified index to the embed.

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

New in version 1.2.

Parameters:
  • index (int) – The index of where to insert the field.

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

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

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

clear_fields()[source]

Removes all fields from this embed.

remove_field(index)[source]

Removes a field at a specified index.

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

Note

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

Parameters:

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

set_field_at(index, name, value, *, inline=True)[source]

Modifies a field to the embed object.

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

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

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

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

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

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

Raises:

IndexError – An invalid index was provided.

to_dict()[source]

Converts this embed object into a dict.

classmethod set_default_colour(value)[source]

Set the default colour of all new embeds.

New in version 2.4.

Returns:

The colour that was set.

Return type:

Optional[Colour]

classmethod set_default_color(value)[source]

Set the default colour of all new embeds.

New in version 2.4.

Returns:

The colour that was set.

Return type:

Optional[Colour]

classmethod get_default_colour()[source]

Get the default colour of all new embeds.

New in version 2.4.

Returns:

The default colour.

Return type:

Optional[Colour]

classmethod get_default_color()[source]

Get the default colour of all new embeds.

New in version 2.4.

Returns:

The default colour.

Return type:

Optional[Colour]

check_limits()[source]

Checks if this embed fits within the limits dictated by Discord. There is also a 6000 character limit across all embeds in a message.

Returns nothing on success, raises ValueError if an attribute exceeds the limits.

Field

Limit

title

256 characters

description

4096 characters

fields

Up to 25 field objects

field.name

256 characters

field.value

1024 characters

footer.text

2048 characters

author.name

256 characters

New in version 2.6.

Raises:

ValueError – One or more of the embed attributes are too long.

AllowedMentions
class disnake.AllowedMentions(*, everyone=True, users=True, roles=True, replied_user=True)[source]

A class that represents what mentions are allowed in a message.

This class can be set during Client initialisation to apply to every message sent. It can also be applied on a per message basis via abc.Messageable.send() for more fine-grained control.

everyone

Whether to allow everyone and here mentions. Defaults to True.

Type:

bool

users

Controls the users being mentioned. If True (the default) then users are mentioned based on the message content. If False then users are not mentioned at all. If a list of abc.Snowflake is given then only the users provided will be mentioned, provided those users are in the message content.

Type:

Union[bool, List[abc.Snowflake]]

roles

Controls the roles being mentioned. If True (the default) then roles are mentioned based on the message content. If False then roles are not mentioned at all. If a list of abc.Snowflake is given then only the roles provided will be mentioned, provided those roles are in the message content.

Type:

Union[bool, List[abc.Snowflake]]

replied_user

Whether to mention the author of the message being replied to. Defaults to True.

New in version 1.6.

Type:

bool

classmethod all()[source]

A factory method that returns a AllowedMentions with all fields explicitly set to True

New in version 1.5.

classmethod none()[source]

A factory method that returns a AllowedMentions with all fields set to False

New in version 1.5.

classmethod from_message(message)[source]

A factory method that returns a AllowedMentions dervived from the current Message state.

Note that this is not what AllowedMentions the message was sent with, but what the message actually mentioned. For example, a message that successfully mentioned everyone will have everyone set to True.

New in version 2.6.

MessageReference
class disnake.MessageReference(*, message_id, channel_id, guild_id=None, fail_if_not_exists=True)[source]

Represents a reference to a Message.

New in version 1.5.

Changed in version 1.6: This class can now be constructed by users.

message_id

The ID of the message referenced.

Type:

Optional[int]

channel_id

The channel ID of the message referenced.

Type:

int

guild_id

The guild ID of the message referenced.

Type:

Optional[int]

fail_if_not_exists

Whether replying to the referenced message should raise HTTPException if the message no longer exists or Discord could not fetch the message.

New in version 1.7.

Type:

bool

resolved

The message that this reference resolved to. If this is None then the original message was not fetched either due to the Discord API not attempting to resolve it or it not being available at the time of creation. If the message was resolved at a prior point but has since been deleted then this will be of type DeletedReferencedMessage.

Currently, this is mainly the replied to message when a user replies to a message.

New in version 1.6.

Type:

Optional[Union[Message, DeletedReferencedMessage]]

classmethod from_message(message, *, fail_if_not_exists=True)[source]

Creates a MessageReference from an existing Message.

New in version 1.6.

Parameters:
  • message (Message) – The message to be converted into a reference.

  • fail_if_not_exists (bool) –

    Whether replying to the referenced message should raise HTTPException if the message no longer exists or Discord could not fetch the message.

    New in version 1.7.

Returns:

A reference to the message.

Return type:

MessageReference

property cached_message[source]

The cached message, if found in the internal message cache.

Type:

Optional[Message]

property jump_url[source]

Returns a URL that allows the client to jump to the referenced message.

New in version 1.7.

Type:

str

InteractionReference
Attributes
class disnake.InteractionReference(*, state, data)[source]

Represents an interaction being referenced in a message.

This means responses to message components do not include this property, instead including a message reference object as components always exist on preexisting messages.

New in version 2.1.

id

The ID of the interaction.

Type:

int

type

The type of interaction.

Type:

InteractionType

name

The name of the application command, including group and subcommand name if applicable (separated by spaces).

Note

For interaction references created before July 18th, 2022, this will not include group or subcommand names.

Type:

str

user

The interaction author.

Type:

User

PartialMessage
Methods
class disnake.PartialMessage(*, channel, id)[source]

Represents a partial message to aid with working messages when only a message and channel ID are present.

There are two ways to construct this class. The first one is through the constructor itself, and the second is via the following:

Note that this class is trimmed down and has no rich attributes.

New in version 1.6.

x == y

Checks if two partial messages are equal.

x != y

Checks if two partial messages are not equal.

hash(x)

Returns the partial message’s hash.

channel

The channel associated with this partial message.

Type:

Union[TextChannel, Thread, DMChannel, VoiceChannel, PartialMessageable]

id

The message ID.

Type:

int

property jump_url[source]

Returns a URL that allows the client to jump to this message.

Type:

str

await delete(*, delay=None)[source]

This function is a coroutine.

Deletes the message.

Your own messages could be deleted without any proper permissions. However to delete other people’s messages, you need the manage_messages permission.

Changed in version 1.1: Added the new delay keyword-only parameter.

Parameters:

delay (Optional[float]) – If provided, the number of seconds to wait in the background before deleting the message. If the deletion fails then it is silently ignored.

Raises:
  • Forbidden – You do not have proper permissions to delete the message.

  • NotFound – The message was deleted already

  • HTTPException – Deleting the message failed.

await publish()[source]

This function is a coroutine.

Publishes this message to your announcement channel.

You must have the send_messages permission to do this.

If the message is not your own then the manage_messages permission is also needed.

Raises:
  • Forbidden – You do not have the proper permissions to publish this message.

  • HTTPException – Publishing the message failed.

await pin(*, reason=None)[source]

This function is a coroutine.

Pins the message.

You must have the manage_messages permission to do this in a non-private channel context.

Parameters:

reason (Optional[str]) –

The reason for pinning the message. Shows up on the audit log.

New in version 1.4.

Raises:
  • Forbidden – You do not have permissions to pin the message.

  • NotFound – The message or channel was not found or deleted.

  • HTTPException – Pinning the message failed, probably due to the channel having more than 50 pinned messages.

await unpin(*, reason=None)[source]

This function is a coroutine.

Unpins the message.

You must have the manage_messages permission to do this in a non-private channel context.

Parameters:

reason (Optional[str]) –

The reason for unpinning the message. Shows up on the audit log.

New in version 1.4.

Raises:
  • Forbidden – You do not have permissions to unpin the message.

  • NotFound – The message or channel was not found or deleted.

  • HTTPException – Unpinning the message failed.

await add_reaction(emoji)[source]

This function is a coroutine.

Adds a reaction to the message.

The emoji may be a unicode emoji or a custom guild Emoji.

You must have the read_message_history permission to use this. If nobody else has reacted to the message using this emoji, the add_reactions permission is required.

Changed in version 2.6: Raises TypeError instead of InvalidArgument.

Parameters:

emoji (Union[Emoji, Reaction, PartialEmoji, str]) – The emoji to react with.

Raises:
  • HTTPException – Adding the reaction failed.

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

  • NotFound – The emoji you specified was not found.

  • TypeError – The emoji parameter is invalid.

await remove_reaction(emoji, member)[source]

This function is a coroutine.

Removes a reaction by the member from the message.

The emoji may be a unicode emoji or a custom guild Emoji.

If the reaction is not your own (i.e. member parameter is not you) then the manage_messages permission is needed.

The member parameter must represent a member and meet the abc.Snowflake abc.

Changed in version 2.6: Raises TypeError instead of InvalidArgument.

Parameters:
Raises:
  • HTTPException – Removing the reaction failed.

  • Forbidden – You do not have the proper permissions to remove the reaction.

  • NotFound – The member or emoji you specified was not found.

  • TypeError – The emoji parameter is invalid.

await clear_reaction(emoji)[source]

This function is a coroutine.

Clears a specific reaction from the message.

The emoji may be a unicode emoji or a custom guild Emoji.

You need the manage_messages permission to use this.

New in version 1.3.

Changed in version 2.6: Raises TypeError instead of InvalidArgument.

Parameters:

emoji (Union[Emoji, Reaction, PartialEmoji, str]) – The emoji to clear.

Raises:
  • HTTPException – Clearing the reaction failed.

  • Forbidden – You do not have the proper permissions to clear the reaction.

  • NotFound – The emoji you specified was not found.

  • TypeError – The emoji parameter is invalid.

await clear_reactions()[source]

This function is a coroutine.

Removes all the reactions from the message.

You need the manage_messages permission to use this.

Raises:
  • HTTPException – Removing the reactions failed.

  • Forbidden – You do not have the proper permissions to remove all the reactions.

await reply(content=None, *, fail_if_not_exists=True, **kwargs)[source]

This function is a coroutine.

A shortcut method to abc.Messageable.send() to reply to the Message.

New in version 1.6.

Changed in version 2.3: Added fail_if_not_exists keyword argument. Defaults to True.

Changed in version 2.6: Raises TypeError or ValueError instead of InvalidArgument.

Parameters:

fail_if_not_exists (bool) –

Whether replying using the message reference should raise HTTPException if the message no longer exists or Discord could not fetch the message.

New in version 2.3.

Raises:
  • HTTPException – Sending the message failed.

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

  • TypeError – You specified both embed and embeds, or file and files, or view and components.

  • ValueError – The files or embeds list is too large.

Returns:

The message that was sent.

Return type:

Message

to_reference(*, fail_if_not_exists=True)[source]

Creates a MessageReference from the current message.

New in version 1.6.

Parameters:

fail_if_not_exists (bool) –

Whether replying using the message reference should raise HTTPException if the message no longer exists or Discord could not fetch the message.

New in version 1.7.

Returns:

The reference to this message.

Return type:

MessageReference

property created_at[source]

The partial message’s creation time in UTC.

Type:

datetime.datetime

guild

The guild that the partial message belongs to, if applicable.

Type:

Optional[Guild]

await fetch()[source]

This function is a coroutine.

Fetches the partial message to a full Message.

Raises:
  • NotFound – The message was not found.

  • Forbidden – You do not have the permissions required to get a message.

  • HTTPException – Retrieving the message failed.

Returns:

The full message.

Return type:

Message

await edit(content=..., *, embed=..., embeds=..., file=..., files=..., attachments=..., suppress=..., suppress_embeds=..., allowed_mentions=..., view=..., components=..., delete_after=None)[source]

This function is a coroutine.

Edits the message.

The content must be able to be transformed into a string via str(content).

Changed in version 2.1: disnake.Message is always returned.

Changed in version 2.5: The suppress keyword-only parameter was deprecated in favor of suppress_embeds.

Changed in version 2.6: Raises TypeError instead of InvalidArgument.

Note

If the original message has embeds with images that were created from local files (using the file parameter with Embed.set_image() or Embed.set_thumbnail()), those images will be removed if the message’s attachments are edited in any way (i.e. by setting file/files/attachments, or adding an embed with local files).

Parameters:
  • content (Optional[str]) – The new content to replace the message with. Could be None to remove the content.

  • embed (Optional[Embed]) – The new embed to replace the original with. This cannot be mixed with the embeds parameter. Could be None to remove the embed.

  • embeds (List[Embed]) –

    The new embeds to replace the original with. Must be a maximum of 10. This cannot be mixed with the embed parameter. To remove all embeds [] should be passed.

    New in version 2.1.

  • file (File) –

    The file to upload. This cannot be mixed with the files parameter. Files will be appended to the message, see the attachments parameter to remove/replace existing files.

    New in version 2.1.

  • files (List[File]) –

    A list of files to upload. This cannot be mixed with the file parameter. Files will be appended to the message, see the attachments parameter to remove/replace existing files.

    New in version 2.1.

  • attachments (Optional[List[Attachment]]) –

    A list of attachments to keep in the message. If [] or None is passed then all existing attachments are removed. Keeps existing attachments if not provided.

    New in version 2.1.

    Changed in version 2.5: Supports passing None to clear attachments.

  • suppress_embeds (bool) – Whether to suppress embeds for the message. This removes all the embeds if set to True. If set to False this brings the embeds back if they were suppressed. Using this parameter requires manage_messages.

  • delete_after (Optional[float]) – If provided, the number of seconds to wait in the background before deleting the message we just edited. If the deletion fails, then it is silently ignored.

  • allowed_mentions (Optional[AllowedMentions]) –

    Controls the mentions being processed in this message. If this is passed, then the object is merged with Client.allowed_mentions. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set in Client.allowed_mentions.

    Note

    Unlike Message.edit(), this does not default to Client.allowed_mentions if no object is passed.

  • view (Optional[View]) –

    The updated view to update this message with. This cannot be mixed with components. If None is passed then the view is removed.

    New in version 2.0.

  • components (Union[disnake.ui.ActionRow, disnake.ui.WrappedComponent, List[Union[disnake.ui.ActionRow, disnake.ui.WrappedComponent, List[disnake.ui.WrappedComponent]]]]) –

    The updated components to update this message with. This cannot be mixed with view. If None is passed then the components are removed.

    New in version 2.4.

Raises:
  • NotFound – The message was not found.

  • HTTPException – Editing the message failed.

  • Forbidden – Tried to suppress embeds on a message without permissions or edited a message’s content or embed that isn’t yours.

  • TypeError – You specified both embed and embeds, or file and files, or view and components.

Returns:

The message that was edited.

Return type:

Message

ApplicationCommand
class disnake.ApplicationCommand[source]

The base class for application commands.

The following classes implement this ABC:

type

The command type

Type:

ApplicationCommandType

name

The command name

Type:

str

name_localizations

Localizations for name.

New in version 2.5.

Type:

LocalizationValue

dm_permission

Whether this command can be used in DMs. Defaults to True.

New in version 2.5.

Type:

bool

property default_member_permissions[source]

The default required member permissions for this command. A member must have all these permissions to be able to invoke the command in a guild.

This is a default value, the set of users/roles that may invoke this command can be overridden by moderators on a guild-specific basis, disregarding this setting.

If None is returned, it means everyone can use the command by default. If an empty Permissions object is returned (that is, all permissions set to False), this means no one can use the command.

New in version 2.5.

Type:

Optional[Permissions]

SlashCommand
class disnake.SlashCommand[source]

The base class for building slash commands.

name

The slash command’s name.

Type:

str

name_localizations

Localizations for name.

New in version 2.5.

Type:

LocalizationValue

description

The slash command’s description.

Type:

str

description_localizations

Localizations for description.

New in version 2.5.

Type:

LocalizationValue

dm_permission

Whether this command can be used in DMs. Defaults to True.

New in version 2.5.

Type:

bool

options

The list of options the slash command has.

Type:

List[Option]

add_option(name, description=None, type=None, required=False, choices=None, options=None, channel_types=None, autocomplete=False, min_value=None, max_value=None, min_length=None, max_length=None)[source]

Adds an option to the current list of options, parameters are the same as for Option

property default_member_permissions[source]

The default required member permissions for this command. A member must have all these permissions to be able to invoke the command in a guild.

This is a default value, the set of users/roles that may invoke this command can be overridden by moderators on a guild-specific basis, disregarding this setting.

If None is returned, it means everyone can use the command by default. If an empty Permissions object is returned (that is, all permissions set to False), this means no one can use the command.

New in version 2.5.

Type:

Optional[Permissions]

UserCommand
class disnake.UserCommand[source]

A user context menu command.

name

The user command’s name.

Type:

str

name_localizations

Localizations for name.

New in version 2.5.

Type:

LocalizationValue

dm_permission

Whether this command can be used in DMs. Defaults to True.

New in version 2.5.

Type:

bool

property default_member_permissions[source]

The default required member permissions for this command. A member must have all these permissions to be able to invoke the command in a guild.

This is a default value, the set of users/roles that may invoke this command can be overridden by moderators on a guild-specific basis, disregarding this setting.

If None is returned, it means everyone can use the command by default. If an empty Permissions object is returned (that is, all permissions set to False), this means no one can use the command.

New in version 2.5.

Type:

Optional[Permissions]

MessageCommand
class disnake.MessageCommand[source]

A message context menu command

name

The message command’s name.

Type:

str

name_localizations

Localizations for name.

New in version 2.5.

Type:

LocalizationValue

dm_permission

Whether this command can be used in DMs. Defaults to True.

New in version 2.5.

Type:

bool

property default_member_permissions[source]

The default required member permissions for this command. A member must have all these permissions to be able to invoke the command in a guild.

This is a default value, the set of users/roles that may invoke this command can be overridden by moderators on a guild-specific basis, disregarding this setting.

If None is returned, it means everyone can use the command by default. If an empty Permissions object is returned (that is, all permissions set to False), this means no one can use the command.

New in version 2.5.

Type:

Optional[Permissions]

Option
Methods
class disnake.Option[source]

Represents a slash command option.

Parameters:
  • name (Union[str, Localized]) –

    The option’s name.

    Changed in version 2.5: Added support for localizations.

  • description (Optional[Union[str, Localized]]) –

    The option’s description.

    Changed in version 2.5: Added support for localizations.

  • type (OptionType) – The option type, e.g. OptionType.user.

  • required (bool) – Whether this option is required.

  • choices (Union[List[OptionChoice], List[Union[str, int]], Dict[str, Union[str, int]]]) – The list of option choices.

  • options (List[Option]) – The list of sub options. Normally you don’t have to specify it directly, instead consider using @main_cmd.sub_command or @main_cmd.sub_command_group decorators.

  • channel_types (List[ChannelType]) – The list of channel types that your option supports, if the type is OptionType.channel. By default, it supports all channel types.

  • autocomplete (bool) – Whether this option can be autocompleted.

  • min_value (Union[int, float]) – The minimum value permitted.

  • max_value (Union[int, float]) – The maximum value permitted.

  • min_length (int) –

    The minimum length for this option if this is a string option.

    New in version 2.6.

  • max_length (int) –

    The maximum length for this option if this is a string option.

    New in version 2.6.

add_choice(name, value)[source]

Adds an OptionChoice to the list of current choices, parameters are the same as for OptionChoice.

add_option(name, description=None, type=None, required=False, choices=None, options=None, channel_types=None, autocomplete=False, min_value=None, max_value=None, min_length=None, max_length=None)[source]

Adds an option to the current list of options, parameters are the same as for Option.

OptionChoice
class disnake.OptionChoice[source]

Represents an option choice.

Parameters:
  • name (Union[str, Localized]) –

    The name of the option choice (visible to users).

    Changed in version 2.5: Added support for localizations.

  • value (Union[str, int]) – The value of the option choice.

SelectOption
class disnake.SelectOption(*, label, value=..., description=None, emoji=None, default=False)[source]

Represents a select menu’s option.

These can be created by users.

New in version 2.0.

label

The label of the option. This is displayed to users. Can only be up to 100 characters.

Type:

str

value

The value of the option. This is not displayed to users. If not provided when constructed then it defaults to the label. Can only be up to 100 characters.

Type:

str

description

An additional description of the option, if any. Can only be up to 100 characters.

Type:

Optional[str]

emoji

The emoji of the option, if available.

Type:

Optional[Union[str, Emoji, PartialEmoji]]

default

Whether this option is selected by default.

Type:

bool

Intents
class disnake.Intents(value=None, **kwargs)[source]

Wraps up a Discord gateway intent flag.

Similar to Permissions, the properties provided are two way. You can set and retrieve individual bits using the properties as if they were regular bools.

To construct an object you can pass keyword arguments denoting the flags to enable or disable. Arguments are applied in order, similar to Permissions.

This is used to disable certain gateway features that are unnecessary to run your bot. To make use of this, it is passed to the intents keyword argument of Client.

New in version 1.5.

x == y

Checks if two Intents instances are equal.

x != y

Checks if two Intents instances are not equal.

x <= y

Checks if an Intents instance is a subset of another Intents instance.

New in version 2.6.

x >= y

Checks if an Intents instance is a superset of another Intents instance.

New in version 2.6.

x < y

Checks if an Intents instance is a strict subset of another Intents instance.

New in version 2.6.

x > y

Checks if an Intents instance is a strict superset of another Intents instance.

New in version 2.6.

x | y, x |= y

Returns a new Intents instance with all enabled intents from both x and y. (Using |= will update in place).

New in version 2.6.

x & y, x &= y

Returns a new Intents instance with only intents enabled on both x and y. (Using &= will update in place).

New in version 2.6.

x ^ y, x ^= y

Returns a new Intents instance with only intents enabled on one of x or y, but not both. (Using ^= will update in place).

New in version 2.6.

~x

Returns a new Intents instance with all intents inverted from x.

New in version 2.6.

hash(x)

Return the flag’s hash.

iter(x)

Returns an iterator of (name, value) pairs. This allows it to be, for example, constructed as a dict or a list of pairs.

Additionally supported are a few operations on class attributes.

Intents.y | Intents.z, Intents(y=True) | Intents.z

Returns a Intents instance with all provided flags enabled.

New in version 2.6.

~Intents.y

Returns a Intents instance with all flags except y inverted from their default value.

New in version 2.6.

value

The raw value. You should query flags via the properties rather than using this raw value.

Changed in version 2.6: This can be now be provided on initialisation.

Type:

int

classmethod all()[source]

A factory method that creates a Intents with everything enabled.

classmethod none()[source]

A factory method that creates a Intents with everything disabled.

classmethod default()[source]

A factory method that creates a Intents with everything enabled except presences, members, and message_content.

guilds

Whether guild related events are enabled.

This corresponds to the following events:

This also corresponds to the following attributes and classes in terms of cache:

It is highly advisable to leave this intent enabled for your bot to function.

Type:

bool

members

Whether guild member related events are enabled.

This corresponds to the following events:

This also corresponds to the following attributes and classes in terms of cache:

For more information go to the member intent documentation.

Note

Currently, this requires opting in explicitly via the developer portal as well. Bots in over 100 guilds will need to apply to Discord for verification.

Type:

bool

bans

Whether guild ban related events are enabled.

This corresponds to the following events:

This does not correspond to any attributes or classes in the library in terms of cache.

Type:

bool

emojis

Alias of emojis_and_stickers.

Changed in version 2.0: Changed to an alias.

Type:

bool

emojis_and_stickers

Whether guild emoji and sticker related events are enabled.

New in version 2.0.

This corresponds to the following events:

This also corresponds to the following attributes and classes in terms of cache:

Type:

bool

integrations

Whether guild integration related events are enabled.

This corresponds to the following events:

This does not correspond to any attributes or classes in the library in terms of cache.

Type:

bool

webhooks

Whether guild webhook related events are enabled.

This corresponds to the following events:

This does not correspond to any attributes or classes in the library in terms of cache.

Type:

bool

invites

Whether guild invite related events are enabled.

This corresponds to the following events:

This does not correspond to any attributes or classes in the library in terms of cache.

Type:

bool

voice_states

Whether guild voice state related events are enabled.

This corresponds to the following events:

This also corresponds to the following attributes and classes in terms of cache:

Note

This intent is required to connect to voice.

Type:

bool

presences

Whether guild presence related events are enabled.

This corresponds to the following events:

This also corresponds to the following attributes and classes in terms of cache:

For more information go to the presence intent documentation.

Note

Currently, this requires opting in explicitly via the developer portal as well. Bots in over 100 guilds will need to apply to Discord for verification.

Type:

bool

messages

Whether guild and direct message related events are enabled.

This is a shortcut to set or get both guild_messages and dm_messages.

This corresponds to the following events:

This also corresponds to the following attributes and classes in terms of cache:

Note that due to an implicit relationship this also corresponds to the following events:

Note

Intents.message_content is required to receive the content of messages.

Type:

bool

guild_messages

Whether guild message related events are enabled.

See also dm_messages for DMs or messages for both.

This corresponds to the following events:

This also corresponds to the following attributes and classes in terms of cache:

Note that due to an implicit relationship this also corresponds to the following events:

Type:

bool

dm_messages

Whether direct message related events are enabled.

See also guild_messages for guilds or messages for both.

This corresponds to the following events:

This also corresponds to the following attributes and classes in terms of cache:

Note that due to an implicit relationship this also corresponds to the following events:

Type:

bool

message_content

Whether messages will have access to message content.

New in version 2.5.

This applies to the following fields on Message instances:

The following cases will always have the above fields:

  • Messages the bot sends

  • Messages the bot receives as a direct message

  • Messages in which the bot is mentioned

  • Messages received from an interaction payload, these will typically be attributes on MessageInteraction instances.

In addition, this also corresponds to the following fields:

For more information go to the message content intent documentation.

Note

Currently, this requires opting in explicitly via the developer portal as well. Bots in over 100 guilds will need to apply to Discord for verification.

Type:

bool

reactions

Whether guild and direct message reaction related events are enabled.

This is a shortcut to set or get both guild_reactions and dm_reactions.

This corresponds to the following events:

This also corresponds to the following attributes and classes in terms of cache:

Type:

bool

guild_reactions

Whether guild message reaction related events are enabled.

See also dm_reactions for DMs or reactions for both.

This corresponds to the following events:

This also corresponds to the following attributes and classes in terms of cache:

Type:

bool

dm_reactions

Whether direct message reaction related events are enabled.

See also guild_reactions for guilds or reactions for both.

This corresponds to the following events:

This also corresponds to the following attributes and classes in terms of cache:

Type:

bool

typing

Whether guild and direct message typing related events are enabled.

This is a shortcut to set or get both guild_typing and dm_typing.

This corresponds to the following events:

This does not correspond to any attributes or classes in the library in terms of cache.

Type:

bool

guild_typing

Whether guild and direct message typing related events are enabled.

See also dm_typing for DMs or typing for both.

This corresponds to the following events:

This does not correspond to any attributes or classes in the library in terms of cache.

Type:

bool

dm_typing

Whether guild and direct message typing related events are enabled.

See also guild_typing for guilds or typing for both.

This corresponds to the following events:

This does not correspond to any attributes or classes in the library in terms of cache.

Type:

bool

guild_scheduled_events

Whether guild scheduled event related events are enabled.

New in version 2.3.

This corresponds to the following events:

This also corresponds to the following attributes and classes in terms of cache:

Type:

bool

automod_configuration

Whether auto moderation configuration related events are enabled.

New in version 2.6.

This corresponds to the following events:

This does not correspond to any attributes or classes in the library in terms of cache.

Type:

bool

automod_execution

Whether auto moderation execution related events are enabled.

New in version 2.6.

This corresponds to the following events:

This does not correspond to any attributes or classes in the library in terms of cache.

Type:

bool

automod

Whether auto moderation related events are enabled.

New in version 2.6.

This is a shortcut to set or get both automod_configuration and automod_execution.

This corresponds to the following events:

This does not correspond to any attributes or classes in the library in terms of cache.

Type:

bool

MemberCacheFlags
class disnake.MemberCacheFlags(**kwargs)[source]

Controls the library’s cache policy when it comes to members.

This allows for finer grained control over what members are cached. Note that the bot’s own member is always cached. This class is passed to the member_cache_flags parameter in Client.

Due to a quirk in how Discord works, in order to ensure proper cleanup of cache resources it is recommended to have Intents.members enabled. Otherwise the library cannot know when a member leaves a guild and is thus unable to cleanup after itself.

To construct an object you can pass keyword arguments denoting the flags to enable or disable. Arguments are applied in order, similar to Permissions.

The default value is all flags enabled.

New in version 1.5.

x == y

Checks if two MemberCacheFlags instances are equal.

x != y

Checks if two MemberCacheFlags instances are not equal.

x <= y

Checks if a MemberCacheFlags instance is a subset of another MemberCacheFlags instance.

New in version 2.6.

x >= y

Checks if a MemberCacheFlags instance is a superset of another MemberCacheFlags instance.

New in version 2.6.

x < y

Checks if a MemberCacheFlags instance is a strict subset of another MemberCacheFlags instance.

New in version 2.6.

x > y

Checks if a MemberCacheFlags instance is a strict superset of another MemberCacheFlags instance.

New in version 2.6.

x | y, x |= y

Returns a new MemberCacheFlags instance with all enabled flags from both x and y. (Using |= will update in place).

New in version 2.6.

x & y, x &= y

Returns a new MemberCacheFlags instance with only flags enabled on both x and y. (Using &= will update in place).

New in version 2.6.

x ^ y, x ^= y

Returns a new MemberCacheFlags instance with only flags enabled on one of x or y, but not both. (Using ^= will update in place).

New in version 2.6.

~x

Returns a new MemberCacheFlags instance with all flags from x inverted.

New in version 2.6.

hash(x)

Return the flag’s hash.

iter(x)

Returns an iterator of (name, value) pairs. This allows it to be, for example, constructed as a dict or a list of pairs.

Additionally supported are a few operations on class attributes.

MemberCacheFlags.y | MemberCacheFlags.z, MemberCacheFlags(y=True) | MemberCacheFlags.z

Returns a MemberCacheFlags instance with all provided flags enabled.

New in version 2.6.

~MemberCacheFlags.y

Returns a MemberCacheFlags instance with all flags except y inverted from their default value.

New in version 2.6.

value

The raw value. You should query flags via the properties rather than using this raw value.

Type:

int

classmethod all()[source]

A factory method that creates a MemberCacheFlags with everything enabled.

classmethod none()[source]

A factory method that creates a MemberCacheFlags with everything disabled.

voice

Whether to cache members that are in voice.

This requires Intents.voice_states.

Members that leave voice are no longer cached.

Type:

bool

joined

Whether to cache members that joined the guild or are chunked as part of the initial log in flow.

This requires Intents.members.

Members that leave the guild are no longer cached.

Type:

bool

classmethod from_intents(intents)[source]

A factory method that creates a MemberCacheFlags based on the currently selected Intents.

Parameters:

intents (Intents) – The intents to select from.

Returns:

The resulting member cache flags.

Return type:

MemberCacheFlags

ApplicationFlags
class disnake.ApplicationFlags(**kwargs)[source]

Wraps up the Discord Application flags.

x == y

Checks if two ApplicationFlags instances are equal.

x != y

Checks if two ApplicationFlags instances are not equal.

x <= y

Checks if an ApplicationFlags instance is a subset of another ApplicationFlags instance.

New in version 2.6.

x >= y

Checks if an ApplicationFlags instance is a superset of another ApplicationFlags instance.

New in version 2.6.

x < y

Checks if an ApplicationFlags instance is a strict subset of another ApplicationFlags instance.

New in version 2.6.

x > y

Checks if an ApplicationFlags instance is a strict superset of another ApplicationFlags instance.

New in version 2.6.

x | y, x |= y

Returns a new ApplicationFlags instance with all enabled flags from both x and y. (Using |= will update in place).

New in version 2.6.

x & y, x &= y

Returns a new ApplicationFlags instance with only flags enabled on both x and y. (Using &= will update in place).

New in version 2.6.

x ^ y, x ^= y

Returns a new ApplicationFlags instance with only flags enabled on one of x or y, but not both. (Using ^= will update in place).

New in version 2.6.

~x

Returns a new ApplicationFlags instance with all flags from x inverted.

New in version 2.6.

hash(x)

Return the flag’s hash.

iter(x)

Returns an iterator of (name, value) pairs. This allows it to be, for example, constructed as a dict or a list of pairs. Note that aliases are not shown.

Additionally supported are a few operations on class attributes.

ApplicationFlags.y | ApplicationFlags.z, ApplicationFlags(y=True) | ApplicationFlags.z

Returns a ApplicationFlags instance with all provided flags enabled.

New in version 2.6.

~ApplicationFlags.y

Returns a ApplicationFlags instance with all flags except y inverted from their default value.

New in version 2.6.

New in version 2.0.

value

The raw value. You should query flags via the properties rather than using this raw value.

Type:

int

gateway_presence

Returns True if the application is verified and is allowed to receive presence information over the gateway.

Type:

bool

gateway_presence_limited

Returns True if the application is allowed to receive limited presence information over the gateway.

Type:

bool

gateway_guild_members

Returns True if the application is verified and is allowed to receive guild members information over the gateway.

Type:

bool

gateway_guild_members_limited

Returns True if the application is allowed to receive limited guild members information over the gateway.

Type:

bool

verification_pending_guild_limit

Returns True if the application is currently pending verification and has hit the guild limit.

Type:

bool

embedded

Returns True if the application is embedded within the Discord client.

Type:

bool

gateway_message_content

Returns True if the application is verified and is allowed to receive message content over the gateway.

Type:

bool

gateway_message_content_limited

Returns True if the application is verified and is allowed to receive limited message content over the gateway.

Type:

bool

application_command_badge

Returns True if the application has registered global application commands.

New in version 2.6.

Type:

bool

ChannelFlags
Attributes
class disnake.ChannelFlags(**kwargs)[source]

Wraps up the Discord Channel flags.

x == y

Checks if two ChannelFlags instances are equal.

x != y

Checks if two ChannelFlags instances are not equal.

x <= y

Checks if a ChannelFlags instance is a subset of another ChannelFlags instance.

New in version 2.6.

x >= y

Checks if a ChannelFlags instance is a superset of another ChannelFlags instance.

New in version 2.6.

x < y

Checks if a ChannelFlags instance is a strict subset of another ChannelFlags instance.

New in version 2.6.

x > y

Checks if a ChannelFlags instance is a strict superset of another ChannelFlags instance.

New in version 2.6.

x | y, x |= y

Returns a new ChannelFlags instance with all enabled flags from both x and y. (Using |= will update in place).

New in version 2.6.

x & y, x &= y

Returns a new ChannelFlags instance with only flags enabled on both x and y. (Using &= will update in place).

New in version 2.6.

x ^ y, x ^= y

Returns a new ChannelFlags instance with only flags enabled on one of x or y, but not both. (Using ^= will update in place).

New in version 2.6.

~x

Returns a new ChannelFlags instance with all flags from x inverted.

New in version 2.6.

hash(x)

Return the flag’s hash.

iter(x)

Returns an iterator of (name, value) pairs. This allows it to be, for example, constructed as a dict or a list of pairs. Note that aliases are not shown.

Additionally supported are a few operations on class attributes.

ChannelFlags.y | ChannelFlags.z, ChannelFlags(y=True) | ChannelFlags.z

Returns a ChannelFlags instance with all provided flags enabled.

New in version 2.6.

~ChannelFlags.y

Returns a ChannelFlags instance with all flags except y inverted from their default value.

New in version 2.6.

New in version 2.5.

value

The raw value. You should query flags via the properties rather than using this raw value.

Type:

int

pinned

Returns True if the thread is pinned.

This only applies to channels of type Thread.

Type:

bool

require_tag

Returns True if the channel requires all newly created threads to have a tag.

This only applies to channels of type ForumChannel.

New in version 2.6.

Type:

bool

AutoModKeywordPresets
class disnake.AutoModKeywordPresets(**kwargs)[source]

Wraps up the pre-defined auto moderation keyword lists, provided by Discord.

x == y

Checks if two AutoModKeywordPresets instances are equal.

x != y

Checks if two AutoModKeywordPresets instances are not equal.

x <= y

Checks if an AutoModKeywordPresets instance is a subset of another AutoModKeywordPresets instance.

x >= y

Checks if an AutoModKeywordPresets instance is a superset of another AutoModKeywordPresets instance.

x < y

Checks if an AutoModKeywordPresets instance is a strict subset of another AutoModKeywordPresets instance.

x > y

Checks if an AutoModKeywordPresets instance is a strict superset of another AutoModKeywordPresets instance.

x | y, x |= y

Returns a new AutoModKeywordPresets instance with all enabled flags from both x and y. (Using |= will update in place).

x & y, x &= y

Returns a new AutoModKeywordPresets instance with only flags enabled on both x and y. (Using &= will update in place).

x ^ y, x ^= y

Returns a new AutoModKeywordPresets instance with only flags enabled on one of x or y, but not both. (Using ^= will update in place).

~x

Returns a new AutoModKeywordPresets instance with all flags from x inverted.

hash(x)

Return the flag’s hash.

iter(x)

Returns an iterator of (name, value) pairs. This allows it to be, for example, constructed as a dict or a list of pairs. Note that aliases are not shown.

Additionally supported are a few operations on class attributes.

AutoModKeywordPresets.y | AutoModKeywordPresets.z, AutoModKeywordPresets(y=True) | AutoModKeywordPresets.z

Returns a AutoModKeywordPresets instance with all provided flags enabled.

~AutoModKeywordPresets.y

Returns a AutoModKeywordPresets instance with all flags except y inverted from their default value.

New in version 2.6.

values[source]

The raw values. You should query flags via the properties rather than using these raw values.

Type:

int

classmethod all()[source]

A factory method that creates a AutoModKeywordPresets with everything enabled.

classmethod none()[source]

A factory method that creates a AutoModKeywordPresets with everything disabled.

profanity

Returns True if the profanity preset is enabled (contains words that may be considered swearing or cursing).

Type:

bool

sexual_content

Returns True if the sexual content preset is enabled (contains sexually explicit words).

Type:

bool

slurs

Returns True if the slurs preset is enabled (contains insults or words that may be considered hate speech).

Type:

bool

AutoModTriggerMetadata
class disnake.AutoModTriggerMetadata(*, keyword_filter=None, presets=None, allow_list=None, mention_total_limit=None)[source]

Metadata for an auto moderation trigger.

New in version 2.6.

keyword_filter

The list of keywords to check for. Used with AutoModTriggerType.keyword.

See api docs for details about how keyword matching works.

Type:

Optional[Sequence[str]]

presets

The keyword presets. Used with AutoModTriggerType.keyword_preset.

Type:

Optional[AutoModKeywordPresets]

allow_list

The keywords that should be exempt from a preset. Used with AutoModTriggerType.keyword_preset.

Type:

Optional[Sequence[str]]

mention_total_limit

The maximum number of mentions (members + roles) allowed. Used with AutoModTriggerType.mention_spam.

Type:

Optional[int]

with_changes(*, keyword_filter=..., presets=..., allow_list=..., mention_total_limit=...)[source]

Returns a new instance with the given changes applied. All other fields will be kept intact.

Returns:

The new metadata instance.

Return type:

AutoModTriggerMetadata

AutoModAction
Attributes
class disnake.AutoModAction[source]

A base class for auto moderation actions.

This class is not meant to be instantiated by the user. The user-constructible subclasses are:

Actions received from the API may be of this type (and not one of the subtypes above) if the action type is not implemented yet.

New in version 2.6.

type

The action type.

Type:

AutoModActionType

AutoModBlockMessageAction
Attributes
class disnake.AutoModBlockMessageAction[source]

Represents an auto moderation action that blocks content from being sent.

New in version 2.6.

type

The action type. Always set to block_message.

Type:

AutoModActionType

AutoModSendAlertAction
Attributes
class disnake.AutoModSendAlertAction(channel)[source]

Represents an auto moderation action that sends an alert to a channel.

New in version 2.6.

Parameters:

channel (abc.Snowflake) – The channel to send an alert in when the rule is triggered.

type

The action type. Always set to send_alert_message.

Type:

AutoModActionType

property channel_id[source]

The channel ID to send an alert in when the rule is triggered.

Type:

int

AutoModTimeoutAction
Attributes
class disnake.AutoModTimeoutAction(duration)[source]

Represents an auto moderation action that times out the user.

New in version 2.6.

Parameters:

duration (Union[int, datetime.timedelta]) – The duration (seconds or timedelta) for which to timeout the user when the rule is triggered.

type

The action type. Always set to timeout.

Type:

AutoModActionType

property duration[source]

The duration (in seconds) for which to timeout the user when the rule is triggered.

Type:

int

File
class disnake.File(fp, filename=None, *, spoiler=False, description=None)[source]

A parameter object used for sending file objects.

Note

File objects are single use and are not meant to be reused in multiple abc.Messageable.send()s.

fp

A file-like object opened in binary mode and read mode or a filename representing a file in the hard drive to open.

Note

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

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

Type:

Union[os.PathLike, io.BufferedIOBase]

filename

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

Type:

Optional[str]

spoiler

Whether the attachment is a spoiler.

Type:

bool

description

The file’s description.

New in version 2.3.

Type:

Optional[str]

Colour
class disnake.Colour(value)[source]

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

There is an alias for this called Color.

x == y

Checks if two colours are equal.

x != y

Checks if two colours are not equal.

hash(x)

Return the colour’s hash.

str(x)

Returns the hex format for the colour.

int(x)

Returns the raw colour value.

value

The raw integer colour value.

Type:

int

property r[source]

Returns the red component of the colour.

Type:

int

property g[source]

Returns the green component of the colour.

Type:

int

property b[source]

Returns the blue component of the colour.

Type:

int

to_rgb()[source]

Tuple[int, int, int]: Returns an (r, g, b) tuple representing the colour.

classmethod from_rgb(r, g, b)[source]

Constructs a Colour from an RGB tuple.

classmethod from_hsv(h, s, v)[source]

Constructs a Colour from an HSV tuple.

classmethod default()[source]

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

classmethod random(*, seed=None)[source]

A factory method that returns a Colour with a random hue.

Note

The random algorithm works by choosing a colour with a random hue but with maxed out saturation and value.

New in version 1.6.

Parameters:

seed (Optional[Union[int, str, float, bytes, bytearray]]) –

The seed to initialize the RNG with. If None is passed the default RNG is used.

New in version 1.7.

classmethod teal()[source]

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

classmethod dark_teal()[source]

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

classmethod brand_green()[source]

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

New in version 2.0.

classmethod green()[source]

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

classmethod dark_green()[source]

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

classmethod blue()[source]

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

classmethod dark_blue()[source]

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

classmethod purple()[source]

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

classmethod dark_purple()[source]

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

classmethod magenta()[source]

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

classmethod dark_magenta()[source]

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

classmethod gold()[source]

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

classmethod dark_gold()[source]

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

classmethod orange()[source]

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

classmethod dark_orange()[source]

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

classmethod brand_red()[source]

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

New in version 2.0.

classmethod red()[source]

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

classmethod dark_red()[source]

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

classmethod lighter_grey()[source]

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

classmethod lighter_gray()[source]

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

classmethod dark_grey()[source]

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

classmethod dark_gray()[source]

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

classmethod light_grey()[source]

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

classmethod light_gray()[source]

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

classmethod darker_grey()[source]

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

classmethod darker_gray()[source]

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

classmethod og_blurple()[source]

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

classmethod old_blurple()[source]

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

classmethod blurple()[source]

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

classmethod greyple()[source]

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

classmethod dark_theme()[source]

A factory method that returns a Colour with a value of 0x36393F. This will appear transparent on Discord’s dark theme.

New in version 1.5.

classmethod fuchsia()[source]

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

New in version 2.0.

classmethod yellow()[source]

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

New in version 2.0.

BaseActivity
Attributes
class disnake.BaseActivity(*, created_at=None, timestamps=None, assets=None, **kwargs)[source]

The base activity that all user-settable activities inherit from. A user-settable activity is one that can be used in Client.change_presence().

The following types currently count as user-settable:

Note that although these types are considered user-settable by the library, Discord typically ignores certain combinations of activity depending on what is currently set. This behaviour may change in the future so there are no guarantees on whether Discord will actually let you set these types.

New in version 1.3.

property created_at[source]

When the user started doing this activity in UTC.

New in version 1.3.

Type:

Optional[datetime.datetime]

property end[source]

When the user will stop doing this activity in UTC, if applicable.

Changed in version 2.6: This attribute can now be None.

Type:

Optional[datetime.datetime]

property start[source]

When the user started doing this activity in UTC, if applicable.

Changed in version 2.6: This attribute can now be None.

Type:

Optional[datetime.datetime]

Activity
class disnake.Activity(*, name=None, url=None, type=None, state=None, details=None, party=None, application_id=None, flags=None, buttons=None, emoji=None, id=None, platform=None, sync_id=None, session_id=None, **kwargs)[source]

Represents an activity in Discord.

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

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

Parameters:
  • name (Optional[str]) – The name of the activity.

  • url (Optional[str]) – A stream URL that the activity could be doing.

  • type (ActivityType) – The type of activity currently being done.

application_id

The application ID of the game.

Type:

Optional[int]

name

The name of the activity.

Type:

Optional[str]

url

A stream URL that the activity could be doing.

Type:

Optional[str]

type

The type of activity currently being done.

Type:

ActivityType

state

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

Type:

Optional[str]

details

The detail of the user’s current activity.

Type:

Optional[str]

assets

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

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

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

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

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

Type:

dict

party

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

  • id: A string representing the party ID.

  • size: A list of two integers denoting (current_size, maximum_size).

Type:

dict

buttons

A list of strings representing the labels of custom buttons shown in a rich presence.

New in version 2.0.

Changed in version 2.6: Changed type to List[str] to match API types.

Type:

List[str]

emoji

The emoji that belongs to this activity.

Type:

Optional[PartialEmoji]

property large_image_url[source]

Returns a URL pointing to the large image asset of this activity, if applicable.

Type:

Optional[str]

property small_image_url[source]

Returns a URL pointing to the small image asset of this activity, if applicable.

Type:

Optional[str]

property large_image_text[source]

Returns the large image asset hover text of this activity, if applicable.

Type:

Optional[str]

property small_image_text[source]

Returns the small image asset hover text of this activity, if applicable.

Type:

Optional[str]

property created_at[source]

When the user started doing this activity in UTC.

New in version 1.3.

Type:

Optional[datetime.datetime]

property end[source]

When the user will stop doing this activity in UTC, if applicable.

Changed in version 2.6: This attribute can now be None.

Type:

Optional[datetime.datetime]

property start[source]

When the user started doing this activity in UTC, if applicable.

Changed in version 2.6: This attribute can now be None.

Type:

Optional[datetime.datetime]

Game
class disnake.Game(name, *, platform=None, **kwargs)[source]

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

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

x == y

Checks if two games are equal.

x != y

Checks if two games are not equal.

hash(x)

Returns the game’s hash.

str(x)

Returns the game’s name.

Parameters:

name (str) – The game’s name.

name

The game’s name.

Type:

str

assets

A dictionary with the same structure as Activity.assets.

Type:

dict

property type[source]

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

It always returns ActivityType.playing.

Type:

ActivityType

property created_at[source]

When the user started doing this activity in UTC.

New in version 1.3.

Type:

Optional[datetime.datetime]

property end[source]

When the user will stop doing this activity in UTC, if applicable.

Changed in version 2.6: This attribute can now be None.

Type:

Optional[datetime.datetime]

property start[source]

When the user started doing this activity in UTC, if applicable.

Changed in version 2.6: This attribute can now be None.

Type:

Optional[datetime.datetime]

Streaming
class disnake.Streaming(*, name, url, details=None, state=None, **kwargs)[source]

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

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

x == y

Checks if two streams are equal.

x != y

Checks if two streams are not equal.

hash(x)

Returns the stream’s hash.

str(x)

Returns the stream’s name.

platform

Where the user is streaming from (ie. YouTube, Twitch).

New in version 1.3.

Type:

Optional[str]

name

The stream’s name.

Type:

Optional[str]

details

An alias for name

Type:

Optional[str]

game

The game being streamed.

New in version 1.3.

Type:

Optional[str]

url

The stream’s URL.

Type:

str

assets

A dictionary with the same structure as Activity.assets.

Type:

dict

property type[source]

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

It always returns ActivityType.streaming.

Type:

ActivityType

property twitch_name[source]

If provided, the twitch name of the user streaming.

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

Type:

Optional[str]

property created_at[source]

When the user started doing this activity in UTC.

New in version 1.3.

Type:

Optional[datetime.datetime]

property end[source]

When the user will stop doing this activity in UTC, if applicable.

Changed in version 2.6: This attribute can now be None.

Type:

Optional[datetime.datetime]

property start[source]

When the user started doing this activity in UTC, if applicable.

Changed in version 2.6: This attribute can now be None.

Type:

Optional[datetime.datetime]

CustomActivity
class disnake.CustomActivity(name, *, emoji=None, state=None, **kwargs)[source]

Represents a Custom activity from Discord.

x == y

Checks if two activities are equal.

x != y

Checks if two activities are not equal.

hash(x)

Returns the activity’s hash.

str(x)

Returns the custom status text.

New in version 1.3.

name

The custom activity’s name.

Type:

Optional[str]

emoji

The emoji to pass to the activity, if any.

Type:

Optional[PartialEmoji]

property type[source]

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

It always returns ActivityType.custom.

Type:

ActivityType

property created_at[source]

When the user started doing this activity in UTC.

New in version 1.3.

Type:

Optional[datetime.datetime]

property end[source]

When the user will stop doing this activity in UTC, if applicable.

Changed in version 2.6: This attribute can now be None.

Type:

Optional[datetime.datetime]

property start[source]

When the user started doing this activity in UTC, if applicable.

Changed in version 2.6: This attribute can now be None.

Type:

Optional[datetime.datetime]

Permissions
class disnake.Permissions(permissions=0, **kwargs)[source]

Wraps up the Discord permission value.

The properties provided are two way. You can set and retrieve individual bits using the properties as if they were regular bools. This allows you to edit permissions.

To construct an object you can pass keyword arguments denoting the permissions to enable or disable. Arguments are applied in order, which notably also means that supplying a flag and its alias will make whatever comes last overwrite the first one; as an example, Permissions(external_emojis=True, use_external_emojis=False) and Permissions(use_external_emojis=True, external_emojis=False) both result in the same permissions value (0).

Changed in version 1.3: You can now use keyword arguments to initialize Permissions similar to update().

x == y

Checks if two permissions are equal.

x != y

Checks if two permissions are not equal.

x <= y

Checks if a permission is a subset of another permission.

x >= y

Checks if a permission is a superset of another permission.

x < y

Checks if a permission is a strict subset of another permission.

x > y

Checks if a permission is a strict superset of another permission.

x | y, x |= y

Returns a new Permissions instance with all enabled permissions from both x and y. (Using |= will update in place).

New in version 2.6.

x & y, x &= y

Returns a new Permissions instance with only permissions enabled on both x and y. (Using &= will update in place).

New in version 2.6.

x ^ y, x ^= y

Returns a new Permissions instance with only permissions enabled on one of x or y, but not both. (Using ^= will update in place).

New in version 2.6.

~x

Returns a new Permissions instance with all permissions from x inverted.

New in version 2.6.

hash(x)

Return the permission’s hash.

iter(x)

Returns an iterator of (perm, value) pairs. This allows it to be, for example, constructed as a dict or a list of pairs. Note that aliases are not shown.

Additionally supported are a few operations on class attributes.

Permissions.y | Permissions.z, Permissions(y=True) | Permissions.z

Returns a Permissions instance with all provided permissions enabled.

New in version 2.6.

~Permissions.y

Returns a Permissions instance with all permissions except y inverted from their default value.

New in version 2.6.

value

The raw value. This value is a bit array field of a 53-bit integer representing the currently available permissions. You should query permissions via the properties rather than using this raw value.

Type:

int

is_subset(other)[source]

Returns True if self has the same or fewer permissions as other.

is_superset(other)[source]

Returns True if self has the same or more permissions as other.

is_strict_subset(other)[source]

Returns True if the permissions on self are a strict subset of those on other.

is_strict_superset(other)[source]

Returns True if the permissions on self are a strict superset of those on other.

classmethod none()[source]

A factory method that creates a Permissions with all permissions set to False.

classmethod all()[source]

A factory method that creates a Permissions with all permissions set to True.

classmethod all_channel()[source]

A Permissions with all channel-specific permissions set to True and the guild-specific ones set to False. The guild-specific permissions are currently:

Changed in version 1.7: Added stream, priority_speaker and use_slash_commands permissions.

Changed in version 2.3: Added use_embedded_activities permission.

classmethod general()[source]

A factory method that creates a Permissions with all “General” permissions from the official Discord UI set to True.

Changed in version 1.7: Permission read_messages is now included in the general permissions, but permissions administrator, create_instant_invite, kick_members, ban_members, change_nickname and manage_nicknames are no longer part of the general permissions.

classmethod membership()[source]

A factory method that creates a Permissions with all “Membership” permissions from the official Discord UI set to True.

New in version 1.7.

Changed in version 2.3: Added moderate_members permission.

classmethod text()[source]

A factory method that creates a Permissions with all “Text” permissions from the official Discord UI set to True.

Changed in version 1.7: Permission read_messages is no longer part of the text permissions. Added use_slash_commands permission.

classmethod voice()[source]

A factory method that creates a Permissions with all “Voice” permissions from the official Discord UI set to True.

Changed in version 2.3: Added use_embedded_activities permission.

classmethod stage()[source]

A factory method that creates a Permissions with all “Stage Channel” permissions from the official Discord UI set to True.

New in version 1.7.

classmethod stage_moderator()[source]

A factory method that creates a Permissions with all “Stage Moderator” permissions from the official Discord UI set to True.

New in version 1.7.

classmethod events()[source]

A factory method that creates a Permissions with all “Events” permissions from the official Discord UI set to True.

New in version 2.4.

classmethod advanced()[source]

A factory method that creates a Permissions with all “Advanced” permissions from the official Discord UI set to True.

New in version 1.7.

classmethod private_channel()[source]

A factory method that creates a Permissions with the best representation of a PrivateChannel’s permissions.

This exists to maintain compatibility with other channel types.

This is equivalent to Permissions.text() with view_channel with the following set to False:

New in version 2.4.

update(**kwargs)[source]

Bulk updates this permission object.

Allows you to set multiple attributes by using keyword arguments. The names must be equivalent to the properties listed. Extraneous key/value pairs will be silently ignored.

Arguments are applied in order, similar to the constructor.

Parameters:

**kwargs – A list of key/value pairs to bulk update permissions with.

create_instant_invite

Returns True if the user can create instant invites.

Type:

bool

kick_members

Returns True if the user can kick users from the guild.

Type:

bool

ban_members

Returns True if a user can ban users from the guild.

Type:

bool

administrator

Returns True if a user is an administrator. This role overrides all other permissions.

This also bypasses all channel-specific overrides.

Type:

bool

manage_channels

Returns True if a user can edit, delete, or create channels in the guild.

This also corresponds to the “Manage Channel” channel-specific override.

Type:

bool

manage_guild

Returns True if a user can edit guild properties.

Type:

bool

add_reactions

Returns True if a user can add reactions to messages.

Type:

bool

view_audit_log

Returns True if a user can view the guild’s audit log.

Type:

bool

priority_speaker

Returns True if a user can be more easily heard while talking.

Type:

bool

stream

Returns True if a user can stream in a voice channel.

Type:

bool

view_channel

Returns True if a user can view all or specific channels.

New in version 1.3.

Changed in version 2.4: read_messages is now an alias of view_channel.

Type:

bool

read_messages

An alias for view_channel.

Type:

bool

send_messages

Returns True if a user can send messages from all or specific text channels and create threads in forum channels.

Type:

bool

create_forum_threads

An alias for send_messages.

New in version 2.5.

Type:

bool

send_tts_messages

Returns True if a user can send TTS messages from all or specific text channels.

Type:

bool

manage_messages

Returns True if a user can delete or pin messages in a text channel.

Note

Note that there are currently no ways to edit other people’s messages.

Type:

bool

Returns True if a user’s messages will automatically be embedded by Discord.

Type:

bool

attach_files

Returns True if a user can send files in their messages.

Type:

bool

read_message_history

Returns True if a user can read a text channel’s previous messages.

Type:

bool

mention_everyone

Returns True if a user’s @everyone or @here will mention everyone in the text channel.

Type:

bool

external_emojis

Returns True if a user can use emojis from other guilds.

Type:

bool

use_external_emojis

An alias for external_emojis.

New in version 1.3.

Type:

bool

view_guild_insights

Returns True if a user can view the guild’s insights.

New in version 1.3.

Type:

bool

connect

Returns True if a user can connect to a voice channel.

Type:

bool

speak

Returns True if a user can speak in a voice channel.

Type:

bool

mute_members

Returns True if a user can mute other users.

Type:

bool

deafen_members

Returns True if a user can deafen other users.

Type:

bool

move_members

Returns True if a user can move users between other voice channels.

Type:

bool

use_voice_activation

Returns True if a user can use voice activation in voice channels.

Type:

bool

change_nickname

Returns True if a user can change their nickname in the guild.

Type:

bool

manage_nicknames

Returns True if a user can change other user’s nickname in the guild.

Type:

bool

manage_roles

Returns True if a user can create or edit roles less than their role’s position.

This also corresponds to the “Manage Permissions” channel-specific override.

Type:

bool

manage_permissions

An alias for manage_roles.

New in version 1.3.

Type:

bool

manage_webhooks

Returns True if a user can create, edit, or delete webhooks.

Type:

bool

manage_emojis

Returns True if a user can create, edit, or delete emojis.

Type:

bool

manage_emojis_and_stickers

An alias for manage_emojis.

New in version 2.0.

Type:

bool

use_application_commands

Returns True if a user can use application commands.

New in version 2.6.

Type:

bool

use_slash_commands

An alias for use_application_commands.

New in version 1.7.

Changed in version 2.6: Became an alias for use_application_commands.

Type:

bool

request_to_speak

Returns True if a user can request to speak in a stage channel.

New in version 1.7.

Type:

bool

manage_events

Returns True if a user can manage guild events.

New in version 2.0.

Type:

bool

manage_threads

Returns True if a user can manage threads.

New in version 2.0.

Type:

bool

create_public_threads

Returns True if a user can create public threads.

New in version 2.0.

Type:

bool

create_private_threads

Returns True if a user can create private threads.

New in version 2.0.

Type:

bool

external_stickers

Returns True if a user can use stickers from other guilds.

New in version 2.0.

Type:

bool

use_external_stickers

An alias for external_stickers.

New in version 2.0.

Type:

bool

send_messages_in_threads

Returns True if a user can send messages in threads.

New in version 2.0.

Type:

bool

use_embedded_activities

Returns True if a user can use activities (applications with the embedded flag) in a voice channel.

New in version 2.6.

Type:

bool

start_embedded_activities

An alias for use_embedded_activities.

New in version 2.3.

Changed in version 2.6: Became an alias for use_embedded_activities.

Type:

bool

moderate_members

Returns True if a user can perform limited moderation actions (timeout).

New in version 2.3.

Type:

bool

PermissionOverwrite
class disnake.PermissionOverwrite(**kwargs)[source]

A type that is used to represent a channel specific permission.

Unlike a regular Permissions, the default value of a permission is equivalent to None and not False. Setting a value to False is explicitly denying that permission, while setting a value to True is explicitly allowing that permission.

The values supported by this are the same as Permissions with the added possibility of it being set to None.

x == y

Checks if two overwrites are equal.

x != y

Checks if two overwrites are not equal.

iter(x)

Returns an iterator of (perm, value) pairs. This allows it to be, for example, constructed as a dict or a list of pairs. Note that aliases are not shown.

Parameters:

**kwargs – Set the value of permissions by their name.

pair()[source]

Tuple[Permissions, Permissions]: Returns the (allow, deny) pair from this overwrite.

classmethod from_pair(allow, deny)[source]

Creates an overwrite from an allow/deny pair of Permissions.

is_empty()[source]

Checks if the permission overwrite is currently empty.

An empty permission overwrite is one that has no overwrites set to True or False.

Returns:

Indicates if the overwrite is empty.

Return type:

bool

update(**kwargs)[source]

Bulk updates this permission overwrite object.

Allows you to set multiple attributes by using keyword arguments. The names must be equivalent to the properties listed. Extraneous key/value pairs will be silently ignored.

Parameters:

**kwargs – A list of key/value pairs to bulk update with.

ShardInfo
Attributes
Methods
class disnake.ShardInfo[source]

A class that gives information and control over a specific shard.

You can retrieve this object via AutoShardedClient.get_shard() or AutoShardedClient.shards.

New in version 1.4.

id

The shard ID for this shard.

Type:

int

shard_count

The shard count for this cluster. If this is None then the bot has not started yet.

Type:

Optional[int]

is_closed()[source]

Whether the shard connection is currently closed.

Return type:

bool

await disconnect()[source]

This function is a coroutine.

Disconnects a shard. When this is called, the shard connection will no longer be open.

If the shard is already disconnected this does nothing.

await reconnect()[source]

This function is a coroutine.

Disconnects and then connects the shard again.

await connect()[source]

This function is a coroutine.

Connects a shard. If the shard is already connected this does nothing.

property latency[source]

Measures latency between a HEARTBEAT and a HEARTBEAT_ACK in seconds for this shard.

Type:

float

is_ws_ratelimited()[source]

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.

Return type:

bool

SessionStartLimit
class disnake.SessionStartLimit[source]

A class that contains information about the current session start limit, at the time when the client connected for the first time.

New in version 2.5.

total

The total number of allowed session starts.

Type:

int

remaining

The remaining number of allowed session starts.

Type:

int

reset_after

The number of milliseconds after which the remaining limit resets, relative to when the client connected. See also reset_time.

Type:

int

max_concurrency

The number of allowed IDENTIFY requests per 5 seconds.

Type:

int

reset_time

The approximate time at which which the remaining limit resets.

Type:

datetime.datetime

GatewayParams
class disnake.GatewayParams[source]

Container type for configuring gateway connections.

New in version 2.6.

Parameters:
  • encoding (str) – The payload encoding (json is currently the only supported encoding). Defaults to "json".

  • zlib (bool) – Whether to enable transport compression. Defaults to True.

SystemChannelFlags
class disnake.SystemChannelFlags[source]

Wraps up a Discord system channel flag value.

Similar to Permissions, the properties provided are two way. You can set and retrieve individual bits using the properties as if they were regular bools. This allows you to edit the system flags easily.

To construct an object you can pass keyword arguments denoting the flags to enable or disable. Arguments are applied in order, similar to Permissions.

x == y

Checks if two SystemChannelFlags instances are equal.

x != y

Checks if two SystemChannelFlags instances are not equal.

x <= y

Checks if a SystemChannelFlags instance is a subset of another SystemChannelFlags instance.

New in version 2.6.

x >= y

Checks if a SystemChannelFlags instance is a superset of another SystemChannelFlags instance.

New in version 2.6.

x < y

Checks if a SystemChannelFlags instance is a strict subset of another SystemChannelFlags instance.

New in version 2.6.

x > y

Checks if a SystemChannelFlags instance is a strict superset of another SystemChannelFlags instance.

New in version 2.6.

x | y, x |= y

Returns a new SystemChannelFlags instance with all enabled flags from both x and y. (Using |= will update in place).

New in version 2.6.

x & y, x &= y

Returns a new SystemChannelFlags instance with only flags enabled on both x and y. (Using &= will update in place).

New in version 2.6.

x ^ y, x ^= y

Returns a new SystemChannelFlags instance with only flags enabled on one of x or y, but not both. (Using ^= will update in place).

New in version 2.6.

~x

Returns a new SystemChannelFlags instance with all flags from x inverted.

New in version 2.6.

hash(x)

Return the flag’s hash.

iter(x)

Returns an iterator of (name, value) pairs. This allows it to be, for example, constructed as a dict or a list of pairs.

Additionally supported are a few operations on class attributes.

SystemChannelFlags.y | SystemChannelFlags.z, SystemChannelFlags(y=True) | SystemChannelFlags.z

Returns a SystemChannelFlags instance with all provided flags enabled.

~SystemChannelFlags.y

Returns a SystemChannelFlags instance with all flags except y inverted from their default value.

value

The raw value. This value is a bit array field of a 53-bit integer representing the currently available flags. You should query flags via the properties rather than using this raw value.

Type:

int

join_notifications

Returns True if the system channel is used for member join notifications.

Type:

bool

premium_subscriptions

Returns True if the system channel is used for “Nitro boosting” notifications.

Type:

bool

guild_reminder_notifications

Returns True if the system channel is used for server setup helpful tips notifications.

New in version 2.0.

Type:

bool

join_notification_replies

Returns True if the system channel shows sticker reply buttons for member join notifications.

New in version 2.3.

Type:

bool

MessageFlags
class disnake.MessageFlags[source]

Wraps up a Discord Message flag value.

See SystemChannelFlags.

x == y

Checks if two MessageFlags instances are equal.

x != y

Checks if two MessageFlags instances are not equal.

x <= y

Checks if a MessageFlags instance is a subset of another MessageFlags instance.

New in version 2.6.

x >= y

Checks if a MessageFlags instance is a superset of another MessageFlags instance.

New in version 2.6.

x < y

Checks if a MessageFlags instance is a strict subset of another MessageFlags instance.

New in version 2.6.

x > y

Checks if a MessageFlags instance is a strict superset of another MessageFlags instance.

New in version 2.6.

x | y, x |= y

Returns a new MessageFlags instance with all enabled flags from both x and y. (Using |= will update in place).

New in version 2.6.

x & y, x &= y

Returns a new MessageFlags instance with only flags enabled on both x and y. (Using &= will update in place).

New in version 2.6.

x ^ y, x ^= y

Returns a new MessageFlags instance with only flags enabled on one of x or y, but not both. (Using ^= will update in place).

New in version 2.6.

~x

Returns a new MessageFlags instance with all flags from x inverted.

New in version 2.6.

hash(x)

Return the flag’s hash.

iter(x)

Returns an iterator of (name, value) pairs. This allows it to be, for example, constructed as a dict or a list of pairs.

Additionally supported are a few operations on class attributes.

MessageFlags.y | MessageFlags.z, MessageFlags(y=True) | MessageFlags.z

Returns a MessageFlags instance with all provided flags enabled.

New in version 2.6.

~MessageFlags.y

Returns a MessageFlags instance with all flags except y inverted from their default value.

New in version 2.6.

New in version 1.3.

value

The raw value. This value is a bit array field of a 53-bit integer representing the currently available flags. You should query flags via the properties rather than using this raw value.

Type:

int

crossposted

Returns True if the message is the original crossposted message.

Type:

bool

is_crossposted

Returns True if the message was crossposted from another channel.

Type:

bool

suppress_embeds

Returns True if the message’s embeds have been suppressed.

Type:

bool

source_message_deleted

Returns True if the source message for this crosspost has been deleted.

Type:

bool

urgent

Returns True if the source message is an urgent message.

An urgent message is one sent by Discord Trust and Safety.

Type:

bool

has_thread

Returns True if the source message is associated with a thread.

New in version 2.0.

Type:

bool

ephemeral

Returns True if the source message is ephemeral.

New in version 2.0.

Type:

bool

loading

Returns True if the source message is a deferred interaction response and shows a “thinking” state.

New in version 2.3.

Type:

bool

failed_to_mention_roles_in_thread

Returns True if the source message failed to mention some roles and add their members to the thread.

New in version 2.4.

Type:

bool

PublicUserFlags
class disnake.PublicUserFlags[source]

Wraps up the Discord User Public flags.

x == y

Checks if two PublicUserFlags instances are equal.

x != y

Checks if two PublicUserFlags instances are not equal.

x <= y

Checks if a PublicUserFlags instance is a subset of another PublicUserFlags instance.

New in version 2.6.

x >= y

Checks if a PublicUserFlags instance is a superset of another PublicUserFlags instance.

New in version 2.6.

x < y

Checks if a PublicUserFlags instance is a strict subset of another PublicUserFlags instance.

New in version 2.6.

x > y

Checks if a PublicUserFlags instance is a strict superset of another PublicUserFlags instance.

New in version 2.6.

x | y, x |= y

Returns a new PublicUserFlags instance with all enabled flags from both x and y. (Using |= will update in place).

New in version 2.6.

x & y, x &= y

Returns a new PublicUserFlags instance with only flags enabled on both x and y. (Using &= will update in place).

New in version 2.6.

x ^ y, x ^= y

Returns a new PublicUserFlags instance with only flags enabled on one of x or y, but not both. (Using ^= will update in place).

New in version 2.6.

~x

Returns a new PublicUserFlags instance with all flags from x inverted.

New in version 2.6.

hash(x)

Return the flag’s hash.

iter(x)

Returns an iterator of (name, value) pairs. This allows it to be, for example, constructed as a dict or a list of pairs. Note that aliases are not shown.

Additionally supported are a few operations on class attributes.

PublicUserFlags.y | PublicUserFlags.z, PublicUserFlags(y=True) | PublicUserFlags.z

Returns a PublicUserFlags instance with all provided flags enabled.

New in version 2.6.

~PublicUserFlags.y

Returns a PublicUserFlags instance with all flags except y inverted from their default value.

New in version 2.6.

New in version 1.4.

value

The raw value. This value is a bit array field of a 53-bit integer representing the currently available flags. You should query flags via the properties rather than using this raw value.

Type:

int

staff

Returns True if the user is a Discord Employee.

Type:

bool

partner

Returns True if the user is a Discord Partner.

Type:

bool

hypesquad

Returns True if the user is a HypeSquad Events member.

Type:

bool

bug_hunter

Returns True if the user is a Bug Hunter

Type:

bool

hypesquad_bravery

Returns True if the user is a HypeSquad Bravery member.

Type:

bool

hypesquad_brilliance

Returns True if the user is a HypeSquad Brilliance member.

Type:

bool

hypesquad_balance

Returns True if the user is a HypeSquad Balance member.

Type:

bool

early_supporter

Returns True if the user is an Early Supporter.

Type:

bool

team_user

Returns True if the user is a Team User.

Type:

bool

system

Returns True if the user is a system user (i.e. represents Discord officially).

Type:

bool

bug_hunter_level_2

Returns True if the user is a Bug Hunter Level 2

Type:

bool

verified_bot

Returns True if the user is a Verified Bot.

Type:

bool

verified_bot_developer

Returns True if the user is an Early Verified Bot Developer.

Type:

bool

early_verified_bot_developer

An alias for verified_bot_developer.

New in version 1.5.

Type:

bool

discord_certified_moderator

Returns True if the user is a Discord Certified Moderator.

New in version 2.0.

Type:

bool

http_interactions_bot

Returns True if the user is a bot that only uses HTTP interactions.

New in version 2.3.

Type:

bool

spammer

Returns True if the user is marked as a spammer.

New in version 2.3.

Type:

bool

all()[source]

List[UserFlags]: Returns all public flags the user has.

Bot UI Kit

The library has helpers to help create component-based UIs.

View
class disnake.ui.View(*, timeout=180.0)[source]

Represents a UI view.

This object must be inherited to create a UI within Discord.

Alternatively, components can be handled with disnake.ui.ActionRows and event listeners for a more low-level approach. Relevant events are disnake.on_button_click(), disnake.on_dropdown(), and the more generic disnake.on_message_interaction().

New in version 2.0.

Parameters:

timeout (Optional[float]) – Timeout in seconds from last interaction with the UI before no longer accepting input. If None then there is no timeout.

timeout

Timeout from last interaction with the UI before no longer accepting input. If None then there is no timeout.

Type:

Optional[float]

children

The list of children attached to this view.

Type:

List[Item]

classmethod from_message(message, /, *, timeout=180.0)[source]

Converts a message’s components into a View.

The Message.components of a message are read-only and separate types from those in the disnake.ui namespace. In order to modify and edit message components they must be converted into a View first.

Parameters:
  • message (disnake.Message) – The message with components to convert into a view.

  • timeout (Optional[float]) – The timeout of the converted view.

Returns:

The converted view. This always returns a View and not one of its subclasses.

Return type:

View

add_item(item)[source]

Adds an item to the view.

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

Parameters:

item (Item) – The item to add to the view.

Raises:
  • TypeError – An Item was not passed.

  • ValueError – Maximum number of children has been exceeded (25) or the row the item is trying to be added to is full.

remove_item(item)[source]

Removes an item from the view.

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

Parameters:

item (Item) – The item to remove from the view.

clear_items()[source]

Removes all items from the view.

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

await interaction_check(interaction)[source]

This function is a coroutine.

A callback that is called when an interaction happens within the view that checks whether the view should process item callbacks for the interaction.

This is useful to override if, for example, you want to ensure that the interaction author is a given user.

The default implementation of this returns True.

Note

If an exception occurs within the body then the check is considered a failure and on_error() is called.

Parameters:

interaction (MessageInteraction) – The interaction that occurred.

Returns:

Whether the view children’s callbacks should be called.

Return type:

bool

await on_timeout()[source]

This function is a coroutine.

A callback that is called when a view’s timeout elapses without being explicitly stopped.

await on_error(error, item, interaction)[source]

This function is a coroutine.

A callback that is called when an item’s callback or interaction_check() fails with an error.

The default implementation prints the traceback to stderr.

Parameters:
  • error (Exception) – The exception that was raised.

  • item (Item) – The item that failed the dispatch.

  • interaction (MessageInteraction) – The interaction that led to the failure.

stop()[source]

Stops listening to interaction events from this view.

This operation cannot be undone.

is_finished()[source]

Whether the view has finished interacting.

Return type:

bool

is_dispatching()[source]

Whether the view has been added for dispatching purposes.

Return type:

bool

is_persistent()[source]

Whether the view is set up as persistent.

A persistent view has all their components with a set custom_id and a timeout set to None.

Return type:

bool

await wait()[source]

Waits until the view has finished interacting.

A view is considered finished when stop() is called or it times out.

Returns:

If True, then the view timed out. If False then the view finished normally.

Return type:

bool

ActionRow
class disnake.ui.ActionRow(*components)[source]

Represents a UI action row. Useful for lower level component manipulation.

x[i]

Returns the component at position i. Also supports slices.

New in version 2.6.

len(x)

Returns the number of components in this row.

New in version 2.6.

iter(x)

Returns an iterator for the components in this row.

New in version 2.6.

To handle interactions created by components sent in action rows or entirely independently, event listeners must be used. For buttons and selects, the related events are disnake.on_button_click() and disnake.on_dropdown(), respectively. Alternatively, disnake.on_message_interaction() can be used for either. For modals, the related event is disnake.on_modal_submit().

New in version 2.4.

Changed in version 2.6: Requires and provides stricter typing for contained components.

Parameters:

*components (WrappedComponent) –

The components of this action row.

Changed in version 2.6: Components can now be either valid in the context of a message, or in the context of a modal. Combining components from both contexts is not supported.

property children[source]

Sequence[WrappedComponent]: A read-only copy of the UI components stored in this action row. To add/remove components to/from the action row, use its methods to directly modify it.

Changed in version 2.6: Returns an immutable sequence instead of a list.

append_item(item)[source]

Append a component to the action row. The component’s type must match that of the action row.

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

Parameters:

item (WrappedComponent) – The component to append to the action row.

Raises:

ValueError – The width of the action row exceeds 5.

insert_item(index, item)[source]

Insert a component to the action row at a given index. The component’s type must match that of the action row.

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

New in version 2.6.

Parameters:
  • index (int) – The index at which to insert the component into the action row.

  • item (WrappedComponent) – The component to insert into the action row.

Raises:

ValueError – The width of the action row exceeds 5.

add_button(index=None, *, style=<ButtonStyle.secondary: 2>, label=None, disabled=False, custom_id=None, url=None, emoji=None)[source]

Add a button to the action row. Can only be used if the action row holds message components.

To append a pre-existing Button use the append_item() method instead.

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

Changed in version 2.6: Now allows for inserting at a given index. The default behaviour of appending is preserved.

Parameters:
  • index (int) – The index at which to insert the button into the action row. If not provided, this method defaults to appending the button to the action row.

  • style (ButtonStyle) – The style of the button.

  • custom_id (Optional[str]) – The ID of the button that gets received during an interaction. If this button is for a URL, it does not have a custom ID.

  • url (Optional[str]) – The URL this button sends you to.

  • disabled (bool) – Whether the button is disabled or not.

  • label (Optional[str]) – The label of the button, if any.

  • emoji (Optional[Union[PartialEmoji, Emoji, str]]) – The emoji of the button, if available.

Raises:

ValueError – The width of the action row exceeds 5.

add_select(*, custom_id=..., placeholder=None, min_values=1, max_values=1, options=..., disabled=False)[source]

Add a select menu to the action row. Can only be used if the action row holds message components.

To append a pre-existing Select use the append_item() method instead.

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

Parameters:
  • custom_id (str) – The ID of the select menu that gets received during an interaction. If not given then one is generated for you.

  • placeholder (Optional[str]) – The placeholder text that is shown if nothing is selected, if any.

  • min_values (int) – The minimum number of items that must be chosen for this select menu. Defaults to 1 and must be between 1 and 25.

  • max_values (int) – The maximum number of items that must be chosen for this select menu. Defaults to 1 and must be between 1 and 25.

  • options (Union[List[disnake.SelectOption], List[str], Dict[str, str]]) – A list of options that can be selected in this menu. Use explicit SelectOptions for fine-grained control over the options. Alternatively, a list of strings will be treated as a list of labels, and a dict will be treated as a mapping of labels to values.

  • disabled (bool) – Whether the select is disabled or not.

Raises:

ValueError – The width of the action row exceeds 5.

add_text_input(*, label, custom_id, style=<TextInputStyle.short: 1>, placeholder=None, value=None, required=True, min_length=None, max_length=None)[source]

Add a text input to the action row. Can only be used if the action row holds modal components.

To append a pre-existing TextInput use the append_item() method instead.

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

New in version 2.4.

Parameters:
  • style (TextInputStyle) – The style of the text input.

  • label (str) – The label of the text input.

  • custom_id (str) – The ID of the text input that gets received during an interaction.

  • placeholder (Optional[str]) – The placeholder text that is shown if nothing is entered.

  • value (Optional[str]) – The pre-filled value of the text input.

  • required (bool) – Whether the text input is required. Defaults to True.

  • min_length (Optional[int]) – The minimum length of the text input.

  • max_length (Optional[int]) – The maximum length of the text input.

Raises:

ValueError – The width of the action row exceeds 5.

clear_items()[source]

Remove all components from the action row.

This function returns the class instance to allow for fluent-style chaining.

New in version 2.6.

remove_item(item)[source]

Remove a component from the action row.

This function returns the class instance to allow for fluent-style chaining.

New in version 2.6.

Parameters:

item (WrappedComponent) – The component to remove from the action row.

Raises:

ValueError – The component could not be found on the action row.

pop(index)[source]

Pop the component at the provided index from the action row.

New in version 2.6.

Parameters:

index (int) – The index at which to pop the component.

Raises:

IndexError – There is no component at the provided index.

classmethod with_modal_components()[source]

Create an empty action row meant to store components compatible with disnake.ui.Modal. Saves the need to import type specifiers to typehint empty action rows.

New in version 2.6.

Returns:

The newly created empty action row, intended for modal components.

Return type:

ActionRow

classmethod with_message_components()[source]

Create an empty action row meant to store components compatible with disnake.Message. Saves the need to import type specifiers to typehint empty action rows.

New in version 2.6.

Returns:

The newly created empty action row, intended for message components.

Return type:

ActionRow

classmethod rows_from_message(message, *, strict=True)[source]

Create a list of up to 5 action rows from the components on an existing message.

This will abide by existing component format on the message, including component ordering and rows. Components will be transformed to UI kit components, such that they can be easily modified and re-sent as action rows.

New in version 2.6.

Parameters:
  • message (disnake.Message) – The message from which to extract the components.

  • strict (bool) – Whether or not to raise an exception if an unknown component type is encountered.

Raises:

TypeError – Strict-mode is enabled and an unknown component type is encountered.

Returns:

The action rows parsed from the components on the message.

Return type:

List[ActionRow]

staticmethod for ... in walk_components(action_rows)[source]

Iterate over the components in a sequence of action rows, yielding each individual component together with the action row of which it is a child.

New in version 2.6.

Parameters:

action_rows (Sequence[ActionRow]) – The sequence of action rows over which to iterate.

Yields:

Tuple[ActionRow, WrappedComponent] – A tuple containing an action row and a component of that action row.

Item
Attributes
Methods
class disnake.ui.Item[source]

Represents the base UI item that all UI items inherit from.

This class adds more functionality on top of the WrappedComponent base class. This functionality mostly relates to disnake.ui.View.

The current UI items supported are:

New in version 2.0.

property view[source]

The underlying view for this item.

Type:

Optional[View]

await callback(interaction, /)[source]

This function is a coroutine.

The callback associated with this UI item.

This can be overriden by subclasses.

Parameters:

interaction (MessageInteraction) – The interaction that triggered this UI item.

WrappedComponent
class disnake.ui.WrappedComponent[source]

Represents the base UI component that all UI components inherit from.

The following classes implement this ABC:

New in version 2.4.

Button
Methods
class disnake.ui.Button(*, style=<ButtonStyle.secondary: 2>, label=None, disabled=False, custom_id=None, url=None, emoji=None, row=None)[source]

Represents a UI button.

New in version 2.0.

Parameters:
  • style (disnake.ButtonStyle) – The style of the button.

  • custom_id (Optional[str]) – The ID of the button that gets received during an interaction. If this button is for a URL, it does not have a custom ID.

  • url (Optional[str]) – The URL this button sends you to.

  • disabled (bool) – Whether the button is disabled.

  • label (Optional[str]) – The label of the button, if any.

  • emoji (Optional[Union[PartialEmoji, Emoji, str]]) – The emoji of the button, if available.

  • row (Optional[int]) – The relative row this button belongs to. A Discord component can only have 5 rows. By default, items are arranged automatically into those 5 rows. If you’d like to control the relative positioning of the row then passing an index is advised. For example, row=1 will show up before row=2. Defaults to None, which is automatic ordering. The row number must be between 0 and 4 (i.e. zero indexed).

property style[source]

The style of the button.

Type:

disnake.ButtonStyle

property custom_id[source]

The ID of the button that gets received during an interaction.

If this button is for a URL, it does not have a custom ID.

Type:

Optional[str]

property url[source]

The URL this button sends you to.

Type:

Optional[str]

await callback(interaction, /)[source]

This function is a coroutine.

The callback associated with this UI item.

This can be overriden by subclasses.

Parameters:

interaction (MessageInteraction) – The interaction that triggered this UI item.

property disabled[source]

Whether the button is disabled.

Type:

bool

property view[source]

The underlying view for this item.

Type:

Optional[View]

property label[source]

The label of the button, if available.

Type:

Optional[str]

property emoji[source]

The emoji of the button, if available.

Type:

Optional[PartialEmoji]

disnake.ui.button(cls=disnake.ui.Button, *, style=ButtonStyle.secondary, label=None, disabled=False, custom_id=..., url=None, emoji=None, row=None)[source]

A decorator that attaches a button to a component.

The function being decorated should have three parameters, self representing the disnake.ui.View, the disnake.ui.Button being pressed and the disnake.MessageInteraction you receive.

Note

Buttons with a URL cannot be created with this function. Consider creating a Button manually instead. This is because buttons with a URL do not have a callback associated with them since Discord does not do any processing with it.

Parameters:
  • cls (Type[Button]) –

    The button subclass to create an instance of. If provided, the following parameters described below do no apply. Instead, this decorator will accept the same keywords as the passed cls does.

    New in version 2.6.

  • label (Optional[str]) – The label of the button, if any.

  • custom_id (Optional[str]) – The ID of the button that gets received during an interaction. It is recommended not to set this parameter to prevent conflicts.

  • style (ButtonStyle) – The style of the button. Defaults to ButtonStyle.grey.

  • disabled (bool) – Whether the button is disabled. Defaults to False.

  • emoji (Optional[Union[str, Emoji, PartialEmoji]]) – The emoji of the button. This can be in string form or a PartialEmoji or a full Emoji.

  • row (Optional[int]) – The relative row this button belongs to. A Discord component can only have 5 rows. By default, items are arranged automatically into those 5 rows. If you’d like to control the relative positioning of the row then passing an index is advised. For example, row=1 will show up before row=2. Defaults to None, which is automatic ordering. The row number must be between 0 and 4 (i.e. zero indexed).

Select
class disnake.ui.Select(*, custom_id=..., placeholder=None, min_values=1, max_values=1, options=..., disabled=False, row=None)[source]

Represents a UI select menu.

This is usually represented as a drop down menu.

In order to get the selected items that the user has chosen, use Select.values.

New in version 2.0.

Parameters:
  • custom_id (str) – The ID of the select menu that gets received during an interaction. If not given then one is generated for you.

  • placeholder (Optional[str]) – The placeholder text that is shown if nothing is selected, if any.

  • min_values (int) – The minimum number of items that must be chosen for this select menu. Defaults to 1 and must be between 1 and 25.

  • max_values (int) – The maximum number of items that must be chosen for this select menu. Defaults to 1 and must be between 1 and 25.

  • options (Union[List[disnake.SelectOption], List[str], Dict[str, str]]) –

    A list of options that can be selected in this menu. Use explicit SelectOptions for fine-grained control over the options. Alternatively, a list of strings will be treated as a list of labels, and a dict will be treated as a mapping of labels to values.

    Changed in version 2.5: Now also accepts a list of str or a dict of str to str, which are then appropriately parsed as SelectOption labels and values.

  • disabled (bool) – Whether the select is disabled.

  • row (Optional[int]) – The relative row this select menu belongs to. A Discord component can only have 5 rows. By default, items are arranged automatically into those 5 rows. If you’d like to control the relative positioning of the row then passing an index is advised. For example, row=1 will show up before row=2. Defaults to None, which is automatic ordering. The row number must be between 0 and 4 (i.e. zero indexed).

property custom_id[source]

The ID of the select menu that gets received during an interaction.

Type:

str

property placeholder[source]

The placeholder text that is shown if nothing is selected, if any.

Type:

Optional[str]

property min_values[source]

The minimum number of items that must be chosen for this select menu.

Type:

int

property max_values[source]

The maximum number of items that must be chosen for this select menu.

Type:

int

property options[source]

A list of options that can be selected in this select menu.

Type:

List[disnake.SelectOption]

add_option(*, label, value=..., description=None, emoji=None, default=False)[source]

Adds an option to the select menu.

To append a pre-existing SelectOption use the append_option() method instead.

Parameters:
  • label (str) – The label of the option. This is displayed to users. Can only be up to 100 characters.

  • value (str) – The value of the option. This is not displayed to users. If not given, defaults to the label. Can only be up to 100 characters.

  • description (Optional[str]) – An additional description of the option, if any. Can only be up to 100 characters.

  • emoji (Optional[Union[str, Emoji, PartialEmoji]]) – The emoji of the option, if available. This can either be a string representing the custom or unicode emoji or an instance of PartialEmoji or Emoji.

  • default (bool) – Whether this option is selected by default.

Raises:

ValueError – The number of options exceeds 25.

append_option(option)[source]

Appends an option to the select menu.

Parameters:

option (disnake.SelectOption) – The option to append to the select menu.

Raises:

ValueError – The number of options exceeds 25.

await callback(interaction, /)[source]

This function is a coroutine.

The callback associated with this UI item.

This can be overriden by subclasses.

Parameters:

interaction (MessageInteraction) – The interaction that triggered this UI item.

property view[source]

The underlying view for this item.

Type:

Optional[View]

property disabled[source]

Whether the select menu is disabled.

Type:

bool

property values[source]

A list of values that have been selected by the user.

Type:

List[str]

is_dispatchable()[source]

Whether the select menu is dispatchable. This will always return True.

Return type:

bool

disnake.ui.select(cls=disnake.ui.Select, *, custom_id=..., placeholder=None, min_values=1, max_values=1, options=..., disabled=False, row=None)[source]

A decorator that attaches a select menu to a component.

The function being decorated should have three parameters, self representing the disnake.ui.View, the disnake.ui.Select being pressed and the disnake.MessageInteraction you receive.

In order to get the selected items that the user has chosen within the callback use Select.values.

Parameters:
  • cls (Type[Select]) –

    The select subclass to create an instance of. If provided, the following parameters described below do no apply. Instead, this decorator will accept the same keywords as the passed cls does.

    New in version 2.6.

  • placeholder (Optional[str]) – The placeholder text that is shown if nothing is selected, if any.

  • custom_id (str) – The ID of the select menu that gets received during an interaction. It is recommended not to set this parameter to prevent conflicts.

  • row (Optional[int]) – The relative row this select menu belongs to. A Discord component can only have 5 rows. By default, items are arranged automatically into those 5 rows. If you’d like to control the relative positioning of the row then passing an index is advised. For example, row=1 will show up before row=2. Defaults to None, which is automatic ordering. The row number must be between 0 and 4 (i.e. zero indexed).

  • min_values (int) – The minimum number of items that must be chosen for this select menu. Defaults to 1 and must be between 1 and 25.

  • max_values (int) – The maximum number of items that must be chosen for this select menu. Defaults to 1 and must be between 1 and 25.

  • options (Union[List[disnake.SelectOption], List[str], Dict[str, str]]) –

    A list of options that can be selected in this menu. Use explicit SelectOptions for fine-grained control over the options. Alternatively, a list of strings will be treated as a list of labels, and a dict will be treated as a mapping of labels to values.

    Changed in version 2.5: Now also accepts a list of str or a dict of str to str, which are then appropriately parsed as SelectOption labels and values.

  • disabled (bool) – Whether the select is disabled. Defaults to False.

TextInput
class disnake.ui.TextInput(*, label, custom_id, style=<TextInputStyle.short: 1>, placeholder=None, value=None, required=True, min_length=None, max_length=None)[source]

Represents a UI text input.

This can only be used in a Modal.

New in version 2.4.

Parameters:
  • label (str) – The label of the text input.

  • custom_id (str) – The ID of the text input that gets received during an interaction.

  • style (TextInputStyle) – The style of the text input.

  • placeholder (Optional[str]) – The placeholder text that is shown if nothing is entered.

  • value (Optional[str]) – The pre-filled value of the text input.

  • required (bool) – Whether the text input is required. Defaults to True.

  • min_length (Optional[int]) – The minimum length of the text input.

  • max_length (Optional[int]) – The maximum length of the text input.

property style[source]

The style of the text input.

Type:

TextInputStyle

property label[source]

The label of the text input.

Type:

str

property custom_id[source]

The ID of the text input that gets received during an interaction.

Type:

str

property placeholder[source]

The placeholder text that is shown if nothing is entered.

Type:

Optional[str]

property value[source]

The pre-filled text of the text input.

Type:

Optional[str]

property required[source]

Whether the text input is required.

Type:

bool

property min_length[source]

The minimum length of the text input.

Type:

Optional[int]

property max_length[source]

The maximum length of the text input.

Type:

Optional[int]

Localization

The library uses the following types/methods to support localization.

Localized
class disnake.Localized(string=None, *, key=..., data=...)[source]

A container type used for localized parameters.

Exactly one of key or data must be provided.

There is an alias for this called Localised.

New in version 2.5.

Parameters:
  • string (Optional[str]) – The default (non-localized) value of the string. Whether this is optional or not depends on the localized parameter type.

  • key (str) – A localization key used for lookups. Incompatible with data.

  • data (Union[Dict[Locale, str], Dict[str, str]]) – A mapping of locales to localized values. Incompatible with key.

LocalizationValue
class disnake.LocalizationValue(localizations)[source]

Container type for (pending) localization data.

New in version 2.5.

property data[source]

A dict with a locale -> localization mapping, if available.

Type:

Optional[Dict[str, str]]

LocalizationProtocol
class disnake.LocalizationProtocol[source]

Manages a key-value mapping of localizations.

This is an abstract class, a concrete implementation is provided as LocalizationStore.

New in version 2.5.

abstractmethod get(key)[source]

Returns localizations for the specified key.

Parameters:

key (str) – The lookup key.

Raises:

LocalizationKeyError – May be raised if no localizations for the provided key were found, depending on the implementation.

Returns:

The localizations for the provided key. May return None if no localizations could be found.

Return type:

Optional[Dict[str, str]]

load(path)[source]

Adds localizations from the provided path.

Parameters:

path (Union[str, os.PathLike]) – The path to the file/directory to load.

Raises:

RuntimeError – The provided path is invalid or couldn’t be loaded

reload()[source]

Clears localizations and reloads all previously loaded sources again. If an exception occurs, the previous data gets restored and the exception is re-raised.

LocalizationStore
class disnake.LocalizationStore(*, strict)[source]

Manages a key-value mapping of localizations using .json files.

New in version 2.5.

strict

Specifies whether get() raises an exception if localizations for a provided key couldn’t be found.

Type:

bool

get(key)[source]

Returns localizations for the specified key.

Parameters:

key (str) – The lookup key.

Raises:

LocalizationKeyError – No localizations for the provided key were found. Raised only if strict is enabled, returns None otherwise.

Returns:

The localizations for the provided key. Returns None if no localizations could be found and strict is disabled.

Return type:

Optional[Dict[str, str]]

load(path)[source]

Adds localizations from the provided path to the store. If the path points to a file, the file gets loaded. If it’s a directory, all .json files in that directory get loaded (non-recursive).

Parameters:

path (Union[str, os.PathLike]) – The path to the file/directory to load.

Raises:

RuntimeError – The provided path is invalid or couldn’t be loaded

reload()[source]

Clears localizations and reloads all previously loaded files/directories again. If an exception occurs, the previous data gets restored and the exception is re-raised. See load() for possible raised exceptions.

Exceptions

The following exceptions are thrown by the library.

exception disnake.DiscordException[source]

Base exception class for disnake.

Ideally speaking, this could be caught to handle any exceptions raised from this library.

exception disnake.ClientException[source]

Exception that’s raised when an operation in the Client fails.

These are usually for exceptions that happened due to user input.

exception disnake.LoginFailure[source]

Exception that’s raised when the Client.login() function fails to log you in from improper credentials or some other misc. failure.

exception disnake.NoMoreItems[source]

Exception that is raised when an async iteration operation has no more items.

exception disnake.HTTPException(response, message)[source]

Exception that’s raised when an HTTP request operation fails.

response

The response of the failed HTTP request. This is an instance of aiohttp.ClientResponse. In some cases this could also be a requests.Response.

Type:

aiohttp.ClientResponse

text

The text of the error. Could be an empty string.

Type:

str

status

The status code of the HTTP request.

Type:

int

code

The Discord specific error code for the failure.

Type:

int

exception disnake.Forbidden(response, message)[source]

Exception that’s raised for when status code 403 occurs.

Subclass of HTTPException.

exception disnake.NotFound(response, message)[source]

Exception that’s raised for when status code 404 occurs.

Subclass of HTTPException.

exception disnake.DiscordServerError(response, message)[source]

Exception that’s raised for when a 500 range status code occurs.

Subclass of HTTPException.

New in version 1.5.

exception disnake.InvalidData[source]

Exception that’s raised when the library encounters unknown or invalid data from Discord.

exception disnake.WebhookTokenMissing[source]

Exception that’s raised when a Webhook or SyncWebhook is missing a token to make requests with.

New in version 2.6.

exception disnake.GatewayNotFound[source]

An exception that is raised when the gateway for Discord could not be found

exception disnake.ConnectionClosed(socket, *, shard_id, code=None)[source]

Exception that’s raised when the gateway connection is closed for reasons that could not be handled internally.

code

The close code of the websocket.

Type:

int

reason

The reason provided for the closure.

Type:

str

shard_id

The shard ID that got closed if applicable.

Type:

Optional[int]

exception disnake.PrivilegedIntentsRequired(shard_id)[source]

Exception that’s raised when the gateway is requesting privileged intents but they’re not ticked in the developer page yet.

Go to https://discord.com/developers/applications/ and enable the intents that are required. Currently these are as follows:

shard_id

The shard ID that got closed if applicable.

Type:

Optional[int]

exception disnake.SessionStartLimitReached(session_start_limit, requested=1)[source]

Exception that’s raised when Client.connect() function fails to connect to Discord due to the session start limit being reached.

New in version 2.6.

session_start_limit

The current state of the session start limit.

Type:

SessionStartLimit

exception disnake.InteractionException[source]

Exception that’s raised when an interaction operation fails

New in version 2.0.

interaction

The interaction that was responded to.

Type:

Interaction

exception disnake.InteractionResponded(interaction)[source]

Exception that’s raised when sending another interaction response using InteractionResponse when one has already been done before.

An interaction can only be responded to once.

New in version 2.0.

interaction

The interaction that’s already been responded to.

Type:

Interaction

exception disnake.InteractionNotResponded(interaction)[source]

Exception that’s raised when editing an interaction response without sending a response message first.

An interaction must be responded to exactly once.

New in version 2.0.

interaction

The interaction that hasn’t been responded to.

Type:

Interaction

exception disnake.InteractionTimedOut(interaction)[source]

Exception that’s raised when an interaction takes more than 3 seconds to respond but is not deferred.

New in version 2.0.

interaction

The interaction that was responded to.

Type:

Interaction

exception disnake.ModalChainNotSupported(interaction)[source]

Exception that’s raised when responding to a modal with another modal.

New in version 2.4.

interaction

The interaction that was responded to.

Type:

ModalInteraction

exception disnake.LocalizationKeyError(key)[source]

Exception that’s raised when a localization key lookup fails.

New in version 2.5.

key

The localization key that couldn’t be found.

Type:

str

exception disnake.opus.OpusError(code)[source]

An exception that is thrown for libopus related errors.

code

The error code returned.

Type:

int

exception disnake.opus.OpusNotLoaded[source]

An exception that is thrown for when libopus is not loaded.

Exception Hierarchy

Warnings

class disnake.DiscordWarning[source]

Base warning class for disnake.

New in version 2.3.

class disnake.ConfigWarning[source]

Warning class related to configuration issues.

New in version 2.3.

class disnake.SyncWarning[source]

Warning class for application command synchronization issues.

New in version 2.3.

class disnake.LocalizationWarning[source]

Warning class for localization issues.

New in version 2.5.

Warning Hierarchy

Meta

If you’re looking for something related to the project itself, it’s here.

Changelog

This page keeps a detailed human friendly rendering of what’s new and changed in specific versions.

v2.6.3

This maintainence release contains backports from v2.8.0.

Bug Fixes

v2.6.2

Bug Fixes

v2.6.1

Bug Fixes
  • Ensure that embed fields are copied properly by Embed.copy() and that the copied embed is completely separate from the original one. (#792)

  • Fix an issue with Member.ban() erroring when the delete_message_days parameter was provided. (#810)

v2.6.0

This release adds support for new forum channel features (like tags) as well as auto moderation, among other things. See below for more.

Also note the breaking changes listed below, which may require additional code changes.

Breaking Changes
Deprecations
  • EmptyEmbed and Embed.Empty are deprecated in favor of None, have been removed from the documentation, and will result in type-checking errors. (#435, #768)

  • The delete_message_days parameter of Guild.ban() and Member.ban() is deprecated in favour of clean_history_duration. (#659)

  • [ext.commands] Using command_prefix=None with Bot is now deprecated in favour of InteractionBot. (#689)

New Features
Bug Fixes
  • Update incorrect channel edit method annotations. (#418)
    • Fix sync_permissions parameter type.

    • Remove topic parameter from StageChannel.edit(), add bitrate.

  • Properly close sockets when receiving a voice server update event. (#488)

  • Warn the user that bools are not supported for default_member_permissions. (#520)

  • Update the Guild Iterator to not get stuck in an infinite loop. (#526)
    • Add a missing import for the scheduled event user iterator.

  • Change the default guild GuildSticker limit to 5. (#531)

  • Handle optional Locale instances (no longer create an enum value). (#533)

  • Update the type field handling for audit logs. (#535)
  • Dispatch disnake.on_reaction_remove() for Thread instances. (#536)

  • Update Guild.bitrate_limit to use the correct value for the VIP_REGIONS feature flag. (#538)

  • Handle ThreadAutoArchiveDuration instances for default_auto_archive_duration when editing channels. (#568)

  • Assume that None is an empty channel name and keep channel.name a string. (#569)

  • Remove the $ prefix from IDENTIFY payload properties. (#572)

  • Replace old application command objects in cogs with the new/copied objects. (#575)

  • Fix opus function calls on arm64 macOS. (#620)

  • Improve channel/guild fallback in resolved interaction data, using PartialMessageable for unhandled/unknown channels instead of using None. (#646)

  • Check the type of the provided parameter when validating names to improve end-user errors when passing an incorrect object to slash command and option names. (#653)

  • Make the ext.commands.default_member_permissions() decorator always work in cogs. (#678)

  • Fix Spotify.start, Spotify.end, Spotify.duration raising KeyError instead of returning None, improve activity typing. (#685)

  • Fixes message initialization failing with threads and no intents by explicitly checking we have a guild object where one is required. (#699, #712)

  • Fixed an issue where it would be possible to remove other features when enabling or disabling the COMMUNITY feature for a Guild. (#705)

  • Fix invalid widget fields. (#736)
  • No longer use deprecated @! syntax for mentioning users. (#743)

  • Fix creation of forum threads without Permissions.manage_threads. (#746)

  • Don’t count initial message in forum threads towards Thread.message_count and Thread.total_message_sent. (#747)

  • [ext.commands] Handle VoiceChannel in commands.is_nsfw(). (#536)

  • [ext.commands] Handle Union[User, Member] annotations on slash commands arguments when using the decorator interface. (#584)

  • [ext.commands] Change has_permissions and bot_has_permissions checks to work with interations in guilds that only added the applications.commands scope, and in DMs. (#673)

  • [ext.commands] Fix edge case with parsing command annotations that contain a union of non-type objects, like Optional[Literal[1, 2, 3]]. (#770)

Documentation
Miscellaneous
  • Refactor the test bot to be easier to use for all users. (#247)

  • Refactor channel edit overloads and internals, improving typing. (#418)

  • Run pyright on examples and fix any typing issues uncovered by this change. (#519)

  • Add initial testing framework. (#529)

  • Explicitly type activity types with literal return values. (#543)

  • Explicitly type channel types with literal return values. (#543)

  • Update PyPI url and minor wording in the README. (#556)

  • Add flake8 as our linter. (#557)

  • Update pyright to 1.1.254. (#559)

  • Add generic parameters to user/message command decorators. (#563)
    • Update default parameter type to improve compatibilty with callable/dynamic defaults.

  • Run docs creation in GitHub actions to test for warnings before a pull is merged. (#564)

  • Add more typing overrides to GuildCommandInteraction. (#580)

  • Rework internal typings for interaction payloads. (#588)

  • Add typings for all gateway payloads. (#594)

  • Add towncrier and sphinxcontrib-towncrier to manage changelogs. (#600)
    • Use towncrier for changelog management.

    • Use sphinxcontrib-towncrier to build changelogs for the in-development documentation.

  • Expand contributing documentation to include more information on creating pull requests and writing features. (#601)

  • Add flake8-comprehensions for catching inefficient comphrehensions. (#602)

  • Resolve minor flake8 issues. (#606)
    • Don’t use star imports except in __init__.py files.

    • Don’t use ambigious variable names.

    • Don’t use setattr and getattr with constant variable names.

  • Add flake8-pytest-style for linting pytest specific features with flake8. (#608)

  • Replace all TypeVar instances with typing_extensions.Self across the entire library where possible. (#610)

  • Remove the internal fill_with_flags decorator for flags classes and use the built in object.__init_subclass__() method. (#616, #660)

  • Add slice to ui.ActionRow __getattr__ and __delattr__ annotations. (#624)

  • Update and standardise all internal Snowflake regexes to match between 17 and 19 characters (inclusive). (#651)

  • Rename internal module disnake.ext.commands.flags to disnake.ext.commands.flag_converter. (#667)

  • Improve parallel documentation build speed. (#690)

  • Limit installation of cchardet in the [speed] extra to Python versions below 3.10 (see aiohttp#6857). (#702)

  • Update annotation and description of options parameter of ui.ActionRow.add_select to match ui.Select. (#744)

  • Update typings to explicitly specify optional types for parameters with a None default. (#751)

  • Adopt SPDX License Headers across all project files. (#756)

v2.5.3

This is a maintenance release with backports from v2.6.0.

Bug Fixes
Miscellaneous
  • Limit installation of cchardet in the [speed] extra to Python versions below 3.10 (see aiohttp#6857). (#772)

v2.5.2

This release is a bugfix release with backports from upto v2.6.0.

Bug Fixes
  • Warn the user that bools are not supported for default_member_permissions. (#520)

  • Update the Guild Iterator to not get stuck in an infinite loop. (#526)
    • Add a missing import for the scheduled event user iterator.

  • Change the default guild GuildSticker limit to 5. (#531)

  • Handle optional Locale instances (no longer create an enum value). (#533)

  • [ext.commands] Handle VoiceChannel in commands.is_nsfw(). (#536)

  • Dispatch disnake.on_reaction_remove() for Thread instances. (#536)

  • Update Guild.bitrate_limit to use the correct value for the VIP_REGIONS feature flag. (#538)

  • Make all *InteractionData dataclasses dicts (MessageInteractionData, ApplicationCommandInteractionData, and so on). (#549)

  • Handle ThreadAutoArchiveDuration instances for default_auto_archive_duration when editing channels. (#568)

  • Assume that None is an empty channel name and keep channel.name a string. (#569)

  • Remove the $ prefix from IDENTIFY payload properties. (#572)

  • Replace old application command objects in cogs with the new/copied objects. (#575)

  • [ext.commands] Handle Union[User, Member] annotations on slash commands arguments when using the decorator interface. (#584)

  • Fix opus function calls on arm64 macOS. (#620)

  • Improve channel/guild fallback in resolved interaction data, using PartialMessageable for unhandled/unknown channels instead of using None. (#646)

Documentation

v2.5.1

Bug Fixes

v2.5.0

This version adds support for API v10 (which comes with a few breaking changes), forum channels, localizations, permissions v2, improves API coverage by adding support for previously missing features like guild previews, widgets, or welcome screens, and contains several miscellaneous enhancements and bugfixes.

Regarding the message content intent: Note that earlier versions will continue working fine after the message content intent deadline (August 31st 2022), as long as the intent is enabled in the developer portal. However, from this version (2.5.0) onward, the intent needs to be enabled in the developer portal and your code. See this page of the guide for more information. If you do not have access to the intent yet, you can temporarily continue using API v9 by calling disnake.http._workaround_set_api_version(9) before connecting, which will keep sending message content before the intent deadline, even with the intent disabled.

Breaking Changes
  • The message_content intent is now required to receive message content and related fields, see above (#353)

  • The new permissions v2 system revamped application command permissions, with the most notable changes being the removal of default_permission and commands.guild_permissions in favor of new fields/methods - see below for all new changes (#405)

  • TextChannel.create_thread() now requires either a message or a type parameter (#355)

  • GuildScheduledEvent.fetch_users() and Guild.bans() now return an async iterator instead of a list of users (#428, #442)

  • Guild.audit_logs() no longer supports the oldest_first parameter (#473)

  • Store channels have been removed as they’re not supported by Discord any longer (#438)

  • on_thread_join() will no longer be invoked when a new thread is created, see on_thread_create() (#445)

  • The voice region enum was replaced with a generic VoiceRegion data class (#477)

  • locale attributes are now of type Locale instead of str (#439)

  • Invite.revoked and Thread.archiver_id have been removed (deprecated in 2.4) (#455)

  • Slash command names and option names are no longer automatically converted to lowercase, an InvalidArgument exception is now raised instead (#422)

  • The interaction parameter of ui.Item.callback() can no longer be passed as a kwarg (#311)

  • The youtube, awkword and sketchy_artist PartyTypes no longer work and have been removed (#408, #409)

  • Trying to defer an interaction response that does not support deferring (e.g. autocomplete) will now raise a TypeError (#505)

  • [ext.commands] Failure to convert an input parameter annotated as LargeInt now raises a LargeIntConversionFailure (#362)

Deprecations
New Features
Bug Fixes
Documentation
Miscellaneous
  • Fix remaining pyright issues, add pyright CI (#311, #387, #514)

  • Update dev dependencies and CI (#345, #386, #451)

  • Improve _WebhookState typing (#391)

  • Improve basic_bot.py example (#399)

  • Add low-level component example (#452)

  • Update Discord server invite links (#476)

v2.4.1

This release is a bugfix release with backports from v2.5.0 up to v2.5.2.

Bug Fixes
Documentation
  • Update the requests intersphinx url to the new url of the requests documentation. (#539)

Miscellaneous
  • Update dev dependencies and CI (#451)

v2.4.0

This version contains many new features, including attachment options, modals, and the ability to directly send message components without views, as well as several fixes and other general improvements.

Breaking Changes
  • The constructor of ApplicationCommand and its subtypes no longer accepts **kwargs for setting internal values (#249)
    • This shouldn’t affect anyone, as **kwargs was only used for setting fields returned by the API and had no effect if the user set them

  • Interaction.permissions now returns proper permission values in DMs (#321)

  • The reason parameter for sticker endpoints in HTTPClient is now kwarg-only

Deprecations
  • Thread.archiver_id is not being provided by the API anymore and will be removed in a future version (#295)

  • Invite.revoked is not being provided by the API anymore and will be removed in a future version (#309)

New Features
Bug Fixes
Documentation
  • Show tooltips when hovering over links (#236, #242)

  • General content improvements/adjustments (#275)

  • Slight redesign and general layout improvements (#278)

Miscellaneous
  • Improve examples (#209, #262, #270, #307, #332, #341)

  • Improve typing/annotations of several parts of the library (#249, #256, #263, #279, #292, #299, #308)

  • Add additional pre-commit hooks for development (#233)

  • Add taskipy for development (#234)

  • Improve member deserialization (#304)

  • Split application command objects into separate types for data returned by the API (#299)

  • Update README banner (#343)

v2.3.2

Bug Fixes
  • Fix invalid default value for application command option descriptions (#338)

v2.3.1

Bug Fixes
Documentation
  • Fix guild_permissions() documentation

  • Fix missing dropdown icon (#235)

Miscellaneous
  • Add isort and black pre-commit hooks, run isort (#169, #173, #233)

  • Rename tests directory (#232)

v2.3.0

This version contains several new features and fixes, notably support for guild scheduled events, guild timeouts, and a slash command rework with parameter injections, as well as several documentation fixes.

Note: the Version Guarantees have been updated to more accurately reflect the versioning scheme this library is following.

Breaking Changes
  • The supported aiohttp version range changed from >=3.6.0,<3.8.0 to >=3.7.0,<3.9.0

  • Due to the upcoming text-in-voice feature (not yet released at the time of writing), many methods/properties that previously returned a TextChannel can now also return a VoiceChannel, which shares many but not all of its methods. Also see the details for text-in-voice under “New Features” below, which include a few important things to note.

  • Slash command internals have undergone an extensive rework, and while existing code should still work as before, it is recommended that you do some testing using the new implementation first

  • Bot.get_slash_command may now also return SubCommandGroup or SubCommand instances, see documentation

  • disnake.types.ThreadArchiveDuration is now ThreadArchiveDurationLiteral, to avoid confusion with the new ThreadArchiveDuration enum

Deprecations
  • The role_ids and user_ids parameters for guild_permissions are now roles and users respectively; the old parameter names will be removed in a future version

New Features
Bug Fixes
  • Fix dispatch of typing events in DMs (#176)

  • Try to retrieve objects in received interactions from cache first (fixing properties like Member.status on member parameters for commands) (#182, #213)

  • Fix return type annotation of ui.button() and ui.select() decorators (#163)

  • Fix incorrect URL returned by Template.url

  • Fix sending local files in embeds with interactions/webhooks if only one embed was specified (#193)

  • Fix leftover uses of json, which didn’t use orjson if available (#184)

  • Fix Message.channel type being DMChannel for ephemeral messages in on_message() (#197)

  • Fix command/option name validation (#210)

  • Always close files after completing HTTP requests (#124)

  • [ext.commands] Fix unnecessary application command sync without changes

  • [ext.commands] Fix incorrect detection of deprecated guild commands in sync algorithm while sync is in progress (#205)

Documentation
Miscellaneous
  • Add Python 3.10 to package classifiers (#127)

  • Change supported aiohttp version range from >=3.6.0,<3.8.0 to >=3.7.0,<3.9.0 (#119, #164)

  • Add guide for configuring inviting a bot through its profile (#153)

  • Rewrite project README (#191)

  • Improve examples (#143)

v2.2.3

Bug Fixes
  • Fix invalid default value for application command option descriptions (#338)

v2.2.2

Bug Fixes
  • Fix channel conversion in audit log entries

  • Fix improper error handling in context menu commands

  • Supply ApplicationCommandInteraction.application_command in autocomplete callbacks

  • Fix Select.append_option not raising an error if 25 options have already been added

  • Improve check for options parameter on slash commands and subcommands

  • Improve parameter parsing for converters

  • Fix warning related to new option properties

Documentation

v2.2.1

Bug Fixes
  • Fixed error related to guild member count

v2.2.0

New Features

v2.1.5

New Features
Bug Fixes
  • Command deletions on reconnections

  • Pending sync tasks on loop termination

v2.1.4

Bug Fixes
  • Fixed some issues with application command permissions synchronisation

v2.1.3

New Features
Bug Fixes
  • Music

  • default_permission kwarg in user / message commands

  • Commands no longer sync during the loop termination

v2.1.2

This is the first stable version of this discord.py 2.0 fork.

New Features

v1.7.3

Bug Fixes

v1.7.2

Bug Fixes

v1.7.1

Bug Fixes

v1.7.0

This version is mainly for improvements and bug fixes. This is more than likely the last major version in the 1.x series. Work after this will be spent on v2.0. As a result, this is the last version to support Python 3.5. Likewise, this is the last version to support user bots.

Development of v2.0 will have breaking changes and support for newer API features.

New Features
Bug Fixes
Miscellaneous
  • User endpoints and all userbot related functionality has been deprecated and will be removed in the next major version of the library.

  • Permission class methods were updated to match the UI of the Discord client (#6476)

  • _ and - characters are now stripped when making a new cog using the disnake package (#6313)

v1.6.0

This version comes with support for replies and stickers.

New Features
Bug Fixes
Miscellaneous

v1.5.1

Bug Fixes
  • Fix utils.escape_markdown() not escaping quotes properly (#5897)

  • Fix Message not being hashable (#5901, #5866)

  • Fix moving channels to the end of the channel list (#5923)

  • Fix seemingly strange behaviour in __eq__ for PermissionOverwrite (#5929)

  • Fix aliases showing up in __iter__ for Intents (#5945)

  • Fix the bot disconnecting from voice when moving them to another channel (#5904)

  • Fix attribute errors when chunking times out sometimes during delayed on_ready dispatching.

  • Ensure that the bot’s own member is not evicted from the cache (#5949)

Miscellaneous
  • Members are now loaded during GUILD_MEMBER_UPDATE events if MemberCacheFlags.joined is set. (#5930)

  • [ext.commands] MemberConverter now properly lazily fetches members if not available from cache.
    • This is the same as having disnake.Member as the type-hint.

  • Guild.chunk() now allows concurrent calls without spamming the gateway with requests.

v1.5.0

This version came with forced breaking changes that Discord is requiring all bots to go through on October 7th. It is highly recommended to read the documentation on intents, A Primer to Gateway Intents.

API Changes
  • Members and presences will no longer be retrieved due to an API change. See Privileged Intents for more info.

  • As a consequence, fetching offline members is disabled if the members intent is not enabled.

New Features
Bug Fixes
  • Fix issue with Guild.by_category() not showing certain channels.

  • Fix abc.GuildChannel.permissions_synced always being False (#5772)

  • Fix handling of cloudflare bans on webhook related requests (#5221)

  • Fix cases where a keep-alive thread would ack despite already dying (#5800)

  • Fix cases where a Member reference would be stale when cache is disabled in message events (#5819)

  • Fix allowed_mentions not being sent when sending a single file (#5835)

  • Fix overwrites being ignored in abc.GuildChannel.edit() if {} is passed (#5756, #5757)

  • [ext.commands] Fix exceptions being raised improperly in command invoke hooks (#5799)

  • [ext.commands] Fix commands not being properly ejected during errors in a cog injection (#5804)

  • [ext.commands] Fix cooldown timing ignoring edited timestamps.

  • [ext.tasks] Fix tasks extending the next iteration on handled exceptions (#5762, #5763)

Miscellaneous
  • Webhook requests are now logged (#5798)

  • Remove caching layer from AutoShardedClient.shards. This was causing issues if queried before launching shards.

  • Gateway rate limits are now handled.

  • Warnings logged due to missed caches are now changed to DEBUG log level.

  • Some strings are now explicitly interned to reduce memory usage.

  • Usage of namedtuples has been reduced to avoid potential breaking changes in the future (#5834)

  • [ext.commands] All BadArgument exceptions from the built-in converters now raise concrete exceptions to better tell them apart (#5748)

  • [ext.tasks] Lazily fetch the event loop to prevent surprises when changing event loop policy (#5808)

v1.4.2

This is a maintenance release with backports from v1.5.0.

Bug Fixes
  • Fix issue with Guild.by_category() not showing certain channels.

  • Fix abc.GuildChannel.permissions_synced always being False (#5772)

  • Fix handling of cloudflare bans on webhook related requests (#5221)

  • Fix cases where a keep-alive thread would ack despite already dying (#5800)

  • Fix cases where a Member reference would be stale when cache is disabled in message events (#5819)

  • Fix allowed_mentions not being sent when sending a single file (#5835)

  • Fix overwrites being ignored in abc.GuildChannel.edit() if {} is passed (#5756, #5757)

  • [ext.commands] Fix exceptions being raised improperly in command invoke hooks (#5799)

  • [ext.commands] Fix commands not being properly ejected during errors in a cog injection (#5804)

  • [ext.commands] Fix cooldown timing ignoring edited timestamps.

  • [ext.tasks] Fix tasks extending the next iteration on handled exceptions (#5762, #5763)

Miscellaneous
  • Remove caching layer from AutoShardedClient.shards. This was causing issues if queried before launching shards.

  • [ext.tasks] Lazily fetch the event loop to prevent surprises when changing event loop policy (#5808)

v1.4.1

Bug Fixes
  • Properly terminate the connection when Client.close() is called (#5207)

  • Fix error being raised when clearing embed author or image when it was already cleared (#5210, #5212)

  • Fix __path__ to allow editable extensions (#5213)

v1.4.0

Another version with a long development time. Features like Intents are slated to be released in a v1.5 release. Thank you for your patience!

New Features
Bug Fixes
Miscellaneous

v1.3.4

Bug Fixes
  • Fix an issue with channel overwrites causing multiple issues including crashes (#5109)

v1.3.3

Bug Fixes
  • Change default WS close to 4000 instead of 1000.
    • The previous close code caused sessions to be invalidated at a higher frequency than desired.

  • Fix None appearing in Member.activities. (#2619)

v1.3.2

Another minor bug fix release.

Bug Fixes
  • Higher the wait time during the GUILD_CREATE stream before on_ready is fired for AutoShardedClient.

  • on_voice_state_update() now uses the inner member payload which should make it more reliable.

  • Fix various Cloudflare handling errors (#2572, #2544)

  • Fix crashes if Message.guild is Object instead of Guild.

  • Fix Webhook.send() returning an empty string instead of None when wait=False.

  • Fix invalid format specifier in webhook state (#2570)

  • [ext.commands] Passing invalid permissions to permission related checks now raises TypeError.

v1.3.1

Minor bug fix release.

Bug Fixes
  • Fix fetching invites in guilds that the user is not in.

  • Fix the channel returned from Client.fetch_channel() raising when sending messages. (#2531)

Miscellaneous
  • Fix compatibility warnings when using the Python 3.9 alpha.

  • Change the unknown event logging from WARNING to DEBUG to reduce noise.

v1.3.0

This version comes with a lot of bug fixes and new features. It’s been in development for a lot longer than was anticipated!

New Features
Bug Fixes
Miscellaneous
  • The library now fully supports Python 3.8 without warnings.

  • Bump the dependency of websockets to 8.0 for those who can use it. (#2453)

  • Due to Discord providing Member data in mentions, users will now be upgraded to Member more often if mentioned.

  • utils.escape_markdown() now properly escapes new quote markdown.

  • The message cache can now be disabled by passing None to max_messages in Client.

  • The default message cache size has changed from 5000 to 1000 to accommodate small bots.

  • Lower memory usage by only creating certain objects as needed in Role.

  • There is now a sleep of 5 seconds before re-IDENTIFYing during a reconnect to prevent long loops of session invalidation.

  • The rate limiting code now uses millisecond precision to have more granular rate limit handling.
    • Along with that, the rate limiting code now uses Discord’s response to wait. If you need to use the system clock again for whatever reason, consider passing assume_synced_clock in Client.

  • The performance of Guild.default_role has been improved from O(N) to O(1). (#2375)

  • The performance of Member.roles has improved due to usage of caching to avoid surprising performance traps.

  • The GC is manually triggered during things that cause large deallocations (such as guild removal) to prevent memory fragmentation.

  • There have been many changes to the documentation for fixes both for usability, correctness, and to fix some linter errors. Thanks to everyone who contributed to those.

  • The loading of the opus module has been delayed which would make the result of opus.is_loaded() somewhat surprising.

  • [ext.commands] Usernames prefixed with @ inside DMs will properly convert using the User converter. (#2498)

  • [ext.tasks] The task sleeping time will now take into consideration the amount of time the task body has taken before sleeping. (#2516)

v1.2.5

Bug Fixes
  • Fix a bug that caused crashes due to missing animated field in Emoji structures in reactions.

v1.2.4

Bug Fixes

v1.2.3

Bug Fixes

v1.2.2

Bug Fixes
  • Audit log related attribute access have been fixed to not error out when they shouldn’t have.

v1.2.1

Bug Fixes
  • User.avatar_url and related attributes no longer raise an error.

  • More compatibility shims with the enum.Enum code.

v1.2.0

This update mainly brings performance improvements and various nitro boosting attributes (referred to in the API as “premium guilds”).

New Features
Bug Fixes
Miscellaneous
  • Improve performance of all Enum related code significantly.
    • This was done by replacing the enum.Enum code with an API compatible one.

    • This should not be a breaking change for most users due to duck-typing.

  • Improve performance of message creation by about 1.5x.

  • Improve performance of message editing by about 1.5-4x depending on payload size.

  • Improve performance of attribute access on Member about by 2x.

  • Improve performance of utils.get() by around 4-6x depending on usage.

  • Improve performance of event parsing lookup by around 2.5x.

  • Keyword arguments in Client.start() and Client.run() are now validated (#953, #2170)

  • The Discord error code is now shown in the exception message for HTTPException.

  • Internal tasks launched by the library will now have their own custom __repr__.

  • All public facing types should now have a proper and more detailed __repr__.

  • [ext.tasks] Errors are now logged via the standard logging module.

v1.1.1

Bug Fixes
  • Webhooks do not overwrite data on retrying their HTTP requests (#2140)

Miscellaneous
  • Add back signal handling to Client.run() due to issues some users had with proper cleanup.

v1.1.0

New Features
disnake.ext.commands
Bug Fixes
disnake.ext.commands
  • Fix lambda converters in a non-module context (e.g. eval).

  • Use message creation time for reference time when computing cooldowns.
    • This prevents cooldowns from triggering during e.g. a RESUME session.

  • Fix the default on_command_error() to work with new-style cogs (#2094)

  • DM channels are now recognised as NSFW in is_nsfw() check.

  • Fix race condition with help commands (#2123)

  • Fix cog descriptions not showing in MinimalHelpCommand (#2139)

Miscellaneous
  • Improve the performance of internal enum creation in the library by about 5x.

  • Make the output of python -m disnake --version a bit more useful.

  • The loop cleanup facility has been rewritten again.

  • The signal handling in Client.run() has been removed.

disnake.ext.commands
  • Custom exception classes are now used for all default checks in the library (#2101)

v1.0.1

Bug Fixes
  • Fix issue with speaking state being cast to int when it was invalid.

  • Fix some issues with loop cleanup that some users experienced on Linux machines.

  • Fix voice handshake race condition (#2056, #2063)

v1.0.0

The changeset for this version are too big to be listed here, for more information please see the migrating page.

v0.16.6

Bug Fixes
  • Fix issue with Client.create_server() that made it stop working.

  • Fix main thread being blocked upon calling StreamPlayer.stop.

  • Handle HEARTBEAT_ACK and resume gracefully when it occurs.

  • Fix race condition when pre-emptively rate limiting that caused releasing an already released lock.

  • Fix invalid state errors when immediately cancelling a coroutine.

v0.16.1

This release is just a bug fix release with some better rate limit implementation.

Bug Fixes
  • Servers are now properly chunked for user bots.

  • The CDN URL is now used instead of the API URL for assets.

  • Rate limit implementation now tries to use header information if possible.

  • Event loop is now properly propagated (#420)

  • Allow falsey values in Client.send_message() and Client.send_file().

v0.16.0

New Features
  • Add Channel.overwrites to get all the permission overwrites of a channel.

  • Add Server.features to get information about partnered servers.

Bug Fixes
  • Timeout when waiting for offline members while triggering on_ready().

    • The fact that we did not timeout caused a gigantic memory leak in the library that caused thousands of duplicate Member instances causing big memory spikes.

  • Discard null sequences in the gateway.

    • The fact these were not discarded meant that on_ready() kept being called instead of on_resumed(). Since this has been corrected, in most cases on_ready() will be called once or twice with on_resumed() being called much more often.

v0.15.1

  • Fix crash on duplicate or out of order reactions.

v0.15.0

New Features
  • Rich Embeds for messages are now supported.

    • To do so, create your own Embed and pass the instance to the embed keyword argument to Client.send_message() or Client.edit_message().

  • Add Client.clear_reactions() to remove all reactions from a message.

  • Add support for MESSAGE_REACTION_REMOVE_ALL event, under on_reaction_clear().

  • Add Permissions.update() and PermissionOverwrite.update() for bulk permission updates.

    • This allows you to use e.g. p.update(read_messages=True, send_messages=False) in a single line.

  • Add PermissionOverwrite.is_empty() to check if the overwrite is empty (i.e. has no overwrites set explicitly as true or false).

For the command extension, the following changed:

  • Context is no longer slotted to facilitate setting dynamic attributes.

v0.14.3

Bug Fixes
  • Fix crash when dealing with MESSAGE_REACTION_REMOVE

  • Fix incorrect buckets for reactions.

v0.14.2

New Features
  • Client.wait_for_reaction() now returns a namedtuple with reaction and user attributes.
    • This is for better support in the case that None is returned since tuple unpacking can lead to issues.

Bug Fixes
  • Fix bug that disallowed None to be passed for emoji parameter in Client.wait_for_reaction().

v0.14.1

Bug fixes
  • Fix bug with Reaction not being visible at import.
    • This was also breaking the documentation.

v0.14.0

This update adds new API features and a couple of bug fixes.

New Features
  • Add support for Manage Webhooks permission under Permissions.manage_webhooks

  • Add support for around argument in 3.5+ Client.logs_from().

  • Add support for reactions.
Bug Fixes

v0.13.0

This is a backwards compatible update with new features.

New Features
  • Add the ability to manage emojis.

    • Client.create_custom_emoji() to create new emoji.

    • Client.edit_custom_emoji() to edit an old emoji.

    • Client.delete_custom_emoji() to delete a custom emoji.

  • Add new Permissions.manage_emojis toggle.

  • Add new statuses for Status.

  • Deprecate Client.change_status()

    • Use Client.change_presence() instead for better more up to date functionality.

    • This method is subject for removal in a future API version.

  • Add Client.change_presence() for changing your status with the new Discord API change.

    • This is the only method that allows changing your status to invisible or do not disturb.

Bug Fixes
  • Paginator pages do not exceed their max_size anymore (#340)

  • Do Not Disturb users no longer show up offline due to the new Status changes.

v0.12.0

This is a bug fix update that also comes with new features.

New Features
  • Add custom emoji support.

    • Adds a new class to represent a custom Emoji named Emoji

    • Adds a utility generator function, Client.get_all_emojis().

    • Adds a list of emojis on a server, Server.emojis.

    • Adds a new event, on_server_emojis_update().

  • Add new server regions to ServerRegion

    • ServerRegion.eu_central and ServerRegion.eu_west.

  • Add support for new pinned system message under MessageType.pins_add.

  • Add order comparisons for Role to allow it to be compared with regards to hierarchy.

    • This means that you can now do role_a > role_b etc to check if role_b is lower in the hierarchy.

  • Add Server.role_hierarchy to get the server’s role hierarchy.

  • Add Member.server_permissions to get a member’s server permissions without their channel specific overwrites.

  • Add Client.get_user_info() to retrieve a user’s info from their ID.

  • Add a new Player property, Player.error to fetch the error that stopped the player.

    • To help with this change, a player’s after function can now take a single parameter denoting the current player.

  • Add support for server verification levels.

    • Adds a new enum called VerificationLevel.

    • This enum can be used in Client.edit_server() under the verification_level keyword argument.

    • Adds a new attribute in the server, Server.verification_level.

  • Add Server.voice_client shortcut property for Client.voice_client_in().

    • This is technically old (was added in v0.10.0) but was undocumented until v0.12.0.

For the command extension, the following are new:

  • Add custom emoji converter.

  • All default converters that can take IDs can now convert via ID.

  • Add coroutine support for Bot.command_prefix.

  • Add a method to reset command cooldown.

Bug Fixes
  • Fix bug that caused the library to not work with the latest websockets library.

  • Fix bug that leaked keep alive threads (#309)

  • Fix bug that disallowed ServerRegion from being used in Client.edit_server().

  • Fix bug in Channel.permissions_for() that caused permission resolution to happen out of order.

  • Fix bug in Member.top_role that did not account for same-position roles.

v0.11.0

This is a minor bug fix update that comes with a gateway update (v5 -> v6).

Breaking Changes
New Features
  • Add the ability to prune members via Client.prune_members().

  • Switch the websocket gateway version to v6 from v5. This allows the library to work with group DMs and 1-on-1 calls.

  • Add AppInfo.owner attribute.

  • Add CallMessage for group voice call messages.

  • Add GroupCall for group voice call information.

  • Add Message.system_content to get the system message.

  • Add the remaining VIP servers and the Brazil servers into ServerRegion enum.

  • Add stderr argument to VoiceClient.create_ffmpeg_player() to redirect stderr.

  • The library now handles implicit permission resolution in Channel.permissions_for().

  • Add Server.mfa_level to query a server’s 2FA requirement.

  • Add Permissions.external_emojis permission.

  • Add Member.voice attribute that refers to a VoiceState.

    • For backwards compatibility, the member object will have properties mirroring the old behaviour.

For the command extension, the following are new:

  • Command cooldown system with the cooldown decorator.

  • UserInputError exception for the hierarchy for user input related errors.

Bug Fixes
  • Client.email is now saved when using a token for user accounts.

  • Fix issue when removing roles out of order.

  • Fix bug where discriminators would not update.

  • Handle cases where HEARTBEAT opcode is received. This caused bots to disconnect seemingly randomly.

For the command extension, the following bug fixes apply:

  • Bot.check decorator is actually a decorator not requiring parentheses.

  • Bot.remove_command and Group.remove_command no longer throw if the command doesn’t exist.

  • Command names are no longer forced to be lower().

  • Fix a bug where Member and User converters failed to work in private message contexts.

  • HelpFormatter now ignores hidden commands when deciding the maximum width.

v0.10.0

For breaking changes, see Migrating to v0.10.0. The breaking changes listed there will not be enumerated below. Since this version is rather a big departure from v0.9.2, this change log will be non-exhaustive.

New Features
  • The library is now fully asyncio compatible, allowing you to write non-blocking code a lot more easily.

  • The library now fully handles 429s and unconditionally retries on 502s.

  • A new command extension module was added but is currently undocumented. Figuring it out is left as an exercise to the reader.

  • Two new exception types, Forbidden and NotFound to denote permission errors or 404 errors.

  • Added Client.delete_invite() to revoke invites.

  • Added support for sending voice. Check VoiceClient for more details.

  • Added Client.wait_for_message() coroutine to aid with follow up commands.

  • Added version_info named tuple to check version info of the library.

  • Login credentials are now cached to have a faster login experience. You can disable this by passing in cache_auth=False when constructing a Client.

  • New utility function, disnake.utils.get() to simplify retrieval of items based on attributes.

  • All data classes now support !=, ==, hash(obj) and str(obj).

  • Added Client.get_bans() to get banned members from a server.

  • Added Client.invites_from() to get currently active invites in a server.

  • Added Server.me attribute to get the Member version of Client.user.

  • Most data classes now support a hash(obj) function to allow you to use them in set or dict classes or subclasses.

  • Add Message.clean_content() to get a text version of the content with the user and channel mentioned changed into their names.

  • Added a way to remove the messages of the user that just got banned in Client.ban().

  • Added Client.wait_until_ready() to facilitate easy creation of tasks that require the client cache to be ready.

  • Added Client.wait_until_login() to facilitate easy creation of tasks that require the client to be logged in.

  • Add disnake.Game to represent any game with custom text to send to Client.change_status().

  • Add Message.nonce attribute.

  • Add Member.permissions_in() as another way of doing Channel.permissions_for().

  • Add Client.move_member() to move a member to another voice channel.

  • You can now create a server via Client.create_server().

  • Added Client.edit_server() to edit existing servers.

  • Added Client.server_voice_state() to server mute or server deafen a member.

  • If you are being rate limited, the library will now handle it for you.

  • Add on_member_ban() and on_member_unban() events that trigger when a member is banned/unbanned.

Performance Improvements
  • All data classes now use __slots__ which greatly reduce the memory usage of things kept in cache.

  • Due to the usage of asyncio, the CPU usage of the library has gone down significantly.

  • A lot of the internal cache lists were changed into dictionaries to change the O(n) lookup into O(1).

  • Compressed READY is now on by default. This means if you’re on a lot of servers (or maybe even a few) you would receive performance improvements by having to download and process less data.

  • While minor, change regex from \d+ to [0-9]+ to avoid unnecessary unicode character lookups.

Bug Fixes
  • Fix bug where guilds being updated did not edit the items in cache.

  • Fix bug where member.roles were empty upon joining instead of having the @everyone role.

  • Fix bug where Role.is_everyone() was not being set properly when the role was being edited.

  • Client.logs_from() now handles cases where limit > 100 to sidestep the disnake API limitation.

  • Fix bug where a role being deleted would trigger a ValueError.

  • Fix bug where Permissions.kick_members() and Permissions.ban_members() were flipped.

  • Mentions are now triggered normally. This was changed due to the way disnake handles it internally.

  • Fix issue when a Message would attempt to upgrade a Message.server when the channel is a Object.

  • Unavailable servers were not being added into cache, this has been corrected.

Version Guarantees

This library does not quite follow the semantic versioning principle, the notable difference being that breaking changes may not only occur on major version increases, but also on minor version bumps (think Python’s own versioning scheme). The primary reason for this is the lack of guarantees on the Discord API side when it comes to breaking changes, which along with the dynamic nature of the API results in breaking changes sometimes being required more frequently than desired. However, any breaking changes will always be explicitly marked as such in the release notes.

In general, the versioning scheme (major.minor.micro) used in this library aims to follow these rules:

  • major bumps indicate a significant refactoring or other large changes that would constitute such an increase (will most likely include breaking changes)

  • minor bumps contain new features, fixes, and may also have breaking changes

  • micro bumps only contain fixes, no new features and no breaking changes

One thing to keep in mind is that breaking changes only apply to publicly documented functions and classes. If it’s not listed in the documentation here then it is not part of the public API and is thus bound to change. This includes attributes that start with an underscore or functions without an underscore that are not documented.

Note

The examples below are non-exhaustive.

Examples of Breaking Changes

  • Changing the default parameter value to something else.

  • Renaming a function without an alias to an old function.

  • Adding or removing parameters to an event.

Examples of Non-Breaking Changes

  • Adding or removing private underscored attributes.

  • Adding an element into the __slots__ of a data class.

  • Changing the behaviour of a function to fix a bug.

  • Changes in the documentation.

  • Modifying the internal HTTP handling.

  • Upgrading the dependencies to a new version, major or otherwise.

Migrating to v1.0

v1.0 is one of the biggest breaking changes in the library due to a complete redesign.

The amount of changes are so massive and long that for all intents and purposes, it is a completely new library.

Part of the redesign involves making things more easy to use and natural. Things are done on the models instead of requiring a Client instance to do any work.

Python Version Change

In order to make development easier and also to allow for our dependencies to upgrade to allow usage of 3.7 or higher, the library had to remove support for Python versions lower than 3.5.3, which essentially means that support for Python 3.4 is dropped.

Major Model Changes

Below are major model changes that have happened in v1.0

Snowflakes are int

Before v1.0, all snowflakes (the id attribute) were strings. This has been changed to int.

Quick example:

# before
ch = client.get_channel('84319995256905728')
if message.author.id == '80528701850124288':
    ...

# after
ch = client.get_channel(84319995256905728)
if message.author.id == 80528701850124288:
    ...

This change allows for fewer errors when using the Copy ID feature in the official client since you no longer have to wrap it in quotes and allows for optimisation opportunities by allowing ETF to be used instead of JSON internally.

Server is now Guild

The official API documentation calls the “Server” concept a “Guild” instead. In order to be more consistent with the API documentation when necessary, the model has been renamed to Guild and all instances referring to it has been changed as well.

A list of changes is as follows:

Before

After

Message.server

Message.guild

Channel.server

GuildChannel.guild

Client.servers

Client.guilds

Client.get_server

Client.get_guild()

Emoji.server

Emoji.guild

Role.server

Role.guild

Invite.server

Invite.guild

Member.server

Member.guild

Permissions.manage_server

Permissions.manage_guild

VoiceClient.server

VoiceClient.guild

Client.create_server

Client.create_guild()

Models are Stateful

As mentioned earlier, a lot of functionality was moved out of Client and put into their respective model.

A list of these changes is enumerated below.

Before

After

Client.add_reaction

Message.add_reaction()

Client.add_roles

Member.add_roles()

Client.ban

Member.ban() or Guild.ban()

Client.change_nickname

Member.edit()

Client.clear_reactions

Message.clear_reactions()

Client.create_channel

Guild.create_text_channel() and Guild.create_voice_channel()

Client.create_custom_emoji

Guild.create_custom_emoji()

Client.create_invite

abc.GuildChannel.create_invite()

Client.create_role

Guild.create_role()

Client.delete_channel

abc.GuildChannel.delete()

Client.delete_channel_permissions

abc.GuildChannel.set_permissions() with overwrite set to None

Client.delete_custom_emoji

Emoji.delete()

Client.delete_invite

Invite.delete() or Client.delete_invite()

Client.delete_message

Message.delete()

Client.delete_messages

TextChannel.delete_messages()

Client.delete_role

Role.delete()

Client.delete_server

Guild.delete()

Client.edit_channel

TextChannel.edit() or VoiceChannel.edit()

Client.edit_channel_permissions

abc.GuildChannel.set_permissions()

Client.edit_custom_emoji

Emoji.edit()

Client.edit_message

Message.edit()

Client.edit_profile

ClientUser.edit() (you get this from Client.user)

Client.edit_role

Role.edit()

Client.edit_server

Guild.edit()

Client.estimate_pruned_members

Guild.estimate_pruned_members()

Client.get_all_emojis

Client.emojis

Client.get_bans

Guild.bans()

Client.get_invite

Client.fetch_invite()

Client.get_message

abc.Messageable.fetch_message()

Client.get_reaction_users

Reaction.users()

Client.get_user_info

Client.fetch_user()

Client.invites_from

abc.GuildChannel.invites() or Guild.invites()

Client.join_voice_channel

VoiceChannel.connect() (see Voice Changes)

Client.kick

Guild.kick() or Member.kick()

Client.leave_server

Guild.leave()

Client.logs_from

abc.Messageable.history() (see Asynchronous Iterators)

Client.move_channel

TextChannel.edit() or VoiceChannel.edit()

Client.move_member

Member.edit()

Client.move_role

Role.edit()

Client.pin_message

Message.pin()

Client.pins_from

abc.Messageable.pins()

Client.prune_members

Guild.prune_members()

Client.purge_from

TextChannel.purge()

Client.remove_reaction

Message.remove_reaction()

Client.remove_roles

Member.remove_roles()

Client.replace_roles

Member.edit()

Client.send_file

abc.Messageable.send() (see Sending Messages)

Client.send_message

abc.Messageable.send() (see Sending Messages)

Client.send_typing

abc.Messageable.trigger_typing() (use abc.Messageable.typing())

Client.server_voice_state

Member.edit()

Client.start_private_message

User.create_dm()

Client.unban

Guild.unban() or Member.unban()

Client.unpin_message

Message.unpin()

Client.wait_for_message

Client.wait_for() (see Waiting For Events)

Client.wait_for_reaction

Client.wait_for() (see Waiting For Events)

Client.wait_until_login

Removed

Client.wait_until_ready

No change

Property Changes

In order to be a bit more consistent, certain things that were properties were changed to methods instead.

The following are now methods instead of properties (requires parentheses):

Dict Value Change

Prior to v1.0 some aggregating properties that retrieved models would return “dict view” objects.

As a consequence, when the dict would change size while you would iterate over it, a RuntimeError would be raised and crash the task. To alleviate this, the “dict view” objects were changed into lists.

The following views were changed to a list:

Voice State Changes

Earlier, in v0.11.0 a VoiceState class was added to refer to voice states along with a Member.voice attribute to refer to it.

However, it was transparent to the user. In an effort to make the library save more memory, the voice state change is now more visible.

The only way to access voice attributes is via the Member.voice attribute. Note that if the member does not have a voice state this attribute can be None.

Quick example:

# before
member.deaf
member.voice.voice_channel

# after
if member.voice: # can be None
    member.voice.deaf
    member.voice.channel
User and Member Type Split

In v1.0 to save memory, User and Member are no longer inherited. Instead, they are “flattened” by having equivalent properties that map out to the functional underlying User. Thus, there is no functional change in how they are used. However this breaks isinstance() checks and thus is something to keep in mind.

These memory savings were accomplished by having a global User cache, and as a positive consequence you can now easily fetch a User by their ID by using the new Client.get_user(). You can also get a list of all User your client can see with Client.users.

Channel Type Split

Prior to v1.0, channels were two different types, Channel and PrivateChannel with a is_private property to help differentiate between them.

In order to save memory the channels have been split into 4 different types:

With this split came the removal of the is_private attribute. You should now use isinstance().

The types are split into two different Abstract Base Classes:

So to check if something is a guild channel you would do:

isinstance(channel, disnake.abc.GuildChannel)

And to check if it’s a private channel you would do:

isinstance(channel, disnake.abc.PrivateChannel)

Of course, if you’re looking for only a specific type you can pass that too, e.g.

isinstance(channel, disnake.TextChannel)

With this type split also came event changes, which are enumerated in Event Changes.

Miscellaneous Model Changes

There were lots of other things added or removed in the models in general.

They will be enumerated here.

Removed

  • Client.login() no longer accepts email and password logins.

    • Use a token and bot=False.

  • Client.get_all_emojis

  • Client.messages

  • Client.wait_for_message and Client.wait_for_reaction are gone.

  • Channel.voice_members

  • Channel.is_private

    • Use isinstance instead with one of the Abstract Base Classes instead.

    • e.g. isinstance(channel, disnake.abc.GuildChannel) will check if it isn’t a private channel.

  • Client.accept_invite

    • There is no replacement for this one. This functionality is deprecated API wise.

  • Guild.default_channel / Server.default_channel and Channel.is_default

    • The concept of a default channel was removed from Discord. See #329.

  • Message.edited_timestamp

  • Message.timestamp

  • Colour.to_tuple()

  • Permissions.view_audit_logs

  • Member.game

  • Guild.role_hierarchy / Server.role_hierarchy

    • Use Guild.roles instead. Note that while sorted, it is in the opposite order of what the old Guild.role_hierarchy used to be.

Changed

Added

Sending Messages

One of the changes that were done was the merger of the previous Client.send_message and Client.send_file functionality into a single method, send().

Basically:

# before
await client.send_message(channel, 'Hello')

# after
await channel.send('Hello')

This supports everything that the old send_message supported such as embeds:

e = disnake.Embed(title='foo')
await channel.send('Hello', embed=e)

There is a caveat with sending files however, as this functionality was expanded to support multiple file attachments, you must now use a File pseudo-namedtuple to upload a single file.

# before
await client.send_file(channel, 'cool.png', filename='testing.png', content='Hello')

# after
await channel.send('Hello', file=disnake.File('cool.png', 'testing.png'))

This change was to facilitate multiple file uploads:

my_files = [
    disnake.File('cool.png', 'testing.png'),
    disnake.File(some_fp, 'cool_filename.png'),
]

await channel.send('Your images:', files=my_files)

Asynchronous Iterators

Prior to v1.0, certain functions like Client.logs_from would return a different type if done in Python 3.4 or 3.5+.

In v1.0, this change has been reverted and will now return a singular type meeting an abstract concept called AsyncIterator.

This allows you to iterate over it like normal:

async for message in channel.history():
    print(message)

Or turn it into a list:

messages = await channel.history().flatten()
for message in messages:
    print(message)

A handy aspect of returning AsyncIterator is that it allows you to chain functions together such as AsyncIterator.map() or AsyncIterator.filter():

async for m_id in channel.history().filter(lambda m: m.author == client.user).map(lambda m: m.id):
    print(m_id)

The functions passed to AsyncIterator.map() or AsyncIterator.filter() can be either coroutines or regular functions.

You can also get single elements a la disnake.utils.find() or disnake.utils.get() via AsyncIterator.get() or AsyncIterator.find():

my_last_message = await channel.history().get(author=client.user)

The following return AsyncIterator:

Event Changes

A lot of events have gone through some changes.

Many events with server in the name were changed to use guild instead.

Before:

  • on_server_join

  • on_server_remove

  • on_server_update

  • on_server_role_create

  • on_server_role_delete

  • on_server_role_update

  • on_server_emojis_update

  • on_server_available

  • on_server_unavailable

After:

The on_voice_state_update() event has received an argument change.

Before:

async def on_voice_state_update(before, after)

After:

async def on_voice_state_update(member, before, after)

Instead of two Member objects, the new event takes one Member object and two VoiceState objects.

The on_guild_emojis_update() event has received an argument change.

Before:

async def on_guild_emojis_update(before, after)

After:

async def on_guild_emojis_update(guild, before, after)

The first argument is now the Guild that the emojis were updated from.

The on_member_ban() event has received an argument change as well:

Before:

async def on_member_ban(member)

After:

async def on_member_ban(guild, user)

As part of the change, the event can either receive a User or Member. To help in the cases that have User, the Guild is provided as the first parameter.

The on_channel_ events have received a type level split (see Channel Type Split).

Before:

  • on_channel_delete

  • on_channel_create

  • on_channel_update

After:

The on_guild_channel_ events correspond to abc.GuildChannel being updated (i.e. TextChannel and VoiceChannel) and the on_private_channel_ events correspond to abc.PrivateChannel being updated (i.e. DMChannel and GroupChannel).

Voice Changes

Voice sending has gone through a complete redesign.

In particular:

  • Connection is done through VoiceChannel.connect() instead of Client.join_voice_channel.

  • You no longer create players and operate on them (you no longer store them).

  • You instead request VoiceClient to play an AudioSource via VoiceClient.play().

  • There are different built-in AudioSources.

  • create_ffmpeg_player/create_stream_player/create_ytdl_player have all been removed.

  • Using VoiceClient.play() will not return an AudioPlayer.

    • Instead, it’s “flattened” like User -> Member is.

  • The after parameter now takes a single parameter (the error).

Basically:

Before:

vc = await client.join_voice_channel(channel)
player = vc.create_ffmpeg_player('testing.mp3', after=lambda: print('done'))
player.start()

player.is_playing()
player.pause()
player.resume()
player.stop()
# ...

After:

vc = await channel.connect()
vc.play(disnake.FFmpegPCMAudio('testing.mp3'), after=lambda e: print('done', e))
vc.is_playing()
vc.pause()
vc.resume()
vc.stop()
# ...

With the changed AudioSource design, you can now change the source that the VoiceClient is playing at runtime via VoiceClient.source.

For example, you can add a PCMVolumeTransformer to allow changing the volume:

vc.source = disnake.PCMVolumeTransformer(vc.source)
vc.source.volume = 0.6

An added benefit of the redesign is that it will be much more resilient towards reconnections:

  • The voice websocket will now automatically re-connect and re-do the handshake when disconnected.

  • The initial connect handshake will now retry up to 5 times so you no longer get as many asyncio.TimeoutError.

  • Audio will now stop and resume when a disconnect is found.

    • This includes changing voice regions etc.

Waiting For Events

Prior to v1.0, the machinery for waiting for an event outside of the event itself was done through two different functions, Client.wait_for_message and Client.wait_for_reaction. One problem with one such approach is that it did not allow you to wait for events outside of the ones provided by the library.

In v1.0 the concept of waiting for another event has been generalised to work with any event as Client.wait_for().

For example, to wait for a message:

# before
msg = await client.wait_for_message(author=message.author, channel=message.channel)

# after
def pred(m):
    return m.author == message.author and m.channel == message.channel

msg = await client.wait_for('message', check=pred)

To facilitate multiple returns, Client.wait_for() returns either a single argument, no arguments, or a tuple of arguments.

For example, to wait for a reaction:

reaction, user = await client.wait_for('reaction_add', check=lambda r, u: u.id == 176995180300206080)

# use user and reaction

Since this function now can return multiple arguments, the timeout parameter will now raise a asyncio.TimeoutError when reached instead of setting the return to None. For example:

def pred(m):
    return m.author == message.author and m.channel == message.channel

try:

    msg = await client.wait_for('message', check=pred, timeout=60.0)
except asyncio.TimeoutError:
    await channel.send('You took too long...')
else:
    await channel.send('You said {0.content}, {0.author}.'.format(msg))

Upgraded Dependencies

Following v1.0 of the library, we’ve updated our requirements to aiohttp v2.0 or higher.

Since this is a backwards incompatible change, it is recommended that you see the changes and the Migration to 2.x pages for details on the breaking changes in aiohttp.

Of the most significant for common users is the removal of helper functions such as:

  • aiohttp.get

  • aiohttp.post

  • aiohttp.delete

  • aiohttp.patch

  • aiohttp.head

  • aiohttp.put

  • aiohttp.request

It is recommended that you create a session instead:

async with aiohttp.ClientSession() as sess:
    async with sess.get('url') as resp:
        # work with resp

Since it is better to not create a session for every request, you should store it in a variable and then call session.close on it when it needs to be disposed.

Sharding

The library has received significant changes on how it handles sharding and now has sharding as a first-class citizen.

If using a Bot account and you want to shard your bot in a single process then you can use the AutoShardedClient.

This class allows you to use sharding without having to launch multiple processes or deal with complicated IPC.

It should be noted that the sharded client does not support user accounts. This is due to the changes in connection logic and state handling.

Usage is as simple as doing:

client = disnake.AutoShardedClient()

instead of using Client.

This will launch as many shards as your bot needs using the /gateway/bot endpoint, which allocates about 1000 guilds per shard.

If you want more control over the sharding you can specify shard_count and shard_ids.

# launch 10 shards regardless
client = disnake.AutoShardedClient(shard_count=10)

# launch specific shard IDs in this process
client = disnake.AutoShardedClient(shard_count=10, shard_ids=(1, 2, 5, 6))

For users of the command extension, there is also AutoShardedBot which behaves similarly.

Connection Improvements

In v1.0, the auto reconnection logic has been powered up significantly.

Client.connect() has gained a new keyword argument, reconnect that defaults to True which controls the reconnect logic. When enabled, the client will automatically reconnect in all instances of your internet going offline or Discord going offline with exponential back-off.

Client.run() and Client.start() gains this keyword argument as well, but for most cases you will not need to specify it unless turning it off.

Command Extension Changes

Due to the Models are Stateful changes, some of the design of the extension module had to undergo some design changes as well.

Context Changes

In v1.0, the Context has received a lot of changes with how it’s retrieved and used.

The biggest change is that pass_context=True no longer exists, Context is always passed. Ergo:

# before
@bot.command()
async def foo():
    await bot.say('Hello')

# after
@bot.command()
async def foo(ctx):
    await ctx.send('Hello')

The reason for this is because Context now meets the requirements of abc.Messageable. This makes it have similar functionality to TextChannel or DMChannel. Using send() will either DM the user in a DM context or send a message in the channel it was in, similar to the old bot.say functionality. The old helpers have been removed in favour of the new abc.Messageable interface. See Removed Helpers for more information.

Since the Context is now passed by default, several shortcuts have been added:

New Shortcuts

  • ctx.author is a shortcut for ctx.message.author.

  • ctx.guild is a shortcut for ctx.message.guild.

  • ctx.channel is a shortcut for ctx.message.channel.

  • ctx.me is a shortcut for ctx.message.guild.me or ctx.bot.user.

  • ctx.voice_client is a shortcut for ctx.message.guild.voice_client.

New Functionality

Subclassing Context

In v1.0, there is now the ability to subclass Context and use it instead of the default provided one.

For example, if you want to add some functionality to the context:

class MyContext(commands.Context):
    @property
    def secret(self):
        return 'my secret here'

Then you can use get_context() inside on_message() with combination with invoke() to use your custom context:

class MyBot(commands.Bot):
    async def on_message(self, message):
        ctx = await self.get_context(message, cls=MyContext)
        await self.invoke(ctx)

Now inside your commands you will have access to your custom context:

@bot.command()
async def secret(ctx):
    await ctx.send(ctx.secret)
Removed Helpers

With the new Context changes, a lot of message sending helpers have been removed.

For a full list of changes, see below:

Before

After

Bot.say

Context.send()

Bot.upload

Context.send()

Bot.whisper

ctx.author.send

Bot.type

Context.typing() or Context.trigger_typing()

Bot.reply

No replacement.

Command Changes

As mentioned earlier, the first command change is that pass_context=True no longer exists, so there is no need to pass this as a parameter.

Another change is the removal of no_pm=True. Instead, use the new guild_only() built-in check.

The commands attribute of Bot and Group have been changed from a dictionary to a set that does not have aliases. To retrieve the previous dictionary behaviour, use all_commands instead.

Command instances have gained new attributes and properties:

  1. signature to get the signature of the command.

  2. usage, an attribute to override the default signature.

  3. root_parent to get the root parent group of a subcommand.

For Group and Bot the following changed:

Check Changes

Prior to v1.0, check()s could only be synchronous. As of v1.0 checks can now be coroutines.

Along with this change, a couple new checks were added.

Event Changes

All command extension events have changed.

Before:

on_command(command, ctx)
on_command_completion(command, ctx)
on_command_error(error, ctx)

After:

on_command(ctx)
on_command_completion(ctx)
on_command_error(ctx, error)

The extraneous command parameter in on_command() and on_command_completion() have been removed. The Command instance was not kept up-to date so it was incorrect. In order to get the up to date Command instance, use the Context.command attribute.

The error handlers, either Command.error() or on_command_error(), have been re-ordered to use the Context as its first parameter to be consistent with other events and commands.

HelpFormatter and Help Command Changes

The HelpFormatter class has been removed. It has been replaced with a HelpCommand class. This class now stores all the command handling and processing of the help command.

The help command is now stored in the Bot.help_command attribute. As an added extension, you can disable the help command completely by assigning the attribute to None or passing it at __init__ as help_command=None.

The new interface allows the help command to be customised through special methods that can be overridden.

Certain subclasses can implement more customisable methods.

The old HelpFormatter was replaced with DefaultHelpCommand, which implements all of the logic of the old help command. The customisable methods can be found in the accompanying documentation.

The library now provides a new more minimalistic HelpCommand implementation that doesn’t take as much space, MinimalHelpCommand. The customisable methods can also be found in the accompanying documentation.

A frequent request was if you could associate a help command with a cog. The new design allows for dynamically changing of cog through binding it to the HelpCommand.cog attribute. After this assignment the help command will pretend to be part of the cog and everything should work as expected. When the cog is unloaded then the help command will be “unbound” from the cog.

For example, to implement a HelpCommand in a cog, the following snippet can be used.

class MyHelpCommand(commands.MinimalHelpCommand):
    def get_command_signature(self, command):
        return '{0.clean_prefix}{1.qualified_name} {1.signature}'.format(self, command)

class MyCog(commands.Cog):
    def __init__(self, bot):
        self._original_help_command = bot.help_command
        bot.help_command = MyHelpCommand()
        bot.help_command.cog = self

    def cog_unload(self):
        self.bot.help_command = self._original_help_command

For more information, check out the relevant documentation.

Cog Changes

Cogs have completely been revamped. They are documented in Cogs as well.

Cogs are now required to have a base class, Cog for future proofing purposes. This comes with special methods to customise some behaviour.

Those that were using listeners, such as on_message inside a cog will now have to explicitly mark them as such using the commands.Cog.listener() decorator.

Along with that, cogs have gained the ability to have custom names through specifying it in the class definition line. More options can be found in the metaclass that facilitates all this, commands.CogMeta.

An example cog with every special method registered and a custom name is as follows:

class MyCog(commands.Cog, name='Example Cog'):
    def cog_unload(self):
        print('cleanup goes here')

    def bot_check(self, ctx):
        print('bot check')
        return True

    def bot_check_once(self, ctx):
        print('bot check once')
        return True

    async def cog_check(self, ctx):
        print('cog local check')
        return await ctx.bot.is_owner(ctx.author)

    async def cog_command_error(self, ctx, error):
        print('Error in {0.command.qualified_name}: {1}'.format(ctx, error))

    async def cog_before_invoke(self, ctx):
        print('cog local before: {0.command.qualified_name}'.format(ctx))

    async def cog_after_invoke(self, ctx):
        print('cog local after: {0.command.qualified_name}'.format(ctx))

    @commands.Cog.listener()
    async def on_message(self, message):
        pass
Before and After Invocation Hooks

Commands have gained new before and after invocation hooks that allow you to do an action before and after a command is run.

They take a single parameter, Context and they must be a coroutine.

They are on a global, per-cog, or per-command basis.

Basically:

# global hooks:

@bot.before_invoke
async def before_any_command(ctx):
    # do something before a command is called
    pass

@bot.after_invoke
async def after_any_command(ctx):
    # do something after a command is called
    pass

The after invocation is hook always called, regardless of an error in the command. This makes it ideal for some error handling or clean up of certain resources such a database connection.

The per-command registration is as follows:

@bot.command()
async def foo(ctx):
    await ctx.send('foo')

@foo.before_invoke
async def before_foo_command(ctx):
    # do something before the foo command is called
    pass

@foo.after_invoke
async def after_foo_command(ctx):
    # do something after the foo command is called
    pass

The special cog method for these is Cog.cog_before_invoke() and Cog.cog_after_invoke(), e.g.:

class MyCog(commands.Cog):
    async def cog_before_invoke(self, ctx):
        ctx.secret_cog_data = 'foo'

    async def cog_after_invoke(self, ctx):
        print('{0.command} is done...'.format(ctx))

    @commands.command()
    async def foo(self, ctx):
        await ctx.send(ctx.secret_cog_data)

To check if a command failed in the after invocation hook, you can use Context.command_failed.

The invocation order is as follows:

  1. Command local before invocation hook

  2. Cog local before invocation hook

  3. Global before invocation hook

  4. The actual command

  5. Command local after invocation hook

  6. Cog local after invocation hook

  7. Global after invocation hook

Converter Changes

Prior to v1.0, a converter was a type hint that could be a callable that could be invoked with a singular argument denoting the argument passed by the user as a string.

This system was eventually expanded to support a Converter system to allow plugging in the Context and do more complicated conversions such as the built-in “disnake” converters.

In v1.0 this converter system was revamped to allow instances of Converter derived classes to be passed. For consistency, the convert() method was changed to always be a coroutine and will now take the two arguments as parameters.

Essentially, before:

class MyConverter(commands.Converter):
    def convert(self):
        return self.ctx.message.server.me

After:

class MyConverter(commands.Converter):
    async def convert(self, ctx, argument):
        return ctx.me

The command framework also got a couple new converters: