Bot
Red
- class redbot.core.bot.Red(*args, cli_flags=None, bot_dir=PosixPath('/home/docs/checkouts/readthedocs.org/user_builds/red-discordbot/checkouts/stable/docs'), **kwargs)[source]
Bases:
GroupMixin
,RPCMixin
,AutoShardedBot
Our subclass of discord.ext.commands.AutoShardedBot
- register_rpc_handler(method)
Registers a method to act as an RPC handler if the internal RPC server is active.
When calling this method through the RPC server, use the naming scheme “cogname__methodname”.
Important
All parameters to RPC handler methods must be JSON serializable objects. The return value of handler methods must also be JSON serializable.
Important
RPC support is included in Red on a provisional basis. Backwards incompatible changes (up to and including removal of the RPC) may occur if deemed necessary.
- Parameters:
method (coroutine) – The method to register with the internal RPC server.
- unregister_rpc_handler(method)
Deregisters an RPC method handler.
This will be called automatically for you on cog unload and will pass silently if the method is not previously registered.
Important
RPC support is included in Red on a provisional basis. Backwards incompatible changes (up to and including removal of the RPC) may occur if deemed necessary.
- Parameters:
method (coroutine) – The method to unregister from the internal RPC server.
- await add_cog(cog, /, *, override=False, guild=..., guilds=...)[source]
-
Adds a “cog” to the bot.
A cog is a class that has its own event listeners and commands.
If the cog is a
app_commands.Group
then it is added to the bot’sCommandTree
as well.Note
Exceptions raised inside a
Cog
’scog_load()
method will be propagated to the caller.Changed in version 2.0:
ClientException
is raised when a cog with the same name is already loaded.Changed in version 2.0:
cog
parameter is now positional-only.Changed in version 2.0: This method is now a coroutine.
- Parameters:
cog (
Cog
) – The cog to register to the bot.override (
bool
) –If a previously loaded cog with the same name should be ejected instead of raising an error.
New in version 2.0.
guild (Optional[
Snowflake
]) –If the cog is an application command group, then this would be the guild where the cog group would be added to. If not given then it becomes a global command instead.
New in version 2.0.
guilds (List[
Snowflake
]) –If the cog is an application command group, then this would be the guilds where the cog group would be added to. If not given then it becomes a global command instead. Cannot be mixed with
guild
.New in version 2.0.
- Raises:
- add_command(command, /)[source]
Adds a
Command
into the internal list of commands.This is usually not called, instead the
command()
orgroup()
shortcut decorators are used instead.Changed in version 1.4: Raise
CommandRegistrationError
instead of genericClientException
Changed in version 2.0:
command
parameter is now positional-only.
- add_dev_env_value(name, value)[source]
Add a custom variable to the dev environment (
[p]debug
,[p]eval
, and[p]repl
commands). If dev mode is disabled, nothing will happen.Example
class MyCog(commands.Cog): def __init__(self, bot): self.bot = bot bot.add_dev_env_value("mycog", lambda ctx: self) bot.add_dev_env_value("mycogdata", lambda ctx: self.settings[ctx.guild.id]) def cog_unload(self): self.bot.remove_dev_env_value("mycog") self.bot.remove_dev_env_value("mycogdata")
Once your cog is loaded, the custom variables
mycog
andmycogdata
will be included in the environment of dev commands.- Parameters:
name (str) – The name of your custom variable.
value (Callable[[commands.Context], Any]) – The function returning the value of the variable. It must take a
commands.Context
as its sole parameter
- Raises:
TypeError –
value
argument isn’t a callable.ValueError – The passed callable takes no or more than one argument.
RuntimeError – The name of the custom variable is either reserved by a variable from the default environment or already taken by some other custom variable.
- add_permissions_hook(hook)[source]
Add a permissions hook.
Permissions hooks are check predicates which are called before calling
Requires.verify
, and they can optionally return an override:True
to allow,False
to deny, andNone
to default to normal behaviour.- Parameters:
hook – A command check predicate which returns
True
,False
orNone
.
- await add_to_blacklist(users_or_roles, *, guild=None)[source]
Add users or roles to the global or local blocklist.
- Parameters:
users_or_roles (Iterable[Union[int, discord.Role, discord.Member, discord.User]]) – The items to add to the blocklist. Roles and role IDs should only be passed when updating a local blocklist.
guild (Optional[discord.Guild]) – The guild, whose local blocklist should be modified. If not passed, the global blocklist will be modified.
- Raises:
TypeError – The values passed were not of the proper type.
- await add_to_whitelist(users_or_roles, *, guild=None)[source]
Add users or roles to the global or local allowlist.
- Parameters:
users_or_roles (Iterable[Union[int, discord.Role, discord.Member, discord.User]]) – The items to add to the allowlist. Roles and role IDs should only be passed when updating a local allowlist.
guild (Optional[discord.Guild]) – The guild, whose local allowlist should be modified. If not passed, the global allowlist will be modified.
- Raises:
TypeError – The passed values were not of the proper type.
- await allowed_by_whitelist_blacklist(who=None, *, who_id=None, guild=None, role_ids=None)[source]
This checks if a user or member is allowed to run things, as considered by Red’s allowlist and blocklist.
If given a user object, this function will check the global lists
If given a member, this will additionally check guild lists
If omitting a user or member, you must provide a value for
who_id
You may also provide a value for
guild
in this caseIf providing a member by guild and member ids, you should supply
role_ids
as well- Parameters:
who (Optional[Union[discord.Member, discord.User]]) – The user or member object to check
who_id (Optional[int]) – The id of the user or member to check If not providing a value for
who
, this is a required parameter.guild (Optional[discord.Guild]) – When used in conjunction with a provided value for
who_id
, checks the lists for the corresponding guild as well. This is ignored whenwho
is passed.role_ids (Optional[List[int]]) – When used with both
who_id
andguild
, checks the role ids provided. This is required for accurate checking of members in a guild if providing ids. This is ignored whenwho
is passed.
- Raises:
TypeError – Did not provide
who
orwho_id
- Returns:
- Return type:
- await before_identify_hook(shard_id, *, initial=False)[source]
A hook that is called before IDENTIFYing a session. Same as in discord.py, but also dispatches “on_red_identify” bot event.
- before_invoke(coro, /)[source]
Overridden decorator method for Red’s
before_invoke
behavior.This can safely be used purely functionally as well.
3rd party cogs should remove any hooks which they register at unload using
remove_before_invoke_hook
Below behavior shared with discord.py:
Note
The
before_invoke
hooks are only called if all checks and argument parsing procedures pass without error. If any check or argument parsing procedures fail then the hooks are not called.- Parameters:
coro (Callable[[commands.Context], Awaitable[Any]]) – The coroutine to register as the pre-invoke hook.
- Raises:
TypeError – The coroutine passed is not actually a coroutine.
- await clear_blacklist(guild=None)[source]
Clears the global or local blocklist.
- Parameters:
guild (Optional[discord.Guild]) – The guild, whose local blocklist should be cleared. If not passed, the global blocklist will be cleared.
- clear_permission_rules(guild_id, **kwargs)[source]
Clear all permission overrides in a scope.
- Parameters:
guild_id (Optional[int]) – The guild ID to wipe permission overrides for. If
None
, this will clear all global rules and leave all guild rules untouched.**kwargs – Keyword arguments to be passed to each required call of
commands.Requires.clear_all_rules
- await clear_whitelist(guild=None)[source]
Clears the global or local allowlist.
- Parameters:
guild (Optional[discord.Guild]) – The guild, whose local allowlist should be cleared. If not passed, the global allowlist will be cleared.
- await cog_disabled_in_guild(cog, guild)[source]
Check if a cog is disabled in a guild
- Parameters:
cog (commands.Cog) –
guild (Optional[discord.Guild]) –
- Return type:
- await cog_disabled_in_guild_raw(cog_name, guild_id)[source]
Check if a cog is disabled in a guild without the cog or guild object
- await disable_app_command(command_name, command_type=<AppCommandType.chat_input: 1>)[source]
Mark an application command as being disabled.
Disabled commands are not added to the bot’s tree, are not able to be synced, and cannot be invoked.
- await embed_requested(channel, *, command=None, check_permissions=True)[source]
Determine if an embed is requested for a response.
- Parameters:
channel (Union[
discord.TextChannel
,discord.VoiceChannel
,discord.StageChannel
,commands.Context
,discord.User
,discord.Member
,discord.Thread
]) – The target messageable object to check embed settings for.- Keyword Arguments:
command (
redbot.core.commands.Command
, optional) – The command ran. This is auto-filled whenchannel
is passed with command context.check_permissions (
bool
) – IfTrue
, this method will also check whether the bot can send embeds in the given channel and if it can’t, it will returnFalse
regardless of the bot’s embed settings.
- Returns:
True
if an embed is requested- Return type:
- Raises:
TypeError – When the passed channel is of type
discord.GroupChannel
,discord.DMChannel
, ordiscord.PartialMessageable
.
- await enable_app_command(command_name, command_type=<AppCommandType.chat_input: 1>)[source]
Mark an application command as being enabled.
Enabled commands are able to be added to the bot’s tree, are able to be synced, and can be invoked.
- Raises:
CommandLimitReached – Raised when attempting to enable a command that would exceed the command limit.
- await get_blacklist(guild=None)[source]
Get the global or local blocklist.
- Parameters:
guild (Optional[discord.Guild]) – The guild to get the local blocklist for. If this is not passed, the global blocklist will be returned.
- Returns:
The IDs of the blocked users/roles.
- Return type:
Set[int]
- get_cog(name, /)[source]
Gets the cog instance requested.
If the cog is not found,
None
is returned instead.Changed in version 2.0:
name
parameter is now positional-only.- Parameters:
name (
str
) – The name of the cog you are requesting. This is equivalent to the name passed via keyword argument in class creation or the class name if unspecified.- Returns:
The cog that was requested. If not found, returns
None
.- Return type:
Optional[
Cog
]
- get_command(name, /)[source]
Get a
Command
from the internal list of commands.This could also be used as a way to get aliases.
The name could be fully qualified (e.g.
'foo bar'
) will get the subcommandbar
of the group commandfoo
. If a subcommand is not found thenNone
is returned just as usual.Changed in version 2.0:
name
parameter is now positional-only.- Parameters:
name (
str
) – The name of the command to get.- Returns:
The command that was requested. If not found, returns
None
.- Return type:
Optional[
Command
]
- await get_embed_colour(location)
Get the embed color for a location. This takes into account all related settings.
- Parameters:
location (
discord.abc.Messageable
) – Location to check embed color for.- Returns:
Embed color for the provided location.
- Return type:
discord.Color
- await get_invite_url()[source]
Generates the invite URL for the bot.
Does not check if the invite URL is configured to be public with
[p]inviteset public
. To check if invites are public, useRed.is_invite_url_public()
.- Returns:
Invite URL.
- Return type:
- await get_or_fetch_member(guild, member_id)[source]
Retrieves a
discord.Member
from a guild and a member ID.Warning
This method may make an API call if the user is not found in the bot cache. For general usage, consider
discord.Guild.get_member
instead.- Parameters:
guild (discord.Guild) – The guild which the member should be retrieved from.
member_id (int) – The ID of the member that should be retrieved.
- Raises:
Errors – Please refer to
discord.Guild.fetch_member
.- Returns:
The user you requested.
- Return type:
- await get_or_fetch_user(user_id)[source]
Retrieves a
discord.User
based on their ID. You do not have to share any guilds with the user to get this information, however many operations do require that you do.Warning
This method may make an API call if the user is not found in the bot cache. For general usage, consider
bot.get_user
instead.- Parameters:
user_id (int) – The ID of the user that should be retrieved.
- Raises:
Errors – Please refer to
discord.Client.fetch_user
.- Returns:
The user you requested.
- Return type:
Gets the shared API tokens for a service, or all of them if no argument specified.
- Parameters:
service_name (str, optional) – The service to get tokens for. Leave empty to get tokens for all services.
- Returns:
A Mapping of token names to tokens. This mapping exists because some services have multiple tokens. If
service_name
isNone
, this method will return a mapping with mappings for all services.- Return type:
- await get_valid_prefixes(guild=None)[source]
This gets the valid prefixes for a guild.
If not provided a guild (or passed None) it will give the DM prefixes.
This is just a fancy wrapper around
get_prefix
- Parameters:
guild (Optional[discord.Guild]) – The guild you want prefixes for. Omit (or pass None) for the DM prefixes
- Returns:
If a guild was specified, the valid prefixes in that guild. If a guild was not specified, the valid prefixes for DMs
- Return type:
List[str]
- await get_whitelist(guild=None)[source]
Get the global or local allowlist.
- Parameters:
guild (Optional[discord.Guild]) – The guild to get the local allowlist for. If this is not passed, the global allowlist will be returned.
- Returns:
The IDs of the allowed users/roles.
- Return type:
Set[int]
- await handle_data_deletion_request(*, requester, user_id)[source]
This tells each cog and extension, as well as any APIs in Red to go delete data
Calling this should be limited to interfaces designed for it.
See
redbot.core.commands.Cog.delete_data_for_user
for details about the parameters and intent.- Parameters:
requester –
user_id –
- Returns:
A named tuple
(failed_modules, failed_cogs, unhandled)
containing lists with names of failed modules, failed cogs, and cogs that didn’t handle data deletion request.- Return type:
DataDeletionResults
- hybrid_command(name=..., with_app_command=True, *args, **kwargs)[source]
A shortcut decorator that invokes
hybrid_command()
and adds it to the internal command list viaadd_command()
.- Returns:
A decorator that converts the provided method into a Command, adds it to the bot, then returns it.
- Return type:
Callable[…,
HybridCommand
]
- hybrid_group(name=..., with_app_command=True, *args, **kwargs)[source]
A shortcut decorator that invokes
hybrid_group()
and adds it to the internal command list viaadd_command()
.- Returns:
A decorator that converts the provided method into a Group, adds it to the bot, then returns it.
- Return type:
Callable[…,
HybridGroup
]
- await ignored_channel_or_guild(ctx)[source]
This checks if the bot is meant to be ignoring commands in a channel or guild, as considered by Red’s whitelist and blacklist.
- Parameters:
ctx – Context object of the command which needs to be checked prior to invoking or a Message object which might be intended for use as a command or an Interaction object which might be intended for use with a command.
- Returns:
True
if commands are allowed in the channel,False
otherwise- Return type:
- Raises:
TypeError –
ctx.channel
is adiscord.PartialMessageable
with atype
other thandiscord.ChannelType.private
- await is_automod_immune(to_check)[source]
Checks if the user, message, context, or role should be considered immune from automated moderation actions.
This will return
False
in direct messages.- Parameters:
to_check (
discord.Message
orcommands.Context
ordiscord.abc.User
ordiscord.Role
) – Something to check if it would be immune- Returns:
True
if immune- Return type:
- await is_invite_url_public()[source]
Determines if invite URL is configured to be public with
[p]inviteset public
.- Returns:
True
if the invite URL is public.- Return type:
- await is_owner(user, /)[source]
Determines if the user should be considered a bot owner.
This takes into account CLI flags and application ownership.
By default, application team members are not considered owners, while individual application owners are.
- Parameters:
user (Union[discord.User, discord.Member]) –
- Return type:
- await load_extension(spec)[source]
-
Loads an extension.
An extension is a python module that contains commands, cogs, or listeners.
An extension must have a global function,
setup
defined as the entry point on what to do when the extension is loaded. This entry point must have a single argument, thebot
.Changed in version 2.0: This method is now a coroutine.
- Parameters:
name (
str
) – The extension name to load. It must be dot separated like regular Python imports if accessing a sub-module. e.g.foo.test
if you want to importfoo/test.py
.package (Optional[
str
]) –The package name to resolve relative imports with. This is required when loading an extension using a relative path, e.g
.foo.test
. Defaults toNone
.New in version 1.7.
- Raises:
ExtensionNotFound – The extension could not be imported. This is also raised if the name of the extension could not be resolved using the provided
package
parameter.ExtensionAlreadyLoaded – The extension is already loaded.
NoEntryPointError – The extension does not have a setup function.
ExtensionFailed – The extension or its setup function had an execution error.
- await message_eligible_as_command(message)[source]
Runs through the things which apply globally about commands to determine if a message may be responded to as a command.
This can’t interact with permissions as permissions is hyper-local with respect to command objects, create command objects for this if that’s needed.
This also does not check for prefix or command conflicts, as it is primarily designed for non-prefix based response handling via on_message_without_command
- Parameters:
message – The message object to check
- Returns:
Whether or not the message is eligible to be treated as a command.
- Return type:
- await process_commands(message, /)[source]
Same as base method, but dispatches an additional event for cogs which want to handle normal messages differently to command messages, without the overhead of additional get_context calls per cog.
- remove_before_invoke_hook(coro)[source]
Functional method to remove a
before_invoke
hook.
- await remove_cog(cogname, /, *, guild=..., guilds=...)[source]
-
Removes a cog from the bot and returns it.
All registered commands and event listeners that the cog has registered will be removed as well.
If no cog is found then this method has no effect.
Changed in version 2.0:
name
parameter is now positional-only.Changed in version 2.0: This method is now a coroutine.
- Parameters:
name (
str
) – The name of the cog to remove.guild (Optional[
Snowflake
]) –If the cog is an application command group, then this would be the guild where the cog group would be removed from. If not given then a global command is removed instead instead.
New in version 2.0.
guilds (List[
Snowflake
]) –If the cog is an application command group, then this would be the guilds where the cog group would be removed from. If not given then a global command is removed instead instead. Cannot be mixed with
guild
.New in version 2.0.
- Returns:
The cog that was removed.
None
if not found.- Return type:
Optional[
Cog
]
- remove_command(name, /)[source]
Remove a
Command
from the internal list of commands.This could also be used as a way to remove aliases.
Changed in version 2.0:
name
parameter is now positional-only.
- await remove_from_blacklist(users_or_roles, *, guild=None)[source]
Remove users or roles from the global or local blocklist.
- Parameters:
users_or_roles (Iterable[Union[int, discord.Role, discord.Member, discord.User]]) – The items to remove from the blocklist. Roles and role IDs should only be passed when updating a local blocklist.
guild (Optional[discord.Guild]) – The guild, whose local blocklist should be modified. If not passed, the global blocklist will be modified.
- Raises:
TypeError – The values passed were not of the proper type.
- await remove_from_whitelist(users_or_roles, *, guild=None)[source]
Remove users or roles from the global or local allowlist.
- Parameters:
users_or_roles (Iterable[Union[int, discord.Role, discord.Member, discord.User]]) – The items to remove from the allowlist. Roles and role IDs should only be passed when updating a local allowlist.
guild (Optional[discord.Guild]) – The guild, whose local allowlist should be modified. If not passed, the global allowlist will be modified.
- Raises:
TypeError – The passed values were not of the proper type.
- remove_permissions_hook(hook)[source]
Remove a permissions hook.
Parameters are the same as those in
add_permissions_hook
.- Raises:
ValueError – If the permissions hook has not been added.
Removes shared API services, as well as keys and tokens associated with them.
- Parameters:
*service_names (str) – The services to remove.
Examples
Removing the youtube service
>>> await ctx.bot.remove_shared_api_services("youtube")
Removes shared API tokens
- Parameters:
Examples
Removing the api_key for youtube
>>> await ctx.bot.remove_shared_api_tokens("youtube", "api_key")
- reset_help_formatter()[source]
Resets Red’s help formatter.
Warning
This method is provisional.
This exists for use in
cog_unload
for cogs which replace the formatter as well as for a rescue command in core_commands.
- staticmethod await send_filtered(destination, filter_mass_mentions=True, filter_invite_links=True, filter_all_links=False, **kwargs)[source]
This is a convenience wrapper around
discord.abc.Messageable.send
It takes the destination you’d like to send to, which filters to apply (defaults on mass mentions, and invite links) and any other parameters normally accepted by destination.send
This should realistically only be used for responding using user provided input. (unfortunately, including usernames) Manually crafted messages which don’t take any user input have no need of this
- Returns:
The message that was sent.
- Return type:
- await send_help_for(ctx, help_for, *, from_help_command=False)[source]
Invokes Red’s helpformatter for a given context and object.
- await send_interactive(channel, messages, *, user=None, 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:
channel (discord.abc.Messageable) – The channel to send the messages to.
user (discord.User) – The user that can respond to the prompt. When this is
None
, any user can respond.box_lang (Optional[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 send_to_owners(content=None, **kwargs)[source]
This sends something to all owners and their configured extra destinations.
This takes the same arguments as discord.abc.Messageable.send
This logs failing sends
- set_help_formatter(formatter)[source]
Set’s Red’s help formatter.
Warning
This method is provisional.
The formatter must implement all methods in
commands.help.HelpFormatterABC
Cogs which set a help formatter should inform users of this. Users should not use multiple cogs which set a help formatter.
This should specifically be an instance of a formatter. This allows cogs to pass a config object or similar to the formatter prior to the bot using it.
See
commands.help.HelpFormatterABC
for more details.- Raises:
RuntimeError – If the default formatter has already been replaced
TypeError – If given an invalid formatter
- await set_prefixes(prefixes, guild=None)[source]
Set global/server prefixes.
If
guild
is not provided (or None is passed), this will set the global prefixes.- Parameters:
prefixes (List[str]) – The prefixes you want to set. Passing empty list will reset prefixes for the
guild
guild (Optional[discord.Guild]) – The guild you want to set the prefixes for. Omit (or pass None) to set the global prefixes
- Raises:
TypeError – If
prefixes
is not a list of stringsValueError – If empty list is passed to
prefixes
when setting global prefixes
Sets shared API tokens for a service
In most cases, this should not be used. Users should instead be using the
set api
commandThis will not clear existing values not specified.
- Parameters:
service_name (str) – The service to set tokens for
**tokens – token_name -> token
Examples
Setting the api_key for youtube from a value in a variable
my_key
>>> await ctx.bot.set_shared_api_tokens("youtube", api_key=my_key)
- await setup_hook()[source]
-
A coroutine to be called to setup the bot, by default this is blank.
To perform asynchronous setup after the bot is logged in but before it has connected to the Websocket, overwrite this coroutine.
This is only called once, in
login()
, and will be called before any events are dispatched, making it a better solution than doing such setup in theon_ready()
event.Warning
Since this is called before the websocket connection is made therefore anything that waits for the websocket will deadlock, this includes things like
wait_for()
andwait_until_ready()
.New in version 2.0.
- await shutdown(*, restart=False)[source]
Gracefully quit Red.
The program will exit with code
0
by default.- Parameters:
restart (bool) – If
True
, the program will exit with code26
. If the launcher sees this, it will attempt to restart the bot.
- await start(token)[source]
-
A shorthand coroutine for
login()
+connect()
.- Parameters:
token (
str
) – The authentication token. Do not prefix this token with anything as the library will do it for you.reconnect (
bool
) – If we should attempt reconnecting, either due to internet failure or a specific failure on Discord’s part. Certain disconnects that lead to bad state will not be handled (such as invalid sharding payloads or bad tokens).
- Raises:
TypeError – An unexpected keyword argument was received.
- property uptime
Allow access to the value, but we don’t want cog creators setting it
- await use_buttons()[source]
Determines whether the bot owner has enabled use of buttons instead of reactions for basic menus.
- Return type:
- await verify_permissions_hooks(ctx)[source]
Run permissions hooks.
- Parameters:
ctx (commands.Context) – The context for the command being invoked.
- Returns:
False
if any hooks returnedFalse
,True
if any hooks returnTrue
and none returnedFalse
,None
otherwise.- Return type:
Optional[bool]