Warning

This document is for Red's development version, which can be significantly different from previous releases. If you're a regular user, you should read the Red documentation for the current stable release.

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.hybrid_command(name=..., *, with_app_command=True, **attrs)[source]

A decorator which transforms an async function into a HybridCommand.

Same interface as discord.ext.commands.hybrid_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.

redbot.core.commands.hybrid_group(name=..., *, with_app_command=True, **attrs)[source]

A decorator which transforms an async function into a HybridGroup.

Same interface as discord.ext.commands.hybrid_group.

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

Bases: CogMixin, Cog

Red’s Cog base class

This includes a metaclass from discord.py

Warning

None of your methods should start with red_ or be dunder names which start with red (eg. __red_test_thing__) unless to override behavior in a method designed to be overridden, as this prefix is reserved for future methods in order to be able to add features non-breakingly.

Attributes and methods must remain compatible with discord.py and with any of red’s methods and attributes.

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

await red_get_data_for_user(*, user_id)

Note

This method is documented provisionally and may have minor changes made to it. It is not expected to undergo major changes, but nothing utilizes this method yet and the inclusion of this method in documentation in advance is solely to allow cog creators time to prepare.

This should be overridden by all cogs.

Overridden implementations should return a mapping of filenames to io.BytesIO containing a human-readable version of the data the cog has about the specified user_id or an empty mapping if the cog does not have end user data.

The data should be easily understood for what it represents to most users of age to use Discord.

You may want to include a readme file which explains specifics about the data.

This method may also be implemented for an extension.

Parameters:

user_id (int) –

Returns:

A mapping of filenames to BytesIO objects suitable to send as a files or as part of an archive to a user.

This may be empty if you don’t have data for users.

Return type:

MutableMapping[str, io.BytesIO]

Raises:

RedUnhandledAPI – If the method was not overridden, or an overridden implementation is not handling this

await red_delete_data_for_user(*, requester, user_id)

This should be overridden by all cogs.

If your cog does not store data, overriding and doing nothing should still be done to indicate that this has been considered.

Note

This may receive other strings in the future without warning you should safely handle any string value (log a warning if needed) as additional requester types may be added in the future without prior warning. (see what this method can raise for details)

This method can currently be passed one of these strings:

  • "discord_deleted_user":

    The request should be processed as if Discord has asked for the data removal This then additionally must treat the user ID itself as something to be deleted. The user ID is no longer operational data as the ID no longer refers to a valid user.

  • "owner":

    The request was made by the bot owner. If removing the data requested by the owner would be an operational hazard (such as removing a user id from a blocked user list) you may elect to inform the user of an alternative way to remove that ID to ensure the process can not be abused by users to bypass anti-abuse measures, but there must remain a way for them to process this request.

  • "user_strict":

    The request was made by a user, the bot settings allow a user to request their own data be deleted, and the bot is configured to respect this at the cost of functionality. Cogs may retain data needed for anti abuse measures such as IDs and timestamps of interactions, but should not keep EUD such as user nicknames if receiving a request of this nature.

  • "user":

    The request was made by a user, the bot settings allow a user to request their own data be deleted, and the bot is configured to let cogs keep data needed for operation. Under this case, you may elect to retain data which is essential to the functionality of the cog. This case will only happen if the bot owner has opted into keeping minimal EUD needed for cog functionality.

Parameters:
  • requester (Literal["discord_deleted_user", "owner", "user", "user_strict"]) – See above notes for details about this parameter

  • user_id (int) – The user ID which needs deletion handling

Raises:

RedUnhandledAPI – If the method was not overridden, or an overridden implementation is not handling this

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

Bases: Cog, GroupCog

Red’s Cog base class with app commands group as the base.

This class inherits from Cog and discord.ext.commands.GroupCog

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

Bases: CogCommandMixin, 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.

Warning

If you subclass this command, attributes and methods must remain compatible.

None of your methods should start with red_ or be dunder names which start with red (eg. __red_test_thing__) unless to override behavior in a method designed to be overridden, as this prefix is reserved for future methods in order to be able to add features non-breakingly.

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.

Changed in version 2.0: func parameter is now positional-only.

See also

The check() decorator

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.

Changed in version 2.0: coro parameter is now positional-only.

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.

Changed in version 2.0: coro parameter is now positional-only.

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

property clean_params

Dict[str, Parameter]: Retrieves the parameter dictionary 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.

property cog_name

The name of the cog this command belongs to, if any.

Type:

Optional[str]

property cooldown

The cooldown of a command when invoked or None if the command doesn’t have a registered cooldown.

New in version 2.0.

Type:

Optional[Cooldown]

