Welcome to Red - Discord Bot’s documentation!¶
Installing Red on Windows¶
Needed Software¶
- Python - Red needs at least Python 3.5
Attention
Please note that 3.6 has issues on some versions of Windows. If you try using Red with 3.6 and experience issues, uninstall Python 3.6 and install the latest version of Python 3.5
Note
Please make sure that the box to add Python to PATH is CHECKED, otherwise you may run into issues when trying to run Red
Attention
Please choose the option to “Run Git from the Windows Command Prompt” in Git’s setup
Installing Red¶
- Open a command prompt (open Start, search for “command prompt”, then click it)
- Run the appropriate command, depending on if you want audio or not
- No audio:
python -m pip install -U --process-dependency-links Red-DiscordBot
- Audio:
python -m pip install -U --process-dependency-links Red-DiscordBot[voice]
- Development version (without audio):
python -m pip install -U --process-dependency-links git+https://github.com/Cog-Creators/Red-DiscordBot@V3/develop#egg=red-discordbot
- Development version (with audio):
python -m pip install -U --process-dependency-links git+https://github.com/Cog-Creators/Red-DiscordBot@V3/develop#egg=red-discordbot[voice]
- Once that has completed, run
redbot-setup
to set up your instance
- This will set the location where data will be stored, as well as your storage backend and the name of the instance (which will be used for running the bot)
- Once done setting up the instance, run
redbot <your instance name>
to run Red. It will walk through the initial setup, asking for your token and a prefix
Installing Red on Mac¶
Installing pre-requirements¶
- Install Brew
- In Finder or Spotlight, search for and open terminal. In the window that will open, paste this:
/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
and press enter.
- In Finder or Spotlight, search for and open terminal. In the window that will open, paste this:
- After the installation, install the required packages by pasting the commands and pressing enter, one-by-one:
brew install python3 --with-brewed-openssl
brew install git
brew install ffmpeg --with-ffplay
brew install opus
Installing Red¶
Without audio:
pip3 install -U --process-dependency-links red-discordbot
With audio:
pip3 install -U --process-dependency-links red-discordbot[voice]
To install the development version (without audio):
pip3 install -U --process-dependency-links git+https://github.com/Cog-Creators/Red-DiscordBot@V3/develop#egg=red-discordbot
To install the development version (with audio):
pip3 install -U --process-dependency-links git+https://github.com/Cog-Creators/Red-DiscordBot@V3/develop#egg=red-discordbot[voice]
Setting up an instance¶
To set up an instance, run redbot-setup
and follow the steps there, providing the requested information
or accepting the defaults. Keep in mind that the instance name will be the one you use when running the bot, so
make it something you can remember
Running Red¶
Run redbot <your instance name>
and go through the initial setup (it will ask for the token and a prefix).
Installing Red on Ubuntu 16.04¶
Warning
For safety reasons, DO NOT install Red with a root user. Instead, make a new one.
Installing the pre-requirements¶
sudo apt install python3.5-dev python3-pip build-essential libssl-dev libffi-dev git ffmpeg libopus-dev unzip -y
Installing the bot¶
To install without audio:
pip3 install -U --process-dependency-links red-discordbot
To install with audio:
pip3 install -U --process-dependency-links red-discordbot[voice]
To install the development version (without audio):
pip3 install -U --process-dependency-links git+https://github.com/Cog-Creators/Red-DiscordBot@V3/develop#egg=red-discordbot
To install the development version (with audio):
pip3 install -U --process-dependency-links git+https://github.com/Cog-Creators/Red-DiscordBot@V3/develop#egg=red-discordbot[voice]
Setting up your instance¶
Run redbot-setup
and follow the prompts. It will ask first for where you want to
store the data (the default is ~/.local/share/Red-DiscordBot
) and will then ask
for confirmation of that selection. Next, it will ask you to choose your storage backend
(the default here is JSON). It will then ask for a name for your instance. This can be
anything as long as it does not contain spaces; however, keep in mind that this is the
name you will use to run your bot, and so it should be something you can remember.
Running Red¶
Run redbot <your instance name>
and run through the initial setup. This will ask for
your token and a prefix.
Installing Red on Debian Stretch¶
Warning
For safety reasons, DO NOT install Red with a root user. Instead, make a new one.
Installing pre-requirements¶
echo "deb http://httpredir.debian.org/debian stretch-backports main contrib non-free" >> /etc/apt/sources.list
apt-get update
apt-get install python3.5-dev python3-pip build-essential libssl-dev libffi-dev git ffmpeg libopus-dev unzip -y
Installing the bot¶
To install without audio:
pip3 install -U --process-dependency-links red-discordbot
To install with audio:
pip3 install -U --process-dependency-links red-discordbot[voice]
To install the development version (without audio):
pip3 install -U --process-dependency-links git+https://github.com/Cog-Creators/Red-DiscordBot@V3/develop#egg=red-discordbot
To install the development version (with audio):
pip3 install -U --process-dependency-links git+https://github.com/Cog-Creators/Red-DiscordBot@V3/develop#egg=red-discordbot[voice]
Setting up your instance¶
Run redbot-setup
and follow the prompts. It will ask first for where you want to
store the data (the default is ~/.local/share/Red-DiscordBot
) and will then ask
for confirmation of that selection. Next, it will ask you to choose your storage backend
(the default here is JSON). It will then ask for a name for your instance. This can be
anything as long as it does not contain spaces; however, keep in mind that this is the
name you will use to run your bot, and so it should be something you can remember.
Running Red¶
Run redbot <your instance name>
and run through the initial setup. This will ask for
your token and a prefix.
Installing Red on CentOS 7¶
Installing pre-requirements¶
yum -y groupinstall development
yum -y install https://centos7.iuscommunity.org/ius-release.rpm
yum -y install yum-utils wget which python35u python35u-pip python35u-devel openssl-devel libffi-devel git opus-devel
sh -c "$(wget https://gist.githubusercontent.com/mustafaturan/7053900/raw/27f4c8bad3ee2bb0027a1a52dc8501bf1e53b270/latest-ffmpeg-centos6.sh -O -)"
Installing Red¶
Without audio:
pip3 install -U --process-dependency-links red-discordbot
With audio:
pip3 install -U --process-dependency-links red-discordbot[voice]
To install the development version (without audio):
pip3 install -U --process-dependency-links git+https://github.com/Cog-Creators/Red-DiscordBot@V3/develop#egg=red-discordbot
To install the development version (with audio):
pip3 install -U --process-dependency-links git+https://github.com/Cog-Creators/Red-DiscordBot@V3/develop#egg=red-discordbot[voice]
Setting up an instance¶
Run redbot-setup
and follow the prompts. It will ask first for where you want to
store the data (the default is ~/.local/share/Red-DiscordBot
) and will then ask
for confirmation of that selection. Next, it will ask you to choose your storage backend
(the default here is JSON). It will then ask for a name for your instance. This can be
anything as long as it does not contain spaces; however, keep in mind that this is the
name you will use to run your bot, and so it should be something you can remember.
Running Red¶
Run redbot <your instance name>
and run through the initial setup. This will ask for
your token and a prefix.
Installing Red on Raspbian Stretch¶
Installing pre-requirements¶
sudo apt-get install python3.5-dev python3-pip build-essential libssl-dev libffi-dev git libav-tools libopus-dev unzip -y
Installing Red¶
Without audio:
pip3 install -U --process-dependency-links red-discordbot
With audio:
pip3 install -U --process-dependency-links red-discordbot[voice]
To install the development version (without audio):
pip3 install -U --process-dependency-links git+https://github.com/Cog-Creators/Red-DiscordBot@V3/develop#egg=red-discordbot
To install the development version (with audio):
pip3 install -U --process-dependency-links git+https://github.com/Cog-Creators/Red-DiscordBot@V3/develop#egg=red-discordbot[voice]
Setting up an instance¶
Run redbot-setup
and follow the prompts. It will ask first for where you want to
store the data (the default is ~/.local/share/Red-DiscordBot
) and will then ask
for confirmation of that selection. Next, it will ask you to choose your storage backend
(the default here is JSON). It will then ask for a name for your instance. This can be
anything as long as it does not contain spaces; however, keep in mind that this is the
name you will use to run your bot, and so it should be something you can remember.
Running Red¶
Run redbot <your instance name>
and run through the initial setup. This will ask for
your token and a prefix.
Warning
Audio will not work on Raspberry Pi’s below 2B. This is a CPU problem and cannot be fixed.
Downloader Cog Reference¶
-
class
redbot.cogs.downloader.downloader.
Downloader
(bot: redbot.core.bot.Red)[source]¶ -
coroutine
cog_install_path
()[source]¶ Get the current cog install path.
Returns: The default cog install path. Return type: pathlib.Path
-
cog_name_from_instance
(instance: object) → str[source]¶ Determines the cog name that Downloader knows from the cog instance.
Probably.
Parameters: instance (object) – The cog instance. Returns: The name of the cog according to Downloader.. Return type: str
-
format_findcog_info
(command_name: str, cog_installable: object = None) → str[source]¶ Format a cog’s info for output to discord.
Parameters: - command_name (str) – Name of the command which belongs to the cog.
- cog_installable (
Installable
orobject
) – Can be anInstallable
instance or a Cog instance.
Returns: A formatted message for the user.
Return type:
-
coroutine
installed_cogs
() → typing.Tuple[redbot.cogs.downloader.installable.Installable][source]¶ Get info on installed cogs.
Returns: All installed cogs / shared lib directories. Return type: tuple
ofInstallable
-
coroutine
is_installed
(cog_name: str) -> (<class 'bool'>, typing.Union[redbot.cogs.downloader.installable.Installable, NoneType])[source]¶ Check to see if a cog has been installed through Downloader.
Parameters: cog_name (str) – The name of the cog to check for. Returns: (True, Installable)
if the cog is installed, else(False, None)
.Return type: tuple
of (bool
,Installable
)
-
coroutine
Migrating Cogs to V3¶
First, be sure to read discord.py’s migration guide as that covers all of the changes to discord.py that will affect the migration process
Red as a package¶
V3 makes Red a package that is installed with pip
. Please
keep this in mind when writing cogs as this affects how imports
should be done (for example, to import pagify
in V2, one
would do from .utils.chat_formatting import pagify
; in
V3, this becomes from redbot.core.utils.chat_formatting import pagify
)
Cogs as packages¶
V3 makes cogs into packages. See Creating cogs for V3 for more on how to create packages for V3.
Config¶
Config is V3’s replacement for dataIO
. Instead of fiddling with
creating config directories and config files as was done in V2, V3’s
Config handles that whilst allowing for easy storage of settings on a
per-server/member/user/role/channel or global basis. Be sure to check
out Config for the API docs for Config as well as a
tutorial on using Config.
Creating cogs for V3¶
This guide serves as a tutorial on creating cogs for Red V3. It will cover the basics of setting up a package for your cog and the basics of setting up the file structure. We will also point you towards some further resources that may assist you in the process.
Getting started¶
To start off, be sure that you have installed Python 3.5 or higher (if you
are on Windows, stick with 3.5). Open a terminal or command prompt and type
pip install --process-dependency-links -U git+https://github.com/Cog-Creators/Red-DiscordBot@V3/develop#egg=redbot[test]
(note that if you get an error with this, try again but put python -m
in front of the command
This will install the latest version of V3.
Setting up a package¶
To set up a package, we would just need to create a new folder.
This should be named whatever you want the cog to be named (for
the purposes of this example, we’ll call this mycog
).
In this folder, create three files: __init__.py
,
mycog.py
, and info.json
. Open the folder in
a text editor or IDE (examples include Sublime Text 3,
Visual Studio Code, Atom, and
PyCharm).
Creating a cog¶
With your package opened in a text editor or IDE, open mycog.py
.
In that file, place the following code:
from discord.ext import commands
class Mycog:
"""My custom cog"""
@commands.command()
async def mycom(self, ctx):
"""This does stuff!"""
# Your code will go here
await ctx.send("I can do stuff!")
Open __init__.py
. In that file, place the following:
from .mycog import Mycog
def setup(bot):
bot.add_cog(Mycog())
Make sure that both files are saved.
Testing your cog¶
To test your cog, you will need a running instance of V3.
Assuming you installed V3 as outlined above, run redbot-setup
and provide the requested information. Once that’s done, run Red
by doing redbot <instance name> --dev
to start Red.
Complete the inital setup by providing a valid token and setting a
prefix. Once the bot has started up, use the link provided in the
console to add it to a server (note that you must have the
Manage Server
(or Administrator
) permission to add bots
to a server). Once it’s been added to a server, find the full path
to the directory where your cog package is located. In Discord, do
[p]addpath <path_to_folder_containing_package>
, then do
[p]load mycog
. Once the cog is loaded, do [p]mycom
The bot should respond with I can do stuff!
. If it did, you
have successfully created a cog!
Additional resources¶
Be sure to check out the migration guide for some resources on developing cogs for V3. This will also cover differences between V2 and V3 for those who developed cogs for V2.
Bank¶
Bank has now been separated from Economy for V3. New to bank is support for having a global bank.
Basic Usage¶
from redbot.core import bank
class MyCog:
@commands.command()
async def balance(self, ctx, user: discord.Member=None):
if user is None:
user = ctx.author
bal = bank.get_balance(user)
currency = bank.get_currency_name(ctx.guild)
await ctx.send(
"{}'s balance is {} {}".format(
user.display_name, bal, currency
)
)
API Reference¶
Bank¶
-
class
redbot.core.bank.
Account
(name: str, balance: int, created_at: datetime.datetime)[source]¶ A single account.
This class should ONLY be instantiated by the bank itself.
-
coroutine
redbot.core.bank.
get_balance
(member: discord.member.Member) → int[source]¶ Get the current balance of a member.
Parameters: member (discord.Member) – The member whose balance to check. Returns: The member’s balance Return type: int
-
coroutine
redbot.core.bank.
set_balance
(member: discord.member.Member, amount: int) → int[source]¶ Set an account balance.
Parameters: - member (discord.Member) – The member whose balance to set.
- amount (int) – The amount to set the balance to.
Returns: New account balance.
Return type: Raises: ValueError
– If attempting to set the balance to a negative number.
-
coroutine
redbot.core.bank.
withdraw_credits
(member: discord.member.Member, amount: int) → int[source]¶ Remove a certain amount of credits from an account.
Parameters: - member (discord.Member) – The member to withdraw credits from.
- amount (int) – The amount to withdraw.
Returns: New account balance.
Return type: Raises: ValueError
– If the withdrawal amount is invalid or if the account has insufficient funds.
-
coroutine
redbot.core.bank.
deposit_credits
(member: discord.member.Member, amount: int) → int[source]¶ Add a given amount of credits to an account.
Parameters: - member (discord.Member) – The member to deposit credits to.
- amount (int) – The amount to deposit.
Returns: The new balance.
Return type: Raises: ValueError
– If the deposit amount is invalid.
-
coroutine
redbot.core.bank.
can_spend
(member: discord.member.Member, amount: int) → bool[source]¶ Determine if a member can spend the given amount.
Parameters: - member (discord.Member) – The member wanting to spend.
- amount (int) – The amount the member wants to spend.
Returns: True
if the member has a sufficient balance to spend the amount, elseFalse
.Return type:
-
coroutine
redbot.core.bank.
transfer_credits
(from_: discord.member.Member, to: discord.member.Member, amount: int)[source]¶ Transfer a given amount of credits from one account to another.
Parameters: - from (discord.Member) – The member to transfer from.
- to (discord.Member) – The member to transfer to.
- amount (int) – The amount to transfer.
Returns: The new balance.
Return type: Raises: ValueError
– If the amount is invalid or iffrom_
has insufficient funds.
-
coroutine
redbot.core.bank.
get_guild_accounts
(guild: discord.guild.Guild) → typing.List[redbot.core.bank.Account][source]¶ Get all account data for the given guild.
Parameters: guild (discord.Guild) – The guild to get accounts for. Returns: A list of all guild accounts. Return type: list
ofAccount
Raises: RuntimeError
– If the bank is currently global.
-
coroutine
redbot.core.bank.
get_global_accounts
() → typing.List[redbot.core.bank.Account][source]¶ Get all global account data.
Returns: A list of all global accounts. Return type: list
ofAccount
Raises: RuntimeError
– If the bank is currently guild specific.
-
coroutine
redbot.core.bank.
get_account
(member: typing.Union[discord.member.Member, discord.user.User]) → redbot.core.bank.Account[source]¶ Get the appropriate account for the given user or member.
A member is required if the bank is currently guild specific.
Parameters: member ( discord.User
ordiscord.Member
) – The user whose account to get.Returns: The user’s account. Return type: Account
-
coroutine
redbot.core.bank.
is_global
() → bool[source]¶ Determine if the bank is currently global.
Returns: True
if the bank is global, otherwiseFalse
.Return type: bool
-
coroutine
redbot.core.bank.
set_global
(global_: bool) → bool[source]¶ Set global status of the bank.
Important
All accounts are reset when you switch!
Parameters: global (bool) – True
will set bank to global mode.Returns: New bank mode, True
is global.Return type: bool Raises: RuntimeError
– If bank is becoming global and adiscord.Member
was not provided.
-
coroutine
redbot.core.bank.
get_bank_name
(guild: discord.guild.Guild = None) → str[source]¶ Get the current bank name.
Parameters: guild ( discord.Guild
, optional) – The guild to get the bank name for (required if bank is guild-specific).Returns: The bank’s name. Return type: str Raises: RuntimeError
– If the bank is guild-specific and guild was not provided.
-
coroutine
redbot.core.bank.
set_bank_name
(name: str, guild: discord.guild.Guild = None) → str[source]¶ Set the bank name.
Parameters: - name (str) – The new name for the bank.
- guild (
discord.Guild
, optional) – The guild to set the bank name for (required if bank is guild-specific).
Returns: The new name for the bank.
Return type: Raises: RuntimeError
– If the bank is guild-specific and guild was not provided.
-
coroutine
redbot.core.bank.
get_currency_name
(guild: discord.guild.Guild = None) → str[source]¶ Get the currency name of the bank.
Parameters: guild ( discord.Guild
, optional) – The guild to get the currency name for (required if bank is guild-specific).Returns: The currency name. Return type: str Raises: RuntimeError
– If the bank is guild-specific and guild was not provided.
-
coroutine
redbot.core.bank.
set_currency_name
(name: str, guild: discord.guild.Guild = None) → str[source]¶ Set the currency name for the bank.
Parameters: - name (str) – The new name for the currency.
- guild (
discord.Guild
, optional) – The guild to set the currency name for (required if bank is guild-specific).
Returns: The new name for the currency.
Return type: Raises: RuntimeError
– If the bank is guild-specific and guild was not provided.
-
coroutine
redbot.core.bank.
get_default_balance
(guild: discord.guild.Guild = None) → int[source]¶ Get the current default balance amount.
Parameters: guild ( discord.Guild
, optional) – The guild to get the default balance for (required if bank is guild-specific).Returns: The bank’s default balance. Return type: int Raises: RuntimeError
– If the bank is guild-specific and guild was not provided.
-
coroutine
redbot.core.bank.
set_default_balance
(amount: int, guild: discord.guild.Guild = None) → int[source]¶ Set the default balance amount.
Parameters: - amount (int) – The new default balance.
- guild (
discord.Guild
, optional) – The guild to set the default balance for (required if bank is guild-specific).
Returns: The new default balance.
Return type: Raises: RuntimeError
– If the bank is guild-specific and guild was not provided.ValueError
– If the amount is invalid.
Cog Manager¶
-
class
redbot.core.cog_manager.
CogManager
(paths: typing.Tuple[str] = ())[source]¶ Directory manager for Red’s cogs.
This module allows you to load cogs from multiple directories and even from outside the bot directory. You may also set a directory for downloader to install new cogs to, the default being the
cogs/
folder in the root bot directory.-
coroutine
add_path
(path: typing.Union[pathlib.Path, str])[source]¶ Add a cog path to current list.
This will ignore duplicates. Does have a side effect of removing all invalid paths from the saved path list.
Parameters: path ( pathlib.Path
orstr
) – Path to add.Raises: ValueError
– Ifpath
does not resolve to an existing directory.
-
coroutine
available_modules
() → typing.List[str][source]¶ Finds the names of all available modules to load.
-
coroutine
find_cog
(name: str) → _frozen_importlib.ModuleSpec[source]¶ Find a cog in the list of available paths.
Parameters: name (str) – Name of the cog to find. Returns: A module spec to be used for specialized cog loading. Return type: importlib.machinery.ModuleSpec Raises: RuntimeError
– If there is no cog with the given name.
-
coroutine
install_path
() → pathlib.Path[source]¶ Get the install path for 3rd party cogs.
Returns: The path to the directory where 3rd party cogs are stored. Return type: pathlib.Path
-
static
invalidate_caches
()[source]¶ Re-evaluate modules in the py cache.
This is an alias for an importlib internal and should be called any time that a new module has been installed to a cog directory.
-
coroutine
paths
() → typing.Tuple[pathlib.Path, ...][source]¶ Get all currently valid path directories.
Returns: All valid cog paths. Return type: tuple
ofpathlib.Path
-
coroutine
remove_path
(path: typing.Union[pathlib.Path, str]) → typing.Tuple[pathlib.Path, ...][source]¶ Remove a path from the current paths list.
Parameters: path ( pathlib.Path
orstr
) – Path to remove.Returns: Tuple of new valid paths. Return type: tuple
ofpathlib.Path
-
coroutine
set_install_path
(path: pathlib.Path) → pathlib.Path[source]¶ Set the install path for 3rd party cogs.
Note
The bot will not remember your old cog install path which means that all previously installed cogs will no longer be found.
Parameters: path (pathlib.Path) – The new directory for cog installs. Returns: Absolute path to the new install directory. Return type: pathlib.Path Raises: ValueError
– Ifpath
is not an existing directory.
-
coroutine
set_paths
(paths_: typing.List[pathlib.Path])[source]¶ Set the current paths list.
Parameters: paths ( list
ofpathlib.Path
) – List of paths to set.
-
coroutine
Data Manager¶
Data manager is a module that handles all the information necessary to bootstrap the bot into a state where more abstract data management systems can take over.
-
redbot.core.data_manager.
load_basic_configuration
(instance_name_: str)[source]¶ Loads the basic bootstrap configuration necessary for
Config
to know where to store or look for data.Important
It is necessary to call this function BEFORE getting any
Config
objects!Parameters: instance_name (str) – The instance name given by CLI argument and created during redbot setup.
-
redbot.core.data_manager.
cog_data_path
(cog_instance=None) → pathlib.Path[source]¶ Gets the base cog data path. If you want to get the folder with which to store your own cog’s data please pass in an instance of your cog class.
Parameters: cog_instance – The instance of the cog you wish to get a data path for. Returns: If cog_instance
is provided it will return a path to a folder dedicated to a given cog. Otherwise it will return a path to the folder that contains data for all cogs.Return type: pathlib.Path
-
redbot.core.data_manager.
load_bundled_data
(cog_instance, init_location: str)[source]¶ This function copies (and overwrites) data from the
data/
folder of the installed cog.Important
This function MUST be called from the
setup()
function of your cog.Examples
>>> from redbot.core import data_manager >>> >>> def setup(bot): >>> cog = MyCog() >>> data_manager.load_bundled_data(cog, __file__) >>> bot.add_cog(cog)
Parameters: - cog_instance – An instance of your cog class.
- init_location (str) – The
__file__
attribute of the file where yoursetup()
function exists.
-
redbot.core.data_manager.
bundled_data_path
(cog_instance) → pathlib.Path[source]¶ The “data” directory that has been copied from installed cogs.
Important
You should NEVER write to this directory. Data manager will overwrite files in this directory each time
load_bundled_data
is called. You should instead write to the directory provided bycog_data_path
.Parameters: cog_instance – Returns: Path object to the bundled data folder. Return type: pathlib.Path Raises: FileNotFoundError
– If no bundled data folder exists or if it hasn’t been loaded yet.
Config¶
Config was introduced in V3 as a way to make data storage easier and safer for all developers regardless of skill level. It will take some getting used to as the syntax is entirely different from what Red has used before, but we believe Config will be extremely beneficial to both cog developers and end users in the long run.
Basic Usage¶
from redbot.core import Config
class MyCog:
def __init__(self):
self.config = Config.get_conf(self, identifier=1234567890)
self.config.register_global(
foo=True
)
@commands.command()
async def return_some_data(self, ctx):
await ctx.send(await config.foo())
Tutorial¶
This tutorial will walk you through how to use Config.
First, you need to import Config:
from redbot.core import Config
Then, in the class’s __init__
function, you need to get a config instance:
class MyCog:
def __init__(self):
self.config = Config.get_conf(self, identifier=1234567890)
The identifier
in Config.get_conf()
is used to keep your cog’s data separate
from that of another cog, and thus should be unique to your cog. For example: if we
have two cogs named MyCog
and their identifier is different, each will have
its own data without overwriting the other’s data. Note that it is also possible
to force registration of a data key before allowing you to get and set data for
that key by adding force_registration=True
after identifier (that defaults
to False
though)
After we’ve gotten that, we need to register default values:
class MyCog:
def __init__(self):
self.config = Config.get_conf(self, identifier=1234567890)
default_global = {
"foobar": True,
"foo": {
"bar": True,
"baz": False
}
}
default_guild = {
"blah": [],
"baz": 1234567890
}
self.config.register_global(**default_global)
self.config.register_guild(**default_guild)
As seen in the example above, we can set up our defaults in dicts and then use those in
the appropriate register
function. As seen above, there’s Config.register_global()
and Config.register_guild()
, but there’s also Config.register_member()
,
Config.register_role()
, Config.register_user()
, and Config.register_channel()
.
Note that member
stores based on guild id AND the user’s id.
Once we have our defaults registered and we have the object, we can now use those values in various ways:
@commands.command()
@checks.admin_or_permissions(manage_guild=True)
async def setbaz(self, ctx, new_value):
await self.config.guild(ctx.guild).baz.set(new_value)
await ctx.send("Value of baz has been changed!")
@commands.command()
@checks.is_owner()
async def setfoobar(self, ctx, new_value):
await self.config.foobar.set(new_value)
@commands.command()
async def checkbaz(self, ctx):
baz_val = await self.config.guild(ctx.guild).baz()
await ctx.send("The value of baz is {}".format("True" if baz_val else "False"))
Notice a few things in the above examples:
Global doesn’t have anything in between
self.config
and the variable.Both the getters and setters need to be awaited because they’re coroutines.
If you’re getting the value, the syntax is:
self.config.<insert scope here, or nothing if global>.variable_name()
If setting, it’s:
self.config.<insert scope here, or nothing if global>.variable_name.set(new_value)
It is also possible to use async with
syntax to get and set config
values. When entering the statement, the config value is retreived, and on exit,
it is saved. This puts a safeguard on any code within the async with
block such that if it breaks from the block in any way (whether it be from
return
, break
, continue
or an exception), the value will
still be saved.
Important
Only mutable config values can be used in the async with
statement
(namely lists or dicts), and they must be modified in place for their
changes to be saved.
Here is an example of the async with
syntax:
@commands.command()
async def addblah(self, ctx, new_blah):
guild_group = self.config.guild(ctx.guild)
async with guild_group.blah() as blah:
blah.append(new_blah)
await ctx.send("The new blah value has been added!")
Important
Please note that while you have nothing between config
and the variable name for global
data, you also have the following commands to get data specific to each category.
Config.guild()
for guild data which takes an object of typediscord.Guild
.Config.member()
which takesdiscord.Member
.Config.user()
which takesdiscord.User
.Config.role()
which takesdiscord.Role
.Config.channel()
which takesdiscord.TextChannel
.
If you need to wipe data from the config, you want to look at Group.clear()
, or Config.clear_all()
and similar methods, such as Config.clear_all_guilds()
.
Which one you should use depends on what you want to do.
If you’re looking to clear data for a single guild/member/channel/role/user,
you want to use Group.clear()
as that will clear the data only for the
specified thing.
If using Config.clear_all()
, it will reset all data everywhere.
There are other methods provided to reset data from a particular scope. For
example, Config.clear_all_guilds()
resets all guild data. For member
data, you can clear on both a per-guild and guild-independent basis, see
Config.clear_all_members()
for more info.
API Reference¶
Important
Before we begin with the nitty gritty API Reference, you should know that there are tons of working code examples
inside the bot itself! Simply take a peek inside of the tests/core/test_config.py
file for examples of using
Config in all kinds of ways.
Config¶
-
class
redbot.core.config.
Config
(cog_name: str, unique_identifier: str, driver_spawn: typing.Callable, force_registration: bool = False, defaults: dict = None)[source]¶ Configuration manager for cogs and Red.
You should always use
get_conf
or to instantiate a Config object. Useget_core_conf
for Config used in the core package.Important
Most config data should be accessed through its respective group method (e.g.
guild()
) however the process for accessing global data is a bit different. There is noglobal
method because global data is accessed by normal attribute access:await conf.foo()
-
unique_identifier
¶ int
– Unique identifier provided to differentiate cog data when name conflicts occur.
-
spawner
¶ A callable object that returns some driver that implements
redbot.core.drivers.red_base.BaseDriver
.
-
force_registration
¶ bool
– Determines if Config should throw an error if a cog attempts to access an attribute which has not been previously registered.Note
You should use this. By enabling force registration you give Config the ability to alert you instantly if you’ve made a typo when attempting to access data.
-
coroutine
all_channels
() → dict[source]¶ Get all channel data as a dict.
Note
The return value of this method will include registered defaults for values which have not yet been set.
Returns: A dictionary in the form { int
:dict
} mappingCHANNEL_ID -> data
.Return type: dict
-
coroutine
all_guilds
() → dict[source]¶ Get all guild data as a dict.
Note
The return value of this method will include registered defaults for values which have not yet been set.
Returns: A dictionary in the form { int
:dict
} mappingGUILD_ID -> data
.Return type: dict
-
coroutine
all_members
(guild: discord.guild.Guild = None) → dict[source]¶ Get data for all members.
If
guild
is specified, only the data for the members of that guild will be returned. As such, the dict will mapMEMBER_ID -> data
. Otherwise, the dict mapsGUILD_ID -> MEMBER_ID -> data
.Note
The return value of this method will include registered defaults for values which have not yet been set.
Parameters: guild ( discord.Guild
, optional) – The guild to get the member data from. Can be omitted if data from every member of all guilds is desired.Returns: A dictionary of all specified member data. Return type: dict
-
coroutine
all_roles
() → dict[source]¶ Get all role data as a dict.
Note
The return value of this method will include registered defaults for values which have not yet been set.
Returns: A dictionary in the form { int
:dict
} mappingROLE_ID -> data
.Return type: dict
-
coroutine
all_users
() → dict[source]¶ Get all user data as a dict.
Note
The return value of this method will include registered defaults for values which have not yet been set.
Returns: A dictionary in the form { int
:dict
} mappingUSER_ID -> data
.Return type: dict
-
channel
(channel: discord.channel.TextChannel) → redbot.core.config.Group[source]¶ Returns a
Group
for the given channel.This does not discriminate between text and voice channels.
Parameters: channel ( discord.abc.GuildChannel
) – A channel object.Returns: The channel’s Group object. Return type: Group
-
coroutine
clear_all
()[source]¶ Clear all data from this Config instance.
This resets all data to its registered defaults.
Important
This cannot be undone.
-
coroutine
clear_all_channels
()[source]¶ Clear all channel data.
This resets all channel data to its registered defaults.
-
coroutine
clear_all_globals
()[source]¶ Clear all global data.
This resets all global data to its registered defaults.
-
coroutine
clear_all_guilds
()[source]¶ Clear all guild data.
This resets all guild data to its registered defaults.
-
coroutine
clear_all_members
(guild: discord.guild.Guild = None)[source]¶ Clear all member data.
This resets all specified member data to its registered defaults.
Parameters: guild ( discord.Guild
, optional) – The guild to clear member data from. Omit to clear member data from all guilds.
-
coroutine
clear_all_roles
()[source]¶ Clear all role data.
This resets all role data to its registered defaults.
-
coroutine
clear_all_users
()[source]¶ Clear all user data.
This resets all user data to its registered defaults.
-
classmethod
get_conf
(cog_instance, identifier: int, force_registration=False)[source]¶ Get a Config instance for your cog.
Parameters: - cog_instance – This is an instance of your cog after it has been instantiated. If
you’re calling this method from within your cog’s
__init__
, this is justself
. - identifier (int) – A (hard-coded) random integer, used to keep your data distinct from any other cog with the same name.
- force_registration (
bool
, optional) – Should config require registration of data keys before allowing you to get/set values? Seeforce_registration
.
Returns: A new Config object.
Return type: - cog_instance – This is an instance of your cog after it has been instantiated. If
you’re calling this method from within your cog’s
-
classmethod
get_core_conf
(force_registration: bool = False)[source]¶ Get a Config instance for a core module.
All core modules that require a config instance should use this classmethod instead of
get_conf
.Parameters: force_registration ( bool
, optional) – Seeforce_registration
.
-
guild
(guild: discord.guild.Guild) → redbot.core.config.Group[source]¶ Returns a
Group
for the given guild.Parameters: guild (discord.Guild) – A guild object. Returns: The guild’s Group object. Return type: Group
-
member
(member: discord.member.Member) → redbot.core.config.Group[source]¶ Returns a
Group
for the given member.Parameters: member (discord.Member) – A member object. Returns: The member’s Group object. Return type: Group
-
register_channel
(**kwargs)[source]¶ Register default values on a per-channel level.
See
register_global
for more details.
-
register_global
(**kwargs)[source]¶ Register default values for attributes you wish to store in
Config
at a global level.Examples
You can register a single value or multiple values:
conf.register_global( foo=True ) conf.register_global( bar=False, baz=None )
You can also now register nested values:
_defaults = { "foo": { "bar": True, "baz": False } } # Will register `foo.bar` == True and `foo.baz` == False conf.register_global( **_defaults )
You can do the same thing without a
_defaults
dict by using double underscore as a variable name separator:# This is equivalent to the previous example conf.register_global( foo__bar=True, foo__baz=False )
-
register_guild
(**kwargs)[source]¶ Register default values on a per-guild level.
See
register_global
for more details.
-
register_member
(**kwargs)[source]¶ Registers default values on a per-member level.
This means that each user’s data is guild-dependent.
See
register_global
for more details.
-
register_role
(**kwargs)[source]¶ Registers default values on a per-role level.
See
register_global
for more details.
-
register_user
(**kwargs)[source]¶ Registers default values on a per-user level.
This means that each user’s data is guild-independent.
See
register_global
for more details.
-
role
(role: discord.role.Role) → redbot.core.config.Group[source]¶ Returns a
Group
for the given role.Parameters: role (discord.Role) – A role object. Returns: The role’s Group object. Return type: Group
-
user
(user: discord.user.User) → redbot.core.config.Group[source]¶ Returns a
Group
for the given user.Parameters: user (discord.User) – A user object. Returns: The user’s Group object. Return type: Group
-
Group¶
-
class
redbot.core.config.
Group
(identifiers: typing.Tuple[str], defaults: dict, spawner, force_registration: bool = False)[source]¶ Represents a group of data, composed of more
Group
orValue
objects.Inherits from
Value
which means that all of the attributes and methods available inValue
are also available when working with aGroup
object.-
force_registration
¶ bool
– Same asConfig.force_registration
.
-
spawner
¶ redbot.core.drivers.red_base.BaseDriver
– A reference toConfig.spawner
.
-
__getattr__
(item: str) → typing.Union[typing.Group, redbot.core.config.Value][source]¶ Get an attribute of this group.
This special method is called whenever dot notation is used on this object.
Parameters: item (str) – The name of the attribute being accessed. Returns: A child value of this Group. This, of course, can be another Group
, due to Config’s composite pattern.Return type: Group
orValue
Raises: AttributeError
– If the attribute has not been registered andforce_registration
is set toTrue
.
-
coroutine
all
() → dict[source]¶ Get a dictionary representation of this group’s data.
Note
The return value of this method will include registered defaults for values which have not yet been set.
Returns: All of this Group’s attributes, resolved as raw data values. Return type: dict
-
coroutine
clear
()[source]¶ Wipe all data from this group.
If used on a global group, it will wipe all global data, but not local data.
-
get_attr
(item: str, default=None, resolve=True)[source]¶ Manually get an attribute of this Group.
This is available to use as an alternative to using normal Python attribute access. It is required if you find a need for dynamic attribute access.
Note
Use of this method should be avoided wherever possible.
Example
A possible use case:
@commands.command() async def some_command(self, ctx, item: str): user = ctx.author # Where the value of item is the name of the data field in Config await ctx.send(await self.conf.user(user).get_attr(item))
Parameters: - item (str) – The name of the data field in
Config
. - default – This is an optional override to the registered default for this item.
- resolve (bool) – If this is
True
this function will return a coroutine that resolves to a “real” data value when awaited. IfFalse
, this method acts the same as__getattr__
.
Returns: The attribute which was requested, its type depending on the value of
resolve
.Return type: types.coroutine
orValue
orGroup
- item (str) – The name of the data field in
-
is_group
(item: str) → bool[source]¶ A helper method for
__getattr__
. Most developers will have no need to use this.Parameters: item (str) – See __getattr__
.
-
is_value
(item: str) → bool[source]¶ A helper method for
__getattr__
. Most developers will have no need to use this.Parameters: item (str) – See __getattr__
.
-
coroutine
set_attr
(item: str, value)[source]¶ Set an attribute by its name.
Similar to
get_attr
in the way it can be used to dynamically set attributes by name.Note
Use of this method should be avoided wherever possible.
Parameters: - item (str) – The name of the attribute being set.
- value – The raw data value to set the attribute as.
-
Value¶
-
class
redbot.core.config.
Value
(identifiers: typing.Tuple[str], default_value, spawner)[source]¶ A singular “value” of data.
-
identifiers
¶ tuple
ofstr
– This attribute provides all the keys necessary to get a specific data element from a json document.
-
default
¶ The default value for the data element that
identifiers
points at.
-
spawner
¶ redbot.core.drivers.red_base.BaseDriver
– A reference toConfig.spawner
.
-
__call__
(default=None)[source]¶ Get the literal value of this data element.
Each
Value
object is created by theGroup.__getattr__
method. The “real” data of theValue
object is accessed by this method. It is a replacement for aget()
method.The return value of this method can also be used as an asynchronous context manager, i.e. with
async with
syntax. This can only be used on values which are mutable (namely lists and dicts), and will set the value with its changes on exit of the context manager.Example
foo = await conf.guild(some_guild).foo() # Is equivalent to this group_obj = conf.guild(some_guild) value_obj = conf.foo foo = await value_obj()
Important
This is now, for all intents and purposes, a coroutine.
Parameters: default ( object
, optional) – This argument acts as an override for the registered default provided bydefault
. This argument is ignored if its value isNone
.Returns: A coroutine object mixed in with an async context manager. When awaited, this returns the raw data value. When used in async with
syntax, on gets the value on entrance, and sets it on exit.Return type: awaitable
mixed withasynchronous context manager
-
coroutine
set
(value)[source]¶ Set the value of the data elements pointed to by
identifiers
.Example
# Sets global value "foo" to False await conf.foo.set(False) # Sets guild specific value of "bar" to True await conf.guild(some_guild).bar.set(True)
Parameters: value – The new literal value of this attribute.
-
Driver Reference¶
-
redbot.core.drivers.
get_driver
(type, *args, **kwargs)[source]¶ Selectively import/load driver classes based on the selected type. This is required so that dependencies can differ between installs (e.g. so that you don’t need to install a mongo dependency if you will just be running a json data backend).
Note
See the respective classes for information on what
args
andkwargs
should be.Parameters: - type (str) – One of: json, mongo
- args – Dependent on driver type.
- kwargs – Dependent on driver type.
Returns: Subclass of
red_base.BaseDriver
.
Base Driver¶
-
class
redbot.core.drivers.red_base.
BaseDriver
(cog_name)[source]¶ -
coroutine
get
(identifiers: typing.Tuple[str])[source]¶ Finds the value indicate by the given identifiers.
Parameters: identifiers – A list of identifiers that correspond to nested dict accesses. Returns: Stored value.
-
coroutine
JSON Driver¶
-
class
redbot.core.drivers.red_json.
JSON
(cog_name, *, data_path_override: pathlib.Path = None, file_name_override: str = 'settings.json')[source]¶ Subclass of
red_base.BaseDriver
.-
file_name
¶ The name of the file in which to store JSON data.
-
Mongo Driver¶
Downloader Framework¶
Info.json¶
The info.json file may exist inside every package folder in the repo, it is optional however. This string describes the valid keys within an info file (and maybe how the Downloader cog uses them).
KEYS (case sensitive):
author
(list of strings) - list of names of authors of the cogbot_version
(list of integer) - Min version number of Red in the format(MAJOR, MINOR, PATCH)
description
(string) - A long description of the cog that appears when a user executes`!cog info
.hidden
(bool) - Determines if a cog is available for install.install_msg
(string) - The message that gets displayed when a cog is installedrequired_cogs
(map of cogname to repo URL) - A map of required cogs that this cog depends on. Downloader will not deal with this functionality but it may be useful for other cogs.requirements
(list of strings) - list of required libraries that are passed to pip on cog install.SHARED_LIBRARIES
do NOT go in this list.short
(string) - A short description of the cog that appears when a user executescog list
tags
(list of strings) - A list of strings that are related to the functionality of the cog. Used to aid in searching.type
(string) - Optional, defaults toCOG
. Must be eitherCOG
orSHARED_LIBRARY
. IfSHARED_LIBRARY
thenhidden
will beTrue
.
API Reference¶
Installable¶
-
class
redbot.cogs.downloader.installable.
Installable
(location: pathlib.Path)[source]¶ Base class for anything the Downloader cog can install.
- Modules
- Repo Libraries
- Other stuff?
The attributes of this class will mostly come from the installation’s info.json.
-
bot_version
¶ tuple
ofint
– The minimum bot version required for this installation. Right now this is always3.0.0
.
bool
– Whether or not this cog will be hidden from the user when they useDownloader
’s commands.
-
required_cogs
¶ dict
– In the form{cog_name : repo_url}
, these are cogs which are required for this installation.
-
coroutine
copy_to
(target_dir: pathlib.Path) → bool[source]¶ Copies this cog/shared_lib to the given directory. This will overwrite any files in the target directory.
Parameters: target_dir (pathlib.Path) – The installation directory to install to. Returns: Status of installation Return type: bool
Repo¶
-
class
redbot.cogs.downloader.repo_manager.
Repo
(name: str, url: str, branch: str, folder_path: pathlib.Path, available_modules: typing.Tuple[redbot.cogs.downloader.installable.Installable] = (), loop: asyncio.events.AbstractEventLoop = None)[source]¶ -
available_cogs
¶ tuple
ofinstallable
– All available cogs in this Repo.This excludes hidden or shared packages.
-
available_libraries
¶ tuple
ofinstallable
– All available shared libraries in this Repo.
-
coroutine
clone
() → typing.Tuple[str][source]¶ Clone a new repo.
Returns: All available module names from this repo. Return type: tuple
ofstr
-
coroutine
current_branch
() → str[source]¶ Determine the current branch using git commands.
Returns: The current branch name. Return type: str
-
coroutine
current_commit
(branch: str = None) → str[source]¶ Determine the current commit hash of the repo.
Parameters: branch ( str
, optional) – Override for repo’s branch attribute.Returns: The requested commit hash. Return type: str
-
coroutine
hard_reset
(branch: str = None) → None[source]¶ Perform a hard reset on the current repo.
Parameters: branch ( str
, optional) – Override for repo branch attribute.
-
coroutine
install_cog
(cog: redbot.cogs.downloader.installable.Installable, target_dir: pathlib.Path) → bool[source]¶ Install a cog to the target directory.
Parameters: - cog (Installable) – The package to install.
- target_dir (pathlib.Path) – The target directory for the cog installation.
Returns: The success of the installation.
Return type:
-
coroutine
install_libraries
(target_dir: pathlib.Path, libraries: typing.Tuple[redbot.cogs.downloader.installable.Installable] = ()) → bool[source]¶ Install shared libraries to the target directory.
If
libraries
is not specified, all shared libraries in the repo will be installed.Parameters: - target_dir (pathlib.Path) – Directory to install shared libraries to.
- libraries (
tuple
ofInstallable
) – A subset of available libraries.
Returns: The success of the installation.
Return type:
-
coroutine
install_raw_requirements
(requirements: typing.Tuple[str], target_dir: pathlib.Path) → bool[source]¶ Install a list of requirements using pip.
Parameters: - requirements (
tuple
ofstr
) – List of requirement names to install via pip. - target_dir (pathlib.Path) – Path to directory where requirements are to be installed.
Returns: Success of the installation
Return type: - requirements (
-
coroutine
install_requirements
(cog: redbot.cogs.downloader.installable.Installable, target_dir: pathlib.Path) → bool[source]¶ Install a cog’s requirements.
Requirements will be installed via pip directly into
target_dir
.Parameters: - cog (Installable) – Cog for which to install requirements.
- target_dir (pathlib.Path) – Path to directory where requirements are to be installed.
Returns: Success of the installation.
Return type:
-
Repo Manager¶
-
class
redbot.cogs.downloader.repo_manager.
RepoManager
(downloader_config: redbot.core.config.Config)[source]¶ -
coroutine
add_repo
(url: str, name: str, branch: str = 'master') → redbot.cogs.downloader.repo_manager.Repo[source]¶ Add and clone a git repository.
Parameters: Returns: New Repo object representing the cloned repository.
Return type:
-
coroutine
delete_repo
(name: str)[source]¶ Delete a repository and its folders.
Parameters: name (str) – The name of the repository to delete. Raises: MissingGitRepo
– If the repo does not exist.
-
get_all_repo_names
() → typing.Tuple[str][source]¶ Get all repo names.
Returns: Return type: tuple
ofstr
-
coroutine
Exceptions¶
-
exception
redbot.cogs.downloader.errors.
DownloaderException
[source]¶ Base class for Downloader exceptions.
-
exception
redbot.cogs.downloader.errors.
InvalidRepoName
[source]¶ Throw when a repo name is invalid. Check the message for a more detailed reason.
-
exception
redbot.cogs.downloader.errors.
ExistingGitRepo
[source]¶ Thrown when trying to clone into a folder where a git repo already exists.
-
exception
redbot.cogs.downloader.errors.
MissingGitRepo
[source]¶ Thrown when a git repo is expected to exist but does not.
-
exception
redbot.cogs.downloader.errors.
CloningError
[source]¶ Thrown when git clone returns a non zero exit code.
-
exception
redbot.cogs.downloader.errors.
CurrentHashError
[source]¶ Thrown when git returns a non zero exit code attempting to determine the current commit hash.
-
exception
redbot.cogs.downloader.errors.
HardResetError
[source]¶ Thrown when there is an issue trying to execute a hard reset (usually prior to a repo update).
Internationalization Framework¶
Basic Usage¶
from discord.ext import commands
from redbot.core.i18n import CogI18n
_ = CogI18n("ExampleCog", __file__)
class ExampleCog:
"""description"""
@commands.command()
async def mycom(self, ctx):
"""command description"""
await ctx.send(_("This is a test command"))
Tutorial¶
After making your cog, generate a messages.pot
file
The process of generating this will depend on the operating system you are using
In a command prompt in your cog’s package (where yourcog.py is), create a directory called “locales”. Then do one of the following:
Windows: python <your python install path>\Tools\i18n\pygettext.py -n -p locales
Mac: ?
Linux: pygettext3 -n -p locales
This will generate a messages.pot file with strings to be translated
API Reference¶
Mod log¶
Mod log has now been separated from Mod for V3.
Basic Usage¶
from redbot.core import modlog
import discord
class MyCog:
@commands.command()
@checks.admin_or_permissions(ban_members=True)
async def ban(self, ctx, user: discord.Member, reason: str=None):
await ctx.guild.ban(user)
case = modlog.create_case(
ctx.guild, ctx.message.created_at, "ban", user,
ctx.author, reason, until=None, channel=None
)
await ctx.send("Done. It was about time.")
Registering Case types¶
To register a single case type:
from redbot.core import modlog
import discord
class MyCog:
def __init__(self, bot):
ban_case = {
"name": "ban",
"default_setting": True,
"image": ":hammer:",
"case_str": "Ban",
"audit_type": "ban"
}
modlog.register_casetype(**ban_case)
To register multiple case types:
from redbot.core import modlog
import discord
class MyCog:
def __init__(self, bot):
new_types = [
{
"name": "ban",
"default_setting": True,
"image": ":hammer:",
"case_str": "Ban",
"audit_type": "ban"
},
{
"name": "kick",
"default_setting": True,
"image": ":boot:",
"case_str": "Kick",
"audit_type": "kick"
}
]
modlog.register_casetypes(new_types)
Important
Image should be the emoji you want to represent your case type with.
API Reference¶
Mod log¶
-
class
redbot.core.modlog.
Case
(guild: discord.guild.Guild, created_at: int, action_type: str, user: discord.user.User, moderator: discord.member.Member, case_number: int, reason: str = None, until: int = None, channel: discord.channel.TextChannel = None, amended_by: discord.member.Member = None, modified_at: int = None, message: discord.message.Message = None)[source]¶ A single mod log case
-
coroutine
from_json
(mod_channel: discord.channel.TextChannel, bot: redbot.core.bot.Red, data: dict)[source]¶ Get a Case object from the provided information
Parameters: - mod_channel (discord.TextChannel) – The mod log channel for the guild
- bot (Red) – The bot’s instance. Needed to get the target user
- data (dict) – The JSON representation of the case to be gotten
Returns: The case object for the requested case
Return type:
-
coroutine
message_content
()[source]¶ Format a case message
Returns: A rich embed representing a case message Return type: discord.Embed
-
coroutine
-
class
redbot.core.modlog.
CaseType
(name: str, default_setting: bool, image: str, case_str: str, audit_type: str = None, guild: discord.guild.Guild = None)[source]¶ A single case type
-
name
¶ str – The name of the case
-
image
¶ str – The emoji to use for the case type (for example, :boot:)
-
case_str
¶ str – The string representation of the case (example: Ban)
-
classmethod
from_json
(data: dict)[source]¶ Parameters: data (dict) – The data to create an instance from Returns: Return type: CaseType
-
coroutine
is_enabled
() → bool[source]¶ Determines if the case is enabled. If the guild is not set, this will always return False
Returns: True if the guild is set and the casetype is enabled for the guild False if the guild is not set or if the guild is set and the type is disabled
Return type: bool
-
-
coroutine
redbot.core.modlog.
get_next_case_number
(guild: discord.guild.Guild) → str[source]¶ Gets the next case number
Parameters: guild ( discord.Guild
) – The guild to get the next case number forReturns: The next case number Return type: str
-
coroutine
redbot.core.modlog.
get_case
(case_number: int, guild: discord.guild.Guild, bot: redbot.core.bot.Red) → redbot.core.modlog.Case[source]¶ Gets the case with the associated case number
Parameters: - case_number (int) – The case number for the case to get
- guild (discord.Guild) – The guild to get the case from
- bot (Red) – The bot’s instance
Returns: The case associated with the case number
Return type: Raises: RuntimeError
– If there is no case for the specified number
-
coroutine
redbot.core.modlog.
get_all_cases
(guild: discord.guild.Guild, bot: redbot.core.bot.Red) → typing.List[redbot.core.modlog.Case][source]¶ Gets all cases for the specified guild
Parameters: - guild (
discord.Guild
) – The guild to get the cases from - bot (Red) – The bot’s instance
Returns: A list of all cases for the guild
Return type: - guild (
-
coroutine
redbot.core.modlog.
create_case
(guild: discord.guild.Guild, created_at: datetime.datetime, action_type: str, user: typing.Union[discord.user.User, discord.member.Member], moderator: discord.member.Member = None, reason: str = None, until: datetime.datetime = None, channel: discord.channel.TextChannel = None) → typing.Union[redbot.core.modlog.Case, NoneType][source]¶ Creates a new case
Parameters: - guild (
discord.Guild
) – The guild the action was taken in - created_at (datetime) – The time the action occurred at
- action_type (str) – The type of action that was taken
- user (
discord.User
ordiscord.Member
) – The user target by the action - moderator (
discord.Member
) – The moderator who took the action - reason (str) – The reason the action was taken
- until (datetime) – The time the action is in effect until
- channel (
discord.TextChannel
ordiscord.VoiceChannel
) – The channel the action was taken in
Returns: The newly created case
Return type: Raises: RuntimeError
– If the mod log channel doesn’t exist- guild (
-
coroutine
redbot.core.modlog.
get_casetype
(name: str, guild: discord.guild.Guild = None) → typing.Union[redbot.core.modlog.CaseType, NoneType][source]¶ Gets the case type
Parameters: - name (str) – The name of the case type to get
- guild (discord.Guild) – If provided, sets the case type’s guild attribute to this guild
Returns: Return type:
-
coroutine
redbot.core.modlog.
get_all_casetypes
(guild: discord.guild.Guild = None) → typing.List[redbot.core.modlog.CaseType][source]¶ Get all currently registered case types
Returns: A list of case types Return type: list
-
coroutine
redbot.core.modlog.
register_casetype
(name: str, default_setting: bool, image: str, case_str: str, audit_type: str = None) → redbot.core.modlog.CaseType[source]¶ Registers a case type. If the case type exists and there are differences between the values passed and what is stored already, the case type will be updated with the new values
Parameters: - name (str) – The name of the case
- default_setting (bool) – Whether the case type should be on (if
True
) or off (ifFalse
) by default - image (str) – The emoji to use for the case type (for example, :boot:)
- case_str (str) – The string representation of the case (example: Ban)
- audit_type (
str
, optional) – The action type of the action as it would appear in the audit log
Returns: The case type that was registered
Return type: Raises: RuntimeError
– If the case type is already registered- TypeError: – If a parameter is missing
ValueError
– If a parameter’s value is not validAttributeError
– If the audit_type is not an attribute ofdiscord.AuditLogAction
-
coroutine
redbot.core.modlog.
register_casetypes
(new_types: typing.List[dict]) → typing.List[redbot.core.modlog.CaseType][source]¶ Registers multiple case types
Parameters: new_types (list) – The new types to register
Returns: True
if all were registered successfullyReturn type: Raises: See also
-
coroutine
redbot.core.modlog.
get_modlog_channel
(guild: discord.guild.Guild) → typing.Union[discord.channel.TextChannel, NoneType][source]¶ Get the current modlog channel
Parameters: guild ( discord.Guild
) – The guild to get the modlog channel forReturns: The channel object representing the modlog channel Return type: discord.TextChannel
orNone
Raises: RuntimeError
– If the modlog channel is not found
-
coroutine
redbot.core.modlog.
set_modlog_channel
(guild: discord.guild.Guild, channel: typing.Union[discord.channel.TextChannel, NoneType]) → bool[source]¶ Changes the modlog channel
Parameters: - guild (
discord.Guild
) – The guild to set a mod log channel for - channel (
discord.TextChannel
orNone
) – The channel to be set as modlog channel
Returns: True
if successfulReturn type: - guild (
-
coroutine
redbot.core.modlog.
reset_cases
(guild: discord.guild.Guild) → bool[source]¶ Wipes all modlog cases for the specified guild
Parameters: guild ( discord.Guild
) – The guild to reset cases forReturns: True
if successfulReturn type: bool
Command Invocation Context¶
The purpose of this module is to allow for Red to further customise the command invocation context provided by discord.py.
-
class
redbot.core.
RedContext
(**attrs)[source]¶ Command invocation context for Red.
All context passed into commands will be of this type.
This class inherits from
commands.Context
.-
coroutine
send_help
() → typing.List[discord.message.Message][source]¶ Send the command help message.
Returns: A list of help messages which were sent to the user. Return type: list
ofdiscord.Message
-
coroutine
send_interactive
(messages: typing.Iterable[str], box_lang: str = None, timeout: int = 15) → typing.List[discord.message.Message][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:
-
coroutine
Utility Functions¶
Chat Formatting¶
-
redbot.core.utils.chat_formatting.
bold
(text: str) → str[source]¶ Get the given text in bold.
Parameters: text (str) – The text to be marked up. Returns: The marked up text. Return type: str
-
redbot.core.utils.chat_formatting.
bordered
(text1: typing.List[str], text2: typing.List[str]) → str[source]¶ Get two blocks of text in a borders.
Note
This will only work with a monospaced font.
Parameters: Returns: The bordered text.
Return type:
-
redbot.core.utils.chat_formatting.
box
(text: str, lang: str = '') → str[source]¶ Get the given text in a code block.
Parameters: Returns: The marked up text.
Return type:
-
redbot.core.utils.chat_formatting.
error
(text: str) → str[source]¶ Get text prefixed with an error emoji.
Returns: The new message. Return type: str
-
redbot.core.utils.chat_formatting.
escape
(text: str, *, mass_mentions: bool = False, formatting: bool = False) → str[source]¶ Get text with all mass mentions or markdown escaped.
Parameters: Returns: The escaped text.
Return type:
-
redbot.core.utils.chat_formatting.
info
(text: str) → str[source]¶ Get text prefixed with an info emoji.
Returns: The new message. Return type: str
-
redbot.core.utils.chat_formatting.
inline
(text: str) → str[source]¶ Get the given text as inline code.
Parameters: text (str) – The text to be marked up. Returns: The marked up text. Return type: str
-
redbot.core.utils.chat_formatting.
italics
(text: str) → str[source]¶ Get the given text in italics.
Parameters: text (str) – The text to be marked up. Returns: The marked up text. Return type: str
-
redbot.core.utils.chat_formatting.
pagify
(text: str, delims: typing.List[str] = ['\n'], *, priority: bool = False, escape_mass_mentions: bool = True, shorten_by: int = 8, page_length: int = 2000) → typing.Iterator[str][source]¶ Generate multiple pages from the given text.
Note
This does not respect code blocks or inline code.
Parameters: Other Parameters: - priority (
bool
) – Set toTrue
to choose the page break delimiter based on the order ofdelims
. Otherwise, the page will always break at the last possible delimiter. - escape_mass_mentions (
bool
) – IfTrue
, any mass mentions (here or everyone) will be silenced. - shorten_by (
int
) – How much to shorten each page by. Defaults to 8. - page_length (
int
) – The maximum length of each page. Defaults to 2000.
Yields: str
– Pages of the given text.- priority (
-
redbot.core.utils.chat_formatting.
question
(text: str) → str[source]¶ Get text prefixed with a question emoji.
Returns: The new message. Return type: str
-
redbot.core.utils.chat_formatting.
strikethrough
(text: str) → str[source]¶ Get the given text with a strikethrough.
Parameters: text (str) – The text to be marked up. Returns: The marked up text. Return type: str
Mod Helpers¶
-
redbot.core.utils.mod.
get_audit_reason
(author: discord.member.Member, reason: str = None)[source]¶ Construct a reason to appear in the audit log.
Parameters: - author (discord.Member) – The author behind the audit log action.
- reason (str) – The reason behidn the audit log action.
Returns: The formatted audit log reason.
Return type:
-
coroutine
redbot.core.utils.mod.
is_admin_or_superior
(bot: redbot.core.bot.Red, obj: typing.Union[discord.message.Message, discord.member.Member, discord.role.Role])[source]¶ Same as
is_mod_or_superior
except for admin permissions.If a message is passed, its author’s permissions are checked. If a role is passed, it simply checks if it is the admin role.
Parameters: - bot (redbot.core.bot.Red) – The bot object.
- obj (
discord.Message
ordiscord.Member
ordiscord.Role
) – The object to check permissions for.
Returns: True
if the object has admin permissions.Return type: Raises: TypeError
– If the wrong type ofobj
was passed.
-
coroutine
redbot.core.utils.mod.
is_mod_or_superior
(bot: redbot.core.bot.Red, obj: typing.Union[discord.message.Message, discord.member.Member, discord.role.Role])[source]¶ Check if an object has mod or superior permissions.
If a message is passed, its author’s permissions are checked. If a role is passed, it simply checks if it is one of either the admin or mod roles.
Parameters: - bot (redbot.core.bot.Red) – The bot object.
- obj (
discord.Message
ordiscord.Member
ordiscord.Role
) – The object to check permissions for.
Returns: True
if the object has mod permissions.Return type: Raises: TypeError
– If the wrong type ofobj
was passed.
-
coroutine
redbot.core.utils.mod.
mass_purge
(messages: typing.List[discord.message.Message], channel: discord.channel.TextChannel)[source]¶ Bulk delete messages from a channel.
If more than 100 messages are supplied, the bot will delete 100 messages at a time, sleeping between each action.
Note
Messages must not be older than 14 days, and the bot must not be a user account.
Parameters: - messages (
list
ofdiscord.Message
) – The messages to bulk delete. - channel (discord.TextChannel) – The channel to delete messages from.
Raises: discord.Forbidden
– You do not have proper permissions to delete the messages or you’re not using a bot account.discord.HTTPException
– Deleting the messages failed.
- messages (
-
coroutine
redbot.core.utils.mod.
slow_deletion
(messages: typing.Iterable[discord.message.Message])[source]¶ Delete a list of messages one at a time.
Any exceptions raised when trying to delete the message will be silenced.
Parameters: messages ( iterable
ofdiscord.Message
) – The messages to delete.
-
redbot.core.utils.mod.
strfdelta
(delta: datetime.timedelta)[source]¶ Format a timedelta object to a message with time units.
Parameters: delta (datetime.timedelta) – The duration to parse. Returns: A message representing the timedelta with units. Return type: str