Commands Package

This package acts almost identically to discord.ext.commands; i.e. all of the attributes from discord.py’s are also in ours. Some of these attributes, however, have been slightly modified, while others have been added to extend functionalities used throughout the bot, as outlined below.

redbot.core.commands.command(name=None, cls=<class 'redbot.core.commands.commands.Command'>, **attrs)[source]

A decorator which transforms an async function into a Command.

Same interface as discord.ext.commands.command.

redbot.core.commands.group(name=None, cls=<class 'redbot.core.commands.commands.Group'>, **attrs)[source]

A decorator which transforms an async function into a Group.

Same interface as discord.ext.commands.group.

class redbot.core.commands.Command(*args, **kwargs)[source]

Bases: redbot.core.commands.commands.CogCommandMixin, discord.ext.commands.core.Command

Command class for Red.

This should not be created directly, and instead via the decorator.

This class inherits from discord.ext.commands.Command. The attributes listed below are simply additions to the ones listed with that class.

checks

A list of check predicates which cannot be overridden, unlike Requires.checks.

Type:List[coroutine function]
translator

A translator for this command’s help docstring.

Type:Translator
ignore_optional_for_conversion

A value which can be set to not have discord.py’s argument parsing behavior for typing.Optional (type used will be of the inner type instead)

Type:bool
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.
after_invoke(coro)[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.
allow_for(model_id, guild_id)[source]

Actively allow this command for the given model.

Parameters:
  • model_id (Union[int, str]) – Must be an int if supplying an ID. str is only valid for “default”.
  • guild_id (int) – The guild ID to allow this cog or command in. For global rules, use 0.
before_invoke(coro)[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.
await can_run(ctx, *, check_all_parents=False, change_permission_state=False)[source]

Check if this command can be run in the given context.

This function first checks if the command can be run using discord.py’s method discord.ext.commands.Command.can_run, then will return the result of Requires.verify.

Keyword Arguments:
 
  • check_all_parents (bool) – If True, this will check permissions for all of this command’s parents and its cog as well as the command itself. Defaults to False.
  • change_permission_state (bool) – Whether or not the permission state should be changed as a result of this call. For most cases this should be False. Defaults to False.
await can_see(ctx)[source]

Check if this command is visible in the given context.

In short, this will verify whether the user can run the command, and also whether the command is hidden or not.

Parameters:ctx (Context) – The invocation context to check with.
Returns:True if this command is visible in the given context.
Return type:bool
clean_params

Retrieves the parameter OrderedDict without the context or self parameters.

Useful for inspecting signature.

clear_rule_for(model_id, guild_id)[source]

Clear the rule which is currently set for this model.

Parameters:
  • model_id (Union[int, str]) – Must be an int if supplying an ID. str is only valid for “default”.
  • guild_id (int) – The guild ID. For global rules, use 0.
cog_name

The name of the cog this command belongs to. None otherwise.

Type:str
copy()[source]

Creates a copy of this command.

deny_to(model_id, guild_id)

Actively deny this command to the given model.

Parameters:
  • model_id (Union[int, str]) – Must be an int if supplying an ID. str is only valid for “default”.
  • guild_id (int) – The guild ID to deny this cog or command in. For global rules, use 0.
disable_in(guild)[source]

Disable this command in the given guild.

Parameters:guild (discord.Guild) – The guild to disable the command in.
Returns:True if the command wasn’t already disabled.
Return type:bool
await do_conversion(ctx, converter, argument, param)[source]

Convert an argument according to its type annotation.

Raises:ConversionFailure – If doing the conversion failed.
Returns:The converted argument.
Return type:Any
enable_in(guild)[source]

Enable this command in the given guild.

Parameters:guild (discord.Guild) – The guild to enable the command in.
Returns:True if the command wasn’t already enabled.
Return type:bool
error(coro)[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.

The on_command_error event is still dispatched for commands with a dedicated error handler.

Red’s global error handler will ignore commands with a registered error handler.

To have red handle specific errors with the default behavior, call Red.on_command_error with unhandled_by_cog set to True.

Due to how discord.py wraps exceptions, the exception you are expecting here is likely in error.original despite that the normal event handler for bot wide command error handling has no such wrapping.

For example:

@a_command.error
async def a_command_error_handler(self, ctx, error):

    if isinstance(error.original, MyErrrorType):
        self.log_exception(error.original)
    else:
        await ctx.bot.on_command_error(ctx, error.original, unhandled_by_cog=True)
Parameters:coro (coroutine function) – The coroutine to register as the local error handler.
Raises:discord.ClientException – The coroutine is not actually a coroutine.
format_help_for_context(ctx)

This formats the help string based on values in context

The steps are (currently, roughly) the following:

  • get the localized help
  • substitute [p] with ctx.clean_prefix
  • substitute [botname] with ctx.me.display_name

More steps may be added at a later time.

Cog creators may override this in their own command classes as long as the method signature stays the same.

Parameters:ctx (Context) –
Returns:Localized help with some formatting
Return type:str
format_shortdoc_for_context(ctx)[source]

This formats the short version of the help string based on values in context

See format_text_for_context for the actual implementation details

Cog creators may override this in their own command classes as long as the method signature stays the same.

Parameters:ctx (Context) –
Returns:Localized help with some formatting
Return type:str
format_text_for_context(ctx, text)

This formats text based on values in context

The steps are (currently, roughly) the following:

  • substitute [p] with ctx.clean_prefix
  • substitute [botname] with ctx.me.display_name

More steps may be added at a later time.

Cog creators should only override this if they want help text to be modified, and may also want to look at format_help_for_context and (for commands only) format_shortdoc_for_context

Parameters:
Returns:

text which has had some portions replaced based on context

Return type:

str

full_parent_name

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
help

Help string for this command.

If the help kwarg was passed into the decorator, it will default to that. If not, it will attempt to translate the docstring of the command’s callback function.

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
parents

Returns all parent commands of this command.

This is sorted by the length of qualified_name from highest to lowest. If the command has no parents, this will be an empty list.

Type:List[commands.Group]
qualified_name

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

Resets the cooldown on this command.

Parameters:ctx (Context) – The invocation context to reset the cooldown under.
root_parent

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.

set_default_rule(rule, guild_id)

Set the default rule for this cog or command.

Parameters:
  • rule (Optional[bool]) – The rule to set as default. If True for allow, False for deny and None for normal.
  • guild_id (int) – The guild to set the default rule in. When 0, this will set the global default rule.
short_doc

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
signature

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.

class redbot.core.commands.Group(*args, **kwargs)[source]

Bases: redbot.core.commands.commands.GroupMixin, redbot.core.commands.commands.Command, redbot.core.commands.commands.CogGroupMixin, discord.ext.commands.core.Group

Group command class for Red.

This class inherits from Command, with GroupMixin and discord.ext.commands.Group mixed in.

class redbot.core.commands.Context(**attrs)[source]

Bases: discord.ext.commands.context.Context

Command invocation context for Red.

All context passed into commands will be of this type.

This class inherits from discord.ext.commands.Context.

assume_yes

Whether or not interactive checks should be skipped and assumed to be confirmed.

This is intended for allowing automation of tasks.

An example of this would be scheduled commands not requiring interaction if the cog developer checks this value prior to confirming something interactively.

Depending on the potential impact of a command, it may still be appropriate not to use this setting.

Type:bool
permission_state

The permission state the current context is in.

Type:PermState
clean_prefix

The command prefix, but a mention prefix is displayed nicer.

Type:str
await embed_colour()[source]

Helper function to get the colour for an embed.

Returns:The colour to be used
Return type:discord.Colour
await embed_requested()[source]

Simple helper to call bot.embed_requested with logic around if embed permissions are available

Returns:True if an embed is requested
Return type:bool
await maybe_send_embed(message)[source]

Simple helper to send a simple message to context without manually checking ctx.embed_requested This should only be used for simple messages.

Parameters:

message (str) – The string to send

Returns:

the message which was sent

Return type:

discord.Message

Raises:
me

The bot member or user object.

If the context is DM, this will be a discord.User object.

Type:discord.abc.User
await react_quietly(reaction)[source]

Adds a reaction to to the command message.

Returns:True if adding the reaction succeeded.
Return type:bool
await send(content=None, **kwargs)[source]

Sends a message to the destination with the content given.

This acts the same as discord.ext.commands.Context.send, with one added keyword argument as detailed below in Other Parameters.

Parameters:

content (str) – The content of the message to send.

Other Parameters:
 
Returns:

The message that was sent.

Return type:

discord.Message

await send_help(command=None)[source]

Send the command help message.

await send_interactive(messages, box_lang=None, timeout=15)[source]

Send multiple messages interactively.

The user will be prompted for whether or not they would like to view the next message, one at a time. They will also be notified of how many messages are remaining on each prompt.

Parameters:
  • messages (iterable of str) – The messages to send.
  • box_lang (str) – If specified, each message will be contained within a codeblock of this language.
  • timeout (int) – How long the user has to respond to the prompt before it times out. After timing out, the bot deletes its prompt message.
await tick()[source]

Add a tick reaction to the command message.

Returns:True if adding the reaction succeeded.
Return type:bool
class redbot.core.commands.GuildContext(**attrs)[source]

Bases: redbot.core.commands.context.Context

At runtime, this will still be a normal context object.

This lies about some type narrowing for type analysis in commands using a guild_only decorator.

It is only correct to use when those types are already narrowed

class redbot.core.commands.DMContext(**attrs)[source]

Bases: redbot.core.commands.context.Context

At runtime, this will still be a normal context object.

This lies about some type narrowing for type analysis in commands using a dm_only decorator.

It is only correct to use when those types are already narrowed

commands.requires

This module manages the logic of resolving command permissions and requirements. This includes rules which override those requirements, as well as custom checks which can be overriden, and some special checks like bot permissions checks.

class redbot.core.commands.requires.PrivilegeLevel[source]

Bases: enum.IntEnum

Enumeration for special privileges.

ADMIN = 3

User has the admin role.

BOT_OWNER = 5

User is a bot owner.

GUILD_OWNER = 4

User is the guild level.

MOD = 2

User has the mod role.

NONE = 1

No special privilege level.

class redbot.core.commands.requires.PermState[source]

Bases: enum.Enum

Enumeration for permission states used by rules.

ACTIVE_ALLOW = 1

This command has been actively allowed, default user checks should be ignored.

ACTIVE_DENY = 5

This command has been actively denied, terminate the command chain.

ALLOWED_BY_HOOK = 6

This command has been actively allowed by a permission hook. check validation doesn’t need this, but is useful to developers

CAUTIOUS_ALLOW = 4

This command has been actively denied, but there exists a subcommand in the ACTIVE_ALLOW state. This occurs when PASSIVE_ALLOW and ACTIVE_DENY are combined.

DENIED_BY_HOOK = 7

This command has been actively denied by a permission hook check validation doesn’t need this, but is useful to developers

NORMAL = 2

No overrides have been set for this command, make determination from default user checks.

PASSIVE_ALLOW = 3

There exists a subcommand in the ACTIVE_ALLOW state, continue down the subcommand tree until we either find it or realise we’re on the wrong branch.

class redbot.core.commands.requires.Requires(privilege_level, user_perms, bot_perms, checks)[source]

Bases: object

This class describes the requirements for executing a specific command.

The permissions described include both bot permissions and user permissions.

checks

A list of checks which can be overridden by rules. Use Command.checks if you would like them to never be overridden.

Type:List[Callable[[Context], Union[bool, Awaitable[bool]]]]
privilege_level

The required privilege level (bot owner, admin, etc.) for users to execute the command. Can be None, in which case the user_perms will be used exclusively, otherwise, for levels other than bot owner, the user can still run the command if they have the required user_perms.

Type:PrivilegeLevel
ready_event

Event for when this Requires object has had its rules loaded. If permissions is loaded, this should be set when permissions has finished loading rules into this object. If permissions is not loaded, it should be set as soon as the command or cog is added.

Type:asyncio.Event
user_perms

The required permissions for users to execute the command. Can be None, in which case the privilege_level will be used exclusively, otherwise, it will pass whether the user has the required privilege_level _or_ user_perms.

Type:Optional[discord.Permissions]
bot_perms

The required bot permissions for a command to be executed. This is not overrideable by other conditions.

Type:discord.Permissions
DEFAULT: ClassVar[str] = 'default'

The key for the default rule in a rules dict.

GLOBAL: ClassVar[int] = 0

Should be used in place of a guild ID when setting/getting global rules.

clear_all_rules(guild_id, *, preserve_default_rule=True)[source]

Clear all rules of a particular scope.

Parameters:guild_id (int) – The guild ID to clear rules for. If set to Requires.GLOBAL, this will clear all global rules and leave all guild rules untouched.
Other Parameters:
 preserve_default_rule (bool) – Whether to preserve the default rule or not. This defaults to being preserved
get_rule(model, guild_id)[source]

Get the rule for a particular model.

Parameters:
  • model (Union[int, str, PermissionModel]) – The model to get the rule for. str is only valid for Requires.DEFAULT.
  • guild_id (int) – The ID of the guild for the rule’s scope. Set to Requires.GLOBAL for a global rule. If a global rule is set for a model, it will be prefered over the guild rule.
Returns:

The state for this rule. See the PermState class for an explanation.

Return type:

PermState

reset()[source]

Reset this Requires object to its original state.

This will clear all rules, including defaults. It also resets the Requires.ready_event.

set_rule(model_id, rule, guild_id)[source]

Set the rule for a particular model.

Parameters:
  • model_id (Union[str, int]) – The model to add a rule for. str is only valid for Requires.DEFAULT.
  • rule (PermState) – Which state this rule should be set as. See the PermState class for an explanation.
  • guild_id (int) – The ID of the guild for the rule’s scope. Set to Requires.GLOBAL for a global rule.
await verify(ctx)[source]

Check if the given context passes the requirements.

This will check the bot permissions, overrides, user permissions and privilege level.

Parameters:

ctx ("Context") – The invkokation context to check with.

Returns:

True if the context passes the requirements.

Return type:

bool

Raises:
  • BotMissingPermissions – If the bot is missing required permissions to run the command.
  • CommandError – Propogated from any permissions checks.

commands.converter

This module contains useful functions and classes for command argument conversion.

Some of the converters within are included provisionaly and are marked as such.

class redbot.core.commands.converter.APIToken

Bases: discord.ext.commands.converter.Converter

Converts to a dict object.

This will parse the input argument separating the key value pairs into a format to be used for the core bots API token storage.

This will split the argument by a space, comma, or semicolon and return a dict to be stored. Since all API’s are different and have different naming convention, this leaves the onus on the cog creator to clearly define how to setup the correct credential names for their cogs.

Note: Core usage of this has been replaced with DictConverter use instead.

Warning

This will be removed in the first minor release after 2020-08-05.

class redbot.core.commands.converter.DictConverter(*expected_keys, delims=None)[source]

Bases: discord.ext.commands.converter.Converter

Converts pairs of space seperated values to a dict

class redbot.core.commands.converter.GuildConverter(*, data, state)[source]

Bases: discord.guild.Guild

Converts to a discord.Guild object.

The lookup strategy is as follows (in order):

  1. Lookup by ID.
  2. Lookup by name.
class redbot.core.commands.converter.UserInputOptional[source]

Bases: typing.Generic

This can be used when user input should be converted as discord.py treats typing.Optional, but the type should not be equivalent to typing.Union[DesiredType, None] for type checking.

Warning

This converter class is still provisional.

This class may not play well with mypy yet and may still require you guard this in a type checking conditional import vs the desired types

We’re aware and looking into improving this.

class redbot.core.commands.converter.NoParseOptional[source]

Bases: object

This can be used instead of typing.Optional to avoid discord.py special casing the conversion behavior.

Warning

This converter class is still provisional.

See also

The ignore_optional_for_conversion option of commands.

class redbot.core.commands.converter.TimedeltaConverter(*, minimum=None, maximum=None, allowed_units=None, default_unit=None)[source]

Bases: discord.ext.commands.converter.Converter

This is a converter for timedeltas. The units should be in order from largest to smallest. This works with or without whitespace.

See parse_timedelta for more information about how this functions.

maximum

If provided, any parsed value higher than this will raise an exception

Type:Optional[timedelta]
minimum

If provided, any parsed value lower than this will raise an exception

Type:Optional[timedelta]
allowed_units

If provided, you can constrain a user to expressing the amount of time in specific units. The units you can choose to provide are the same as the parser understands: (weeks, days, hours, minutes, seconds)

Type:Optional[List[str]]
default_unit

If provided, it will additionally try to match integer-only input into a timedelta, using the unit specified. Same units as in allowed_units apply.

Type:Optional[str]
redbot.core.commands.converter.get_dict_converter(*expected_keys, delims=None)[source]

Returns a typechecking safe DictConverter suitable for use with discord.py

redbot.core.commands.converter.get_timedelta_converter(*, default_unit=None, maximum=None, minimum=None, allowed_units=None)[source]

This creates a type suitable for typechecking which works with discord.py’s commands.

See parse_timedelta for more information about how this functions.

Parameters:
  • maximum (Optional[timedelta]) – If provided, any parsed value higher than this will raise an exception
  • minimum (Optional[timedelta]) – If provided, any parsed value lower than this will raise an exception
  • allowed_units (Optional[List[str]]) – If provided, you can constrain a user to expressing the amount of time in specific units. The units you can choose to provide are the same as the parser understands: (weeks, days, hours, minutes, seconds)
  • default_unit (Optional[str]) – If provided, it will additionally try to match integer-only input into a timedelta, using the unit specified. Same units as in allowed_units apply.
Returns:

The converter class, which will be a subclass of TimedeltaConverter

Return type:

type

redbot.core.commands.converter.parse_timedelta(argument, *, maximum=None, minimum=None, allowed_units=None)[source]

This converts a user provided string into a timedelta

The units should be in order from largest to smallest. This works with or without whitespace.

Parameters:
  • argument (str) – The user provided input
  • maximum (Optional[timedelta]) – If provided, any parsed value higher than this will raise an exception
  • minimum (Optional[timedelta]) – If provided, any parsed value lower than this will raise an exception
  • allowed_units (Optional[List[str]]) – If provided, you can constrain a user to expressing the amount of time in specific units. The units you can chose to provide are the same as the parser understands. (weeks, days, hours, minutes, seconds)
Returns:

If matched, the timedelta which was parsed. This can return None

Return type:

Optional[timedelta]

Raises:

BadArgument – If the argument passed uses a unit not allowed, but understood or if the value is out of bounds.

class redbot.core.commands.converter.Literal(valid_names)[source]

Bases: discord.ext.commands.converter.Converter

This can be used as a converter for typing.Literal.

In a type checking context it is typing.Literal. In a runtime context, it’s a converter which only matches the literals it was given.

Warning

This converter class is still provisional.