copy()[source]

Creates a copy of this command.

Returns:

A new instance of this command.

Return type:

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.

This is generally called by the settings managed with the [p]command disable global/server commands. Any changes made outside of that will not persist after cog reload and may also be affected when either of those commands is called on this command. It is not recommended to rely on this method, if you want a consistent behavior.

Parameters:

guild (discord.Guild) – The guild to disable the command in.

Returns:

True if the command wasn’t already disabled.

Return type:

bool

enable_in(guild)[source]

Enable this command in the given guild.

This is generally called by the settings managed with the [p]command disable global/server commands. Any changes made outside of that will not persist after cog reload and may also be affected when either of those commands is called on this command. It is not recommended to rely on this method, if you want a consistent behavior.

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, MyErrorType):
        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 and cog 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

property 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

get_cooldown_retry_after(ctx, /)[source]

Retrieves the amount of seconds before this command can be tried again.

New in version 1.4.

Changed in version 2.0: ctx parameter is now positional-only.

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]

bool: Checks whether the command has an error handler registered.

New in version 1.7.

property 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_enabled(guild=None)[source]

Check if the command is enabled globally or in a guild.

When guild is provided, this method checks whether the command is enabled both globally and in the guild.

This is generally set by the settings managed with the [p]command enable/disable global/server commands.

Parameters:

guild (discord.abc.Snowflake, optional) – The guild to check that the command is enabled in. If this is None, this will check whether the command is enabled globally.

Returns:

True if the command is enabled.

Return type:

bool

is_on_cooldown(ctx, /)[source]

Checks whether the command is currently on cooldown.

Changed in version 2.0: ctx parameter is now positional-only.

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

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]

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

Changed in version 2.0: func parameter is now positional-only.

Parameters:

func – The function to remove from the checks.

reset_cooldown(ctx, /)[source]

Resets the cooldown on this command.

Changed in version 2.0: ctx parameter is now positional-only.

Parameters:

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

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

Type:

Optional[Group]

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.

property 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

property 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.HybridCommand(*args, **kwargs)[source]

Bases: Command, HybridCommand[_CogT, _P, _T]

HybridCommand class for Red.

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

This class inherits from Command and discord.ext.commands.HybridCommand.

Warning

This class is not intended to be subclassed.

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

Bases: GroupMixin, Command, CogGroupMixin, Group

Group command class for Red.

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

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

Bases: Group, HybridGroup[_CogT, _P, _T]

HybridGroup command class for Red.

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

This class inherits from Group and discord.ext.commands.HybridGroup.

Warning

This class is not intended to be subclassed.

command(name=..., *args, **kwargs)[source]

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

group(name=..., *args, **kwargs)[source]

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

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

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

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]

Short-hand for calling bot.embed_requested with permission checks.

Equivalent to:

await ctx.bot.embed_requested(ctx)
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:
property 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, *, message=None)[source]

Adds a reaction to the command message.

Parameters:

reaction (Union[discord.Emoji, discord.Reaction, discord.PartialEmoji, str]) – The emoji to react with.

Keyword Arguments:

