Checks

This section documents checks - special decorators intented to simplify working with Discord-specific conditions.

Classes

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

Enumerations

BucketType

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.

Functions

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

Note

See app_check() for this function’s application command counterpart.

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.

Note

See app_check_any() for this function’s application command counterpart.

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

Same as check(), but for app commands.

New in version 2.10.

Parameters:

predicate (Callable[[disnake.ApplicationCommandInteraction], bool]) – The predicate to check if the command should be invoked.

@disnake.ext.commands.app_check_any(*checks)[source]

Same as check_any(), but for app commands.

Note

See check_any() for this function’s prefix command counterpart.

New in version 2.10.

Parameters:

*checks (Callable[[disnake.ApplicationCommandInteraction], bool]) – An argument list of checks that have been decorated with the app_check() decorator.

Raises:

TypeError – A check passed has not been decorated with the app_check() decorator.

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