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.
Cog
(*args, **kwargs)[source]¶ Bases:
redbot.core.commands.commands.CogMixin
,discord.ext.commands.cog.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]
withctx.clean_prefix
substitute
[botname]
withctx.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.
-
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
- Raises
RedUnhandledAPI – If the method was not overridden, or an overridden implementation is not handling this
-
-
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.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
-
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
-
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.
-
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.
-
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 ofRequires.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 toFalse
.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 toFalse
.
-
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.
-
clean_params
¶ OrderedDict[
str
,inspect.Parameter
]: Retrieves the parameter OrderedDict without the context or self parameters.Useful for inspecting signature.
-
deny_to
(model_id, guild_id)¶ Actively deny this command to the given model.
-
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
-
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
-
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
withunhandled_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]
withctx.clean_prefix
substitute
[botname]
withctx.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.
-
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 detailsCog creators may override this in their own command and cog classes as long as the method signature stays the same.
-
format_text_for_context
(ctx, text)¶ This formats text based on values in context
The steps are (currently, roughly) the following:
substitute
[p]
withctx.clean_prefix
substitute
[botname]
withctx.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
-
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 beone two
.- Type
-
get_cooldown_retry_after
(ctx)[source]¶ Retrieves the amount of seconds before this command can be tried again.
New in version 1.4.
-
has_error_handler
()[source]¶ bool
: Checks whether the command has an error handler registered.New in version 1.7.
-
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.
-
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 beone two three
.- Type
-
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 isa
.- Type
Optional[
Command
]
-
set_default_rule
(rule, guild_id)¶ Set the default rule for this cog or command.
-
-
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
, withGroupMixin
anddiscord.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
-
clean_prefix
¶ The command prefix, but with a sanitized version of the bot’s mention if it was used as prefix. This can be used in a context where discord user mentions might not render properly.
- Type
-
await
embed_colour
()[source]¶ Helper function to get the colour for an embed.
- Returns
The colour to be used
- Return type
-
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
-
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
- Raises
-
me
¶ The bot member or user object.
If the context is DM, this will be a
discord.User
object.- Type
-
await
react_quietly
(reaction)[source]¶ Adds a reaction to the command message.
- Returns
True
if adding the reaction succeeded.- Return type
-
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
-
-
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 overridden, and some special checks like bot permissions checks.
-
class
redbot.core.commands.requires.
PermState
(value)[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 swaps this out, but the information may be useful to developers. It is treated as
ACTIVE_ALLOW
for the current command andPASSIVE_ALLOW
for subcommands.
-
CAUTIOUS_ALLOW
= 4¶ This command has been actively denied, but there exists a subcommand in the
ACTIVE_ALLOW
state. This occurs whenPASSIVE_ALLOW
andACTIVE_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.
-
-
class
redbot.core.commands.requires.
PrivilegeLevel
(value)[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.
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.
-
privilege_level
¶ The required privilege level (bot owner, admin, etc.) for users to execute the command. Can be
None
, in which case theuser_perms
will be used exclusively, otherwise, for levels other than bot owner, the user can still run the command if they have the requireduser_perms
.- Type
-
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
-
user_perms
¶ The required permissions for users to execute the command. Can be
None
, in which case theprivilege_level
will be used exclusively, otherwise, it will pass whether the user has the requiredprivilege_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
-
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 forRequires.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
-
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 forRequires.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
- 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 totyping.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.
DictConverter
(*expected_keys, delims=None)[source]¶ Bases:
discord.ext.commands.converter.Converter
Converts pairs of space separated values to a dict
-
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.
-
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.
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]
-
-
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
-
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.
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.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.
-
class
redbot.core.commands.help.
HelpSettings
(page_char_limit=1000, max_pages_in_guild=2, use_menus=False, show_hidden=False, show_aliases=True, verify_checks=True, verify_exists=False, tagline='', delete_delay=0, use_tick=False)[source]¶ Bases:
object
A representation of help settings.
Warning
This class is provisional.
-
pretty
¶ Returns a discord safe representation of the settings
-
-
class
redbot.core.commands.help.
RedHelpFormatter
[source]¶ Bases:
redbot.core.commands.help.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.
-
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