message (str, optional) – The message to send if adding the reaction doesn’t succeed.

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.

  • filter (callable (str) -> str, optional) – A function which is used to filter the content before it is sent. This must take a single str as an argument, and return the processed str. When None is passed, content won’t be touched. Defaults to None.

  • **kwargs – See discord.ext.commands.Context.send.

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, join_character='')[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 code block 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.

  • join_character (str) – The character used to join all the messages when the file output is selected.

Returns:

A list of sent messages.

Return type:

List[discord.Message]

await tick(*, message=None)[source]

Add a tick reaction to the command message.

Keyword Arguments:

message (str, optional) – The message to send if adding the reaction doesn’t succeed.

Returns:

True if adding the reaction succeeded.

Return type:

bool

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

Bases: 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: 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 overridden, and some special checks like bot permissions checks.

class redbot.core.commands.requires.PermState(value)[source]

Bases: 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 swaps this out, but the information may be useful to developers. It is treated as ACTIVE_ALLOW for the current command and PASSIVE_ALLOW for subcommands.

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 swaps this out, but the information may be useful to developers. It is treated as ACTIVE_DENY for the current command and any subcommands.

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.

classmethod from_bool(value)[source]

Get a PermState from a bool or NoneType.

class redbot.core.commands.requires.PrivilegeLevel(value)[source]

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

classmethod await from_ctx(ctx)[source]

Get a command author’s PrivilegeLevel based on context.

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 = 'default'

The key for the default rule in a rules dict.

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

  • 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 preferred 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 invocation 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 – Propagated from any permissions checks.

commands.converter

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

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

redbot.core.commands.converter.UserInputOptional

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.

Note: In type checking context, this type hint can be passed multiple types, but such usage is not supported and will fail at runtime

Warning

This converter class is still provisional.

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

Bases: Converter

Converts a cog name to the matching redbot.core.commands.Cog object.

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

Bases: Converter

Converts a command name to the matching redbot.core.commands.Command object.

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

Bases: Converter

Converts pairs of space separated values to a dict

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.

See also

The ignore_optional_for_conversion option of commands.

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

Bases: Converter

Converts ID or user mention to an int.

Useful for commands like [p]ban or [p]unban where the bot is not necessarily going to share any servers with the user that a moderator wants to ban/unban.

This converter doesn’t check if the ID/mention points to an actual user but it won’t match IDs and mentions that couldn’t possibly be valid.

For example, the converter will not match on “123” because the number doesn’t have enough digits to be valid ID but, it will match on “12345678901234567” even though there is no user with such ID.

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

Bases: Converter

This is a converter for relative deltas.

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

See parse_relativedelta for more information about how this functions.

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: (years, months, 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]

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

Bases: 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[datetime.timedelta]

minimum

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

Type:

Optional[datetime.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.finite_float(arg)[source]

This converts a user provided string into a finite float.

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[datetime.timedelta]) – If provided, any parsed value higher than this will raise an exception

  • minimum (Optional[datetime.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_relativedelta(argument, *, allowed_units=None)[source]

This converts a user provided string into a datetime with offset from NOW

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

Parameters:
  • argument (str) – The user provided input

  • 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. (years, months, weeks, days, hours, minutes, seconds)

Returns:

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

Return type:

Optional[dateutil.relativedelta.relativedelta]

Raises:

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

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[datetime.timedelta]) – If provided, any parsed value higher than this will raise an exception

  • minimum (Optional[datetime.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[datetime.timedelta]

Raises:

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

redbot.core.commands.converter.positive_int = Range[int, 0, None]

This converts a user provided string into a positive (>=0) integer.

Help Functionality

Warning

The content in this section is provisional and may change without prior notice or warning. Updates to this will be communicated on this issue

class redbot.core.commands.help.HelpFormatterABC[source]

Bases: ABC

Describes the required interface of a help formatter.

Additional notes for 3rd party developers are included in this class.

Note

You may define __init__ however you want (such as to include config), Red will not initialize a formatter for you, and must be passed an initialized formatter.

If you want to use Red’s existing settings, use HelpSettings.from_context

Warning

This class is documented but provisional with expected changes.

In the future, this class will receive changes to support invoking the help command without context.

abstractmethod await send_help(ctx, help_for=None, *, from_help_command=False)[source]

This is (currently) the only method you must implement.

This method should handle any and all errors which may arise.

The types subclasses must handle are defined as HelpTarget

class redbot.core.commands.help.HelpSettings(page_char_limit=1000, max_pages_in_guild=2, use_menus=HelpMenuSetting.disabled, show_hidden=False, show_aliases=True, verify_checks=True, verify_exists=False, tagline='', delete_delay=0, use_tick=False, react_timeout=30)[source]

Bases: object

A representation of help settings.

Warning

This class is provisional.

classmethod await from_context(context)[source]

Get the HelpSettings for the current context

property pretty

Returns a discord safe representation of the settings

class redbot.core.commands.help.RedHelpFormatter[source]

Bases: HelpFormatterABC

Red’s help implementation

This is intended to be overridable in parts to only change some behavior.

While this exists as a class for easy partial overriding, most implementations should not need or want a shared state.

Warning

This class is documented but may receive changes between versions without warning as needed. The supported way to modify help is to write a separate formatter.

The primary reason for this class being documented is to allow the opaque use of the class as a fallback, as any method in base class which is intended for use will be present and implemented here.

Note

This class may use various internal methods which are not safe to use in third party code. The internal methods used here may change, with this class being updated at the same time.

await command_not_found(ctx, help_for, help_settings)[source]

Sends an error, fuzzy help, or stays quiet based on settings

staticmethod async for ... in help_filter_func(ctx, objects, help_settings, bypass_hidden=False)[source]

This does most of actual filtering.

staticmethod parse_command(ctx, help_for)[source]

Handles parsing

await send_help(ctx, help_for=None, *, from_help_command=False)[source]

This delegates to other functions.

For most cases, you should use this and only this directly.

await send_pages(ctx, pages, embed=True, help_settings=None)[source]

Sends pages based on settings.

await subcommand_not_found(ctx, command, not_found, help_settings)[source]

Sends an error