Normalize names of attributes with Config instances (#3765)

* Lets normalize how we name config attributes across the bot.

Signed-off-by: Drapersniper <27962761+drapersniper@users.noreply.github.com>

* ....

Signed-off-by: Drapersniper <27962761+drapersniper@users.noreply.github.com>

* nothing to see here

Signed-off-by: Drapersniper <27962761+drapersniper@users.noreply.github.com>
This commit is contained in:
Draper 2020-04-20 18:12:57 +01:00 committed by GitHub
parent df7ca65108
commit e4018ec677
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
22 changed files with 328 additions and 325 deletions

View File

@ -202,15 +202,15 @@ the built-in Economy credits::
class Pets:
def __init__(self):
self.conf = Config.get_conf(self, 1234567890)
self.config = Config.get_conf(self, 1234567890)
# Here we'll assign some default costs for the pets
self.conf.register_global(
self.config.register_global(
dog=100,
cat=100,
bird=50
)
self.conf.register_user(
self.config.register_user(
pets={}
)
@ -229,7 +229,7 @@ And now that the cog is set up we'll need to create some commands that allow use
# We will need to use "get_raw"
try:
cost = await self.conf.get_raw(pet_type)
cost = await self.config.get_raw(pet_type)
except KeyError:
# KeyError is thrown whenever the data you try to access does not
# exist in the registered defaults or in the saved data.
@ -241,15 +241,15 @@ assign a new pet to the user. This is very easily done using the V3 bank API and
# continued
if await bank.can_spend(ctx.author, cost):
await self.conf.user(ctx.author).pets.set_raw(
await self.config.user(ctx.author).pets.set_raw(
pet_name, value={'cost': cost, 'hunger': 0}
)
# this is equivalent to doing the following
pets = await self.conf.user(ctx.author).pets()
pets = await self.config.user(ctx.author).pets()
pets[pet_name] = {'cost': cost, 'hunger': 0}
await self.conf.user(ctx.author).pets.set(pets)
await self.config.user(ctx.author).pets.set(pets)
Since the pets can get hungry we're gonna need a command that let's pet owners check how hungry their pets are::
@ -257,7 +257,7 @@ Since the pets can get hungry we're gonna need a command that let's pet owners c
@commands.command()
async def hunger(self, ctx, pet_name: str):
try:
hunger = await self.conf.user(ctx.author).pets.get_raw(pet_name, 'hunger')
hunger = await self.config.user(ctx.author).pets.get_raw(pet_name, 'hunger')
except KeyError:
# Remember, this is thrown if something in the provided identifiers
# is not found in the saved data or the defaults.
@ -274,7 +274,7 @@ We're responsible pet owners here, so we've also got to have a way to feed our p
# This is a bit more complicated because we need to check if the pet is
# owned first.
try:
pet = await self.conf.user(ctx.author).pets.get_raw(pet_name)
pet = await self.config.user(ctx.author).pets.get_raw(pet_name)
except KeyError:
# If the given pet name doesn't exist in our data
await ctx.send("You don't own that pet!")
@ -285,12 +285,12 @@ We're responsible pet owners here, so we've also got to have a way to feed our p
# Determine the new hunger and make sure it doesn't go negative
new_hunger = max(hunger - food, 0)
await self.conf.user(ctx.author).pets.set_raw(
await self.config.user(ctx.author).pets.set_raw(
pet_name, 'hunger', value=new_hunger
)
# We could accomplish the same thing a slightly different way
await self.conf.user(ctx.author).pets.get_attr(pet_name).hunger.set(new_hunger)
await self.config.user(ctx.author).pets.get_attr(pet_name).hunger.set(new_hunger)
await ctx.send("Your pet is now at {}/100 hunger!".format(new_hunger)
@ -300,7 +300,7 @@ Of course, if we're less than responsible pet owners, there are consequences::
@commands.command()
async def adopt(self, ctx, pet_name: str, *, member: discord.Member):
try:
pet = await self.conf.user(member).pets.get_raw(pet_name)
pet = await self.config.user(member).pets.get_raw(pet_name)
except KeyError:
await ctx.send("That person doesn't own that pet!")
return
@ -310,15 +310,15 @@ Of course, if we're less than responsible pet owners, there are consequences::
await ctx.send("That pet is too well taken care of to be adopted.")
return
await self.conf.user(member).pets.clear_raw(pet_name)
await self.config.user(member).pets.clear_raw(pet_name)
# this is equivalent to doing the following
pets = await self.conf.user(member).pets()
pets = await self.config.user(member).pets()
del pets[pet_name]
await self.conf.user(member).pets.set(pets)
await self.config.user(member).pets.set(pets)
await self.conf.user(ctx.author).pets.set_raw(pet_name, value=pet)
await self.config.user(ctx.author).pets.set_raw(pet_name, value=pet)
await ctx.send(
"Your request to adopt this pet has been granted due to "
"how poorly it was taken care of."
@ -351,15 +351,15 @@ much the same way they would in V2. The following examples will demonstrate how
class ExampleCog:
def __init__(self):
self.conf = Config.get_conf(self, 1234567890)
self.config = Config.get_conf(self, 1234567890)
self.data = {}
async def load_data(self):
self.data = await self.conf.custom("V2", "V2").all()
self.data = await self.config.custom("V2", "V2").all()
async def save_data(self):
await self.conf.custom("V2", "V2").set(self.data)
await self.config.custom("V2", "V2").set(self.data)
async def setup(bot):
@ -407,13 +407,13 @@ API Reference
includes keys within a `dict` when one is being set, as well as keys in nested dictionaries
within that `dict`. For example::
>>> conf = Config.get_conf(self, identifier=999)
>>> conf.register_global(foo={})
>>> await conf.foo.set_raw(123, value=True)
>>> await conf.foo()
>>> config = Config.get_conf(self, identifier=999)
>>> config.register_global(foo={})
>>> await config.foo.set_raw(123, value=True)
>>> await config.foo()
{'123': True}
>>> await conf.foo.set({123: True, 456: {789: False}}
>>> await conf.foo()
>>> await config.foo.set({123: True, 456: {789: False}}
>>> await config.foo()
{'123': True, '456': {'789': False}}
.. automodule:: redbot.core.config

View File

@ -70,11 +70,11 @@ class Admin(commands.Cog):
"""A collection of server administration utilities."""
def __init__(self):
self.conf = Config.get_conf(self, 8237492837454039, force_registration=True)
self.config = Config.get_conf(self, 8237492837454039, force_registration=True)
self.conf.register_global(serverlocked=False)
self.config.register_global(serverlocked=False)
self.conf.register_guild(
self.config.register_guild(
announce_ignore=False,
announce_channel=None, # Integer ID
selfroles=[], # List of integer ID's
@ -290,7 +290,7 @@ class Admin(commands.Cog):
async def announce(self, ctx: commands.Context, *, message: str):
"""Announce a message to all servers the bot is in."""
if not self.is_announcing():
announcer = Announcer(ctx, message, config=self.conf)
announcer = Announcer(ctx, message, config=self.config)
announcer.start()
self.__current_announcer = announcer
@ -325,7 +325,7 @@ class Admin(commands.Cog):
"""
if channel is None:
channel = ctx.channel
await self.conf.guild(ctx.guild).announce_channel.set(channel.id)
await self.config.guild(ctx.guild).announce_channel.set(channel.id)
await ctx.send(
_("The announcement channel has been set to {channel.mention}").format(channel=channel)
)
@ -333,8 +333,8 @@ class Admin(commands.Cog):
@announceset.command(name="ignore")
async def announceset_ignore(self, ctx):
"""Toggle announcements being enabled this server."""
ignored = await self.conf.guild(ctx.guild).announce_ignore()
await self.conf.guild(ctx.guild).announce_ignore.set(not ignored)
ignored = await self.config.guild(ctx.guild).announce_ignore()
await self.config.guild(ctx.guild).announce_ignore.set(not ignored)
if ignored:
await ctx.send(
_("The server {guild.name} will receive announcements.").format(guild=ctx.guild)
@ -352,14 +352,14 @@ class Admin(commands.Cog):
:param guild:
:return:
"""
selfrole_ids = set(await self.conf.guild(guild).selfroles())
selfrole_ids = set(await self.config.guild(guild).selfroles())
guild_roles = guild.roles
valid_roles = tuple(r for r in guild_roles if r.id in selfrole_ids)
valid_role_ids = set(r.id for r in valid_roles)
if selfrole_ids != valid_role_ids:
await self.conf.guild(guild).selfroles.set(list(valid_role_ids))
await self.config.guild(guild).selfroles.set(list(valid_role_ids))
# noinspection PyTypeChecker
return valid_roles
@ -427,7 +427,7 @@ class Admin(commands.Cog):
).format(role=role)
)
return
async with self.conf.guild(ctx.guild).selfroles() as curr_selfroles:
async with self.config.guild(ctx.guild).selfroles() as curr_selfroles:
if role.id not in curr_selfroles:
curr_selfroles.append(role.id)
await ctx.send(_("Added."))
@ -449,7 +449,7 @@ class Admin(commands.Cog):
).format(role=role)
)
return
async with self.conf.guild(ctx.guild).selfroles() as curr_selfroles:
async with self.config.guild(ctx.guild).selfroles() as curr_selfroles:
curr_selfroles.remove(role.id)
await ctx.send(_("Removed."))
@ -458,8 +458,8 @@ class Admin(commands.Cog):
@checks.is_owner()
async def serverlock(self, ctx: commands.Context):
"""Lock a bot to its current servers only."""
serverlocked = await self.conf.serverlocked()
await self.conf.serverlocked.set(not serverlocked)
serverlocked = await self.config.serverlocked()
await self.config.serverlocked.set(not serverlocked)
if serverlocked:
await ctx.send(_("The bot is no longer serverlocked."))
@ -468,7 +468,7 @@ class Admin(commands.Cog):
# region Event Handlers
async def on_guild_join(self, guild: discord.Guild):
if await self.conf.serverlocked():
if await self.config.serverlocked():
await guild.leave()

View File

@ -14,8 +14,7 @@ class SelfRole(commands.Converter):
role_converter = commands.RoleConverter()
role = await role_converter.convert(ctx, arg)
conf = admin.conf
selfroles = await conf.guild(ctx.guild).selfroles()
selfroles = await admin.config.guild(ctx.guild).selfroles()
if role.id not in selfroles:
raise commands.BadArgument(_("The provided role is not a valid selfrole."))

View File

@ -49,25 +49,25 @@ class Alias(commands.Cog):
def __init__(self, bot: Red):
super().__init__()
self.bot = bot
self._aliases = Config.get_conf(self, 8927348724)
self.config = Config.get_conf(self, 8927348724)
self._aliases.register_global(**self.default_global_settings)
self._aliases.register_guild(**self.default_guild_settings)
self.config.register_global(**self.default_global_settings)
self.config.register_guild(**self.default_guild_settings)
async def unloaded_aliases(self, guild: discord.Guild) -> Generator[AliasEntry, None, None]:
return (AliasEntry.from_json(d) for d in (await self._aliases.guild(guild).entries()))
return (AliasEntry.from_json(d) for d in (await self.config.guild(guild).entries()))
async def unloaded_global_aliases(self) -> Generator[AliasEntry, None, None]:
return (AliasEntry.from_json(d) for d in (await self._aliases.entries()))
return (AliasEntry.from_json(d) for d in (await self.config.entries()))
async def loaded_aliases(self, guild: discord.Guild) -> Generator[AliasEntry, None, None]:
return (
AliasEntry.from_json(d, bot=self.bot)
for d in (await self._aliases.guild(guild).entries())
for d in (await self.config.guild(guild).entries())
)
async def loaded_global_aliases(self) -> Generator[AliasEntry, None, None]:
return (AliasEntry.from_json(d, bot=self.bot) for d in (await self._aliases.entries()))
return (AliasEntry.from_json(d, bot=self.bot) for d in (await self.config.entries()))
async def is_alias(
self,
@ -123,9 +123,9 @@ class Alias(commands.Cog):
alias = AliasEntry(alias_name, command, ctx.author, global_=global_)
if global_:
settings = self._aliases
settings = self.config
else:
settings = self._aliases.guild(ctx.guild)
settings = self.config.guild(ctx.guild)
await settings.enabled.set(True)
async with settings.entries() as curr_aliases:
@ -137,9 +137,9 @@ class Alias(commands.Cog):
self, ctx: commands.Context, alias_name: str, global_: bool = False
) -> bool:
if global_:
settings = self._aliases
settings = self.config
else:
settings = self._aliases.guild(ctx.guild)
settings = self.config.guild(ctx.guild)
async with settings.entries() as aliases:
for alias in aliases:

View File

@ -48,15 +48,15 @@ class Bank(commands.Cog):
"""Base command for bank settings."""
if ctx.invoked_subcommand is None:
if await bank.is_global():
bank_name = await bank._conf.bank_name()
currency_name = await bank._conf.currency()
default_balance = await bank._conf.default_balance()
bank_name = await bank._config.bank_name()
currency_name = await bank._config.currency()
default_balance = await bank._config.default_balance()
else:
if not ctx.guild:
return
bank_name = await bank._conf.guild(ctx.guild).bank_name()
currency_name = await bank._conf.guild(ctx.guild).currency()
default_balance = await bank._conf.guild(ctx.guild).default_balance()
bank_name = await bank._config.guild(ctx.guild).bank_name()
currency_name = await bank._config.guild(ctx.guild).currency()
default_balance = await bank._config.guild(ctx.guild).default_balance()
settings = _(
"Bank settings:\n\nBank name: {bank_name}\nCurrency: {currency_name}\n"

View File

@ -40,9 +40,9 @@ class Downloader(commands.Cog):
super().__init__()
self.bot = bot
self.conf = Config.get_conf(self, identifier=998240343, force_registration=True)
self.config = Config.get_conf(self, identifier=998240343, force_registration=True)
self.conf.register_global(schema_version=0, installed_cogs={}, installed_libraries={})
self.config.register_global(schema_version=0, installed_cogs={}, installed_libraries={})
self.already_agreed = False
@ -99,22 +99,22 @@ class Downloader(commands.Cog):
self._ready.set()
async def _maybe_update_config(self) -> None:
schema_version = await self.conf.schema_version()
schema_version = await self.config.schema_version()
if schema_version == 0:
await self._schema_0_to_1()
schema_version += 1
await self.conf.schema_version.set(schema_version)
await self.config.schema_version.set(schema_version)
async def _schema_0_to_1(self):
"""
This contains migration to allow saving state
of both installed cogs and shared libraries.
"""
old_conf = await self.conf.get_raw("installed", default=[])
old_conf = await self.config.get_raw("installed", default=[])
if not old_conf:
return
async with self.conf.installed_cogs() as new_cog_conf:
async with self.config.installed_cogs() as new_cog_conf:
for cog_json in old_conf:
repo_name = cog_json["repo_name"]
module_name = cog_json["cog_name"]
@ -126,7 +126,7 @@ class Downloader(commands.Cog):
"commit": "",
"pinned": False,
}
await self.conf.clear_raw("installed")
await self.config.clear_raw("installed")
# no reliable way to get installed libraries (i.a. missing repo name)
# but it only helps `[p]cog update` run faster so it's not an issue
@ -150,7 +150,7 @@ class Downloader(commands.Cog):
All installed cogs.
"""
installed = await self.conf.installed_cogs()
installed = await self.config.installed_cogs()
# noinspection PyTypeChecker
return tuple(
InstalledModule.from_json(cog_json, self._repo_manager)
@ -167,7 +167,7 @@ class Downloader(commands.Cog):
All installed shared libraries.
"""
installed = await self.conf.installed_libraries()
installed = await self.config.installed_libraries()
# noinspection PyTypeChecker
return tuple(
InstalledModule.from_json(lib_json, self._repo_manager)
@ -195,8 +195,8 @@ class Downloader(commands.Cog):
The modules to check off.
"""
installed_cogs = await self.conf.installed_cogs()
installed_libraries = await self.conf.installed_libraries()
installed_cogs = await self.config.installed_cogs()
installed_libraries = await self.config.installed_libraries()
for module in modules:
if module.type == InstallableType.COG:
installed = installed_cogs
@ -208,8 +208,8 @@ class Downloader(commands.Cog):
repo_json = installed.setdefault(module.repo_name, {})
repo_json[module.name] = module_json
await self.conf.installed_cogs.set(installed_cogs)
await self.conf.installed_libraries.set(installed_libraries)
await self.config.installed_cogs.set(installed_cogs)
await self.config.installed_libraries.set(installed_libraries)
async def _remove_from_installed(self, modules: Iterable[InstalledModule]) -> None:
"""Remove modules from the saved list
@ -221,8 +221,8 @@ class Downloader(commands.Cog):
The modules to remove.
"""
installed_cogs = await self.conf.installed_cogs()
installed_libraries = await self.conf.installed_libraries()
installed_cogs = await self.config.installed_cogs()
installed_libraries = await self.config.installed_libraries()
for module in modules:
if module.type == InstallableType.COG:
installed = installed_cogs
@ -233,8 +233,8 @@ class Downloader(commands.Cog):
with contextlib.suppress(KeyError):
installed[module._json_repo_name].pop(module.name)
await self.conf.installed_cogs.set(installed_cogs)
await self.conf.installed_libraries.set(installed_libraries)
await self.config.installed_cogs.set(installed_cogs)
await self.config.installed_libraries.set(installed_libraries)
async def _shared_lib_load_check(self, cog_name: str) -> Optional[Repo]:
# remove in Red 3.4

View File

@ -990,8 +990,8 @@ class RepoManager:
def __init__(self) -> None:
self._repos: Dict[str, Repo] = {}
self.conf = Config.get_conf(self, identifier=170708480, force_registration=True)
self.conf.register_global(repos={})
self.config = Config.get_conf(self, identifier=170708480, force_registration=True)
self.config.register_global(repos={})
async def initialize(self) -> None:
await self._load_repos(set_repos=True)
@ -1040,7 +1040,7 @@ class RepoManager:
url=url, name=name, branch=branch, commit="", folder_path=self.repos_folder / name
)
await r.clone()
await self.conf.repos.set_raw(name, value=r.branch)
await self.config.repos.set_raw(name, value=r.branch)
self._repos[name] = r
@ -1110,7 +1110,7 @@ class RepoManager:
safe_delete(repo.folder_path)
await self.conf.repos.clear_raw(repo.name)
await self.config.repos.clear_raw(repo.name)
try:
del self._repos[name]
except KeyError:
@ -1189,10 +1189,10 @@ class RepoManager:
if not folder.is_dir():
continue
try:
branch = await self.conf.repos.get_raw(folder.stem, default="")
branch = await self.config.repos.get_raw(folder.stem, default="")
ret[folder.stem] = await Repo.from_folder(folder, branch)
if branch == "":
await self.conf.repos.set_raw(folder.stem, value=ret[folder.stem].branch)
await self.config.repos.set_raw(folder.stem, value=ret[folder.stem].branch)
except errors.NoRemoteURL:
log.warning("A remote URL does not exist for repo %s", folder.stem)
except errors.DownloaderException as err:

View File

@ -17,7 +17,7 @@ class Filter(commands.Cog):
def __init__(self, bot: Red):
super().__init__()
self.bot = bot
self.settings = Config.get_conf(self, 4766951341)
self.config = Config.get_conf(self, 4766951341)
default_guild_settings = {
"filter": [],
"filterban_count": 0,
@ -27,9 +27,9 @@ class Filter(commands.Cog):
}
default_member_settings = {"filter_count": 0, "next_reset_time": 0}
default_channel_settings = {"filter": []}
self.settings.register_guild(**default_guild_settings)
self.settings.register_member(**default_member_settings)
self.settings.register_channel(**default_channel_settings)
self.config.register_guild(**default_guild_settings)
self.config.register_member(**default_member_settings)
self.config.register_channel(**default_channel_settings)
self.register_task = self.bot.loop.create_task(self.register_filterban())
self.pattern_cache = {}
@ -62,7 +62,7 @@ class Filter(commands.Cog):
The default name used is *John Doe*.
"""
guild = ctx.guild
await self.settings.guild(guild).filter_default_name.set(name)
await self.config.guild(guild).filter_default_name.set(name)
await ctx.send(_("The name to use on filtered names has been set."))
@filterset.command(name="ban")
@ -83,12 +83,12 @@ class Filter(commands.Cog):
)
return
elif count == 0 and timeframe == 0:
await self.settings.guild(ctx.guild).filterban_count.set(0)
await self.settings.guild(ctx.guild).filterban_time.set(0)
await self.config.guild(ctx.guild).filterban_count.set(0)
await self.config.guild(ctx.guild).filterban_time.set(0)
await ctx.send(_("Autoban disabled."))
else:
await self.settings.guild(ctx.guild).filterban_count.set(count)
await self.settings.guild(ctx.guild).filterban_time.set(timeframe)
await self.config.guild(ctx.guild).filterban_count.set(count)
await self.config.guild(ctx.guild).filterban_time.set(timeframe)
await ctx.send(_("Count and time have been set."))
@commands.group(name="filter")
@ -105,7 +105,7 @@ class Filter(commands.Cog):
if ctx.invoked_subcommand is None:
server = ctx.guild
author = ctx.author
word_list = await self.settings.guild(server).filter()
word_list = await self.config.guild(server).filter()
if word_list:
words = ", ".join(word_list)
words = _("Filtered in this server:") + "\n\n" + words
@ -127,7 +127,7 @@ class Filter(commands.Cog):
if ctx.invoked_subcommand is None:
channel = ctx.channel
author = ctx.author
word_list = await self.settings.channel(channel).filter()
word_list = await self.config.channel(channel).filter()
if word_list:
words = ", ".join(word_list)
words = _("Filtered in this channel:") + "\n\n" + words
@ -276,8 +276,8 @@ class Filter(commands.Cog):
This is disabled by default.
"""
guild = ctx.guild
current_setting = await self.settings.guild(guild).filter_names()
await self.settings.guild(guild).filter_names.set(not current_setting)
current_setting = await self.config.guild(guild).filter_names()
await self.config.guild(guild).filter_names.set(not current_setting)
if current_setting:
await ctx.send(_("Names and nicknames will no longer be filtered."))
else:
@ -296,14 +296,14 @@ class Filter(commands.Cog):
) -> bool:
added = False
if isinstance(server_or_channel, discord.Guild):
async with self.settings.guild(server_or_channel).filter() as cur_list:
async with self.config.guild(server_or_channel).filter() as cur_list:
for w in words:
if w.lower() not in cur_list and w:
cur_list.append(w.lower())
added = True
elif isinstance(server_or_channel, discord.TextChannel):
async with self.settings.channel(server_or_channel).filter() as cur_list:
async with self.config.channel(server_or_channel).filter() as cur_list:
for w in words:
if w.lower not in cur_list and w:
cur_list.append(w.lower())
@ -316,14 +316,14 @@ class Filter(commands.Cog):
) -> bool:
removed = False
if isinstance(server_or_channel, discord.Guild):
async with self.settings.guild(server_or_channel).filter() as cur_list:
async with self.config.guild(server_or_channel).filter() as cur_list:
for w in words:
if w.lower() in cur_list:
cur_list.remove(w.lower())
removed = True
elif isinstance(server_or_channel, discord.TextChannel):
async with self.settings.channel(server_or_channel).filter() as cur_list:
async with self.config.channel(server_or_channel).filter() as cur_list:
for w in words:
if w.lower() in cur_list:
cur_list.remove(w.lower())
@ -347,9 +347,9 @@ class Filter(commands.Cog):
try:
pattern = self.pattern_cache[(guild, channel)]
except KeyError:
word_list = set(await self.settings.guild(guild).filter())
word_list = set(await self.config.guild(guild).filter())
if channel:
word_list |= set(await self.settings.channel(channel).filter())
word_list |= set(await self.config.channel(channel).filter())
if word_list:
pattern = re.compile(
@ -368,18 +368,18 @@ class Filter(commands.Cog):
server = message.guild
author = message.author
filter_count = await self.settings.guild(server).filterban_count()
filter_time = await self.settings.guild(server).filterban_time()
user_count = await self.settings.member(author).filter_count()
next_reset_time = await self.settings.member(author).next_reset_time()
filter_count = await self.config.guild(server).filterban_count()
filter_time = await self.config.guild(server).filterban_time()
user_count = await self.config.member(author).filter_count()
next_reset_time = await self.config.member(author).next_reset_time()
if filter_count > 0 and filter_time > 0:
if message.created_at.timestamp() >= next_reset_time:
next_reset_time = message.created_at.timestamp() + filter_time
await self.settings.member(author).next_reset_time.set(next_reset_time)
await self.config.member(author).next_reset_time.set(next_reset_time)
if user_count > 0:
user_count = 0
await self.settings.member(author).filter_count.set(user_count)
await self.config.member(author).filter_count.set(user_count)
hits = await self.filter_hits(message.content, message.channel)
@ -392,7 +392,7 @@ class Filter(commands.Cog):
self.bot.dispatch("filter_message_delete", message, hits)
if filter_count > 0 and filter_time > 0:
user_count += 1
await self.settings.member(author).filter_count.set(user_count)
await self.config.member(author).filter_count.set(user_count)
if (
user_count >= filter_count
and message.created_at.timestamp() < next_reset_time
@ -449,12 +449,12 @@ class Filter(commands.Cog):
return # Discord Hierarchy applies to nicks
if await self.bot.is_automod_immune(member):
return
if not await self.settings.guild(member.guild).filter_names():
if not await self.config.guild(member.guild).filter_names():
return
if await self.filter_hits(member.display_name, member.guild):
name_to_use = await self.settings.guild(member.guild).filter_default_name()
name_to_use = await self.config.guild(member.guild).filter_default_name()
reason = _("Filtered nickname") if member.nick else _("Filtered name")
try:
await member.edit(nick=name_to_use, reason=reason)

View File

@ -18,8 +18,8 @@ class Image(commands.Cog):
def __init__(self, bot):
super().__init__()
self.bot = bot
self.settings = Config.get_conf(self, identifier=2652104208, force_registration=True)
self.settings.register_global(**self.default_global)
self.config = Config.get_conf(self, identifier=2652104208, force_registration=True)
self.config.register_global(**self.default_global)
self.session = aiohttp.ClientSession()
self.imgur_base_url = "https://api.imgur.com/3/"
@ -28,11 +28,11 @@ class Image(commands.Cog):
async def initialize(self) -> None:
"""Move the API keys from cog stored config to core bot config if they exist."""
imgur_token = await self.settings.imgur_client_id()
imgur_token = await self.config.imgur_client_id()
if imgur_token is not None:
if not await self.bot.get_shared_api_tokens("imgur"):
await self.bot.set_shared_api_tokens("imgur", client_id=imgur_token)
await self.settings.imgur_client_id.clear()
await self.config.imgur_client_id.clear()
@commands.group(name="imgur")
async def _imgur(self, ctx):

View File

@ -14,7 +14,7 @@ class MixinMeta(ABC):
"""
def __init__(self, *_args):
self.settings: Config
self.config: Config
self.bot: Red
self.cache: dict

View File

@ -23,7 +23,7 @@ class Events(MixinMeta):
guild_cache = self.cache.get(guild.id, None)
if guild_cache is None:
repeats = await self.settings.guild(guild).delete_repeats()
repeats = await self.config.guild(guild).delete_repeats()
if repeats == -1:
return False
guild_cache = self.cache[guild.id] = defaultdict(lambda: deque(maxlen=repeats))
@ -45,7 +45,7 @@ class Events(MixinMeta):
guild = message.guild
author = message.author
max_mentions = await self.settings.guild(guild).ban_mention_spam()
max_mentions = await self.config.guild(guild).ban_mention_spam()
if max_mentions:
mentions = set(message.mentions)
if len(mentions) >= max_mentions:
@ -97,7 +97,7 @@ class Events(MixinMeta):
@commands.Cog.listener()
async def on_user_update(self, before: discord.User, after: discord.User):
if before.name != after.name:
async with self.settings.user(before).past_names() as name_list:
async with self.config.user(before).past_names() as name_list:
while None in name_list: # clean out null entries from a bug
name_list.remove(None)
if after.name in name_list:
@ -110,7 +110,7 @@ class Events(MixinMeta):
@commands.Cog.listener()
async def on_member_update(self, before: discord.Member, after: discord.Member):
if before.nick != after.nick and after.nick is not None:
async with self.settings.member(before).past_nicks() as nick_list:
async with self.config.member(before).past_nicks() as nick_list:
while None in nick_list: # clean out null entries from a bug
nick_list.remove(None)
if after.nick in nick_list:

View File

@ -71,7 +71,7 @@ class KickBanMixin(MixinMeta):
if author == user:
return _("I cannot let you do that. Self-harm is bad {}").format("\N{PENSIVE FACE}")
elif not await is_allowed_by_hierarchy(self.bot, self.settings, guild, author, user):
elif not await is_allowed_by_hierarchy(self.bot, self.config, guild, author, user):
return _(
"I cannot let you do that. You are "
"not higher than the user in the role "
@ -82,7 +82,7 @@ class KickBanMixin(MixinMeta):
elif not (0 <= days <= 7):
return _("Invalid days. Must be between 0 and 7.")
toggle = await self.settings.guild(guild).dm_on_kickban()
toggle = await self.config.guild(guild).dm_on_kickban()
if toggle:
with contextlib.suppress(discord.HTTPException):
em = discord.Embed(
@ -142,13 +142,13 @@ class KickBanMixin(MixinMeta):
except discord.HTTPException:
continue
async with self.settings.guild(guild).current_tempbans() as guild_tempbans:
async with self.config.guild(guild).current_tempbans() as guild_tempbans:
for uid in guild_tempbans.copy():
user = banned_users.get(uid, None)
if not user:
continue
unban_time = datetime.utcfromtimestamp(
await self.settings.member(member(uid, guild)).banned_until()
await self.config.member(member(uid, guild)).banned_until()
)
if datetime.utcnow() > unban_time: # Time to unban the user
queue_entry = (guild.id, uid)
@ -186,7 +186,7 @@ class KickBanMixin(MixinMeta):
)
)
return
elif not await is_allowed_by_hierarchy(self.bot, self.settings, guild, author, user):
elif not await is_allowed_by_hierarchy(self.bot, self.config, guild, author, user):
await ctx.send(
_(
"I cannot let you do that. You are "
@ -199,7 +199,7 @@ class KickBanMixin(MixinMeta):
await ctx.send(_("I cannot do that due to discord hierarchy rules"))
return
audit_reason = get_audit_reason(author, reason)
toggle = await self.settings.guild(guild).dm_on_kickban()
toggle = await self.config.guild(guild).dm_on_kickban()
if toggle:
with contextlib.suppress(discord.HTTPException):
em = discord.Embed(
@ -255,7 +255,7 @@ class KickBanMixin(MixinMeta):
author = ctx.author
guild = ctx.guild
if days is None:
days = await self.settings.guild(guild).default_days()
days = await self.config.guild(guild).default_days()
result = await self.ban_user(
user=user, ctx=ctx, days=days, reason=reason, create_modlog_case=True
@ -309,7 +309,7 @@ class KickBanMixin(MixinMeta):
return
if days is None:
days = await self.settings.guild(guild).default_days()
days = await self.config.guild(guild).default_days()
if not (0 <= days <= 7):
await ctx.send(_("Invalid days. Must be between 0 and 7."))
@ -409,10 +409,10 @@ class KickBanMixin(MixinMeta):
invite = ""
queue_entry = (guild.id, user.id)
await self.settings.member(user).banned_until.set(unban_time.timestamp())
cur_tbans = await self.settings.guild(guild).current_tempbans()
await self.config.member(user).banned_until.set(unban_time.timestamp())
cur_tbans = await self.config.guild(guild).current_tempbans()
cur_tbans.append(user.id)
await self.settings.guild(guild).current_tempbans.set(cur_tbans)
await self.config.guild(guild).current_tempbans.set(cur_tbans)
with contextlib.suppress(discord.HTTPException):
# We don't want blocked DMs preventing us from banning
@ -464,7 +464,7 @@ class KickBanMixin(MixinMeta):
)
)
return
elif not await is_allowed_by_hierarchy(self.bot, self.settings, guild, author, user):
elif not await is_allowed_by_hierarchy(self.bot, self.config, guild, author, user):
await ctx.send(
_(
"I cannot let you do that. You are "
@ -540,7 +540,7 @@ class KickBanMixin(MixinMeta):
if await self._voice_perm_check(ctx, user_voice_state, move_members=True) is False:
return
elif not await is_allowed_by_hierarchy(self.bot, self.settings, guild, author, member):
elif not await is_allowed_by_hierarchy(self.bot, self.config, guild, author, member):
await ctx.send(
_(
"I cannot let you do that. You are "
@ -620,7 +620,7 @@ class KickBanMixin(MixinMeta):
await ctx.send(e)
await ctx.send(_("Unbanned that user from this server"))
if await self.settings.guild(guild).reinvite_on_unban():
if await self.config.guild(guild).reinvite_on_unban():
user = ctx.bot.get_user(user_id)
if not user:
await ctx.send(

View File

@ -69,12 +69,12 @@ class Mod(
super().__init__()
self.bot = bot
self.settings = Config.get_conf(self, 4961522000, force_registration=True)
self.settings.register_global(**self.default_global_settings)
self.settings.register_guild(**self.default_guild_settings)
self.settings.register_channel(**self.default_channel_settings)
self.settings.register_member(**self.default_member_settings)
self.settings.register_user(**self.default_user_settings)
self.config = Config.get_conf(self, 4961522000, force_registration=True)
self.config.register_global(**self.default_global_settings)
self.config.register_guild(**self.default_guild_settings)
self.config.register_channel(**self.default_channel_settings)
self.config.register_member(**self.default_member_settings)
self.config.register_user(**self.default_user_settings)
self.cache: dict = {}
self.tban_expiry_task = self.bot.loop.create_task(self.check_tempban_expirations())
self.last_case: dict = defaultdict(dict)
@ -93,45 +93,45 @@ class Mod(
async def _maybe_update_config(self):
"""Maybe update `delete_delay` value set by Config prior to Mod 1.0.0."""
if not await self.settings.version():
guild_dict = await self.settings.all_guilds()
if not await self.config.version():
guild_dict = await self.config.all_guilds()
for guild_id, info in guild_dict.items():
delete_repeats = info.get("delete_repeats", False)
if delete_repeats:
val = 3
else:
val = -1
await self.settings.guild(discord.Object(id=guild_id)).delete_repeats.set(val)
await self.settings.version.set("1.0.0") # set version of last update
if await self.settings.version() < "1.1.0":
await self.config.guild(discord.Object(id=guild_id)).delete_repeats.set(val)
await self.config.version.set("1.0.0") # set version of last update
if await self.config.version() < "1.1.0":
msg = _(
"Ignored guilds and channels have been moved. "
"Please use `[p]moveignoredchannels` if "
"you were previously using these functions."
)
self.bot.loop.create_task(send_to_owners_with_prefix_replaced(self.bot, msg))
await self.settings.version.set("1.1.0")
if await self.settings.version() < "1.2.0":
await self.config.version.set("1.1.0")
if await self.config.version() < "1.2.0":
msg = _(
"Delete delay settings have been moved. "
"Please use `[p]movedeletedelay` if "
"you were previously using these functions."
)
self.bot.loop.create_task(send_to_owners_with_prefix_replaced(self.bot, msg))
await self.settings.version.set("1.2.0")
await self.config.version.set("1.2.0")
@commands.command()
@commands.is_owner()
async def moveignoredchannels(self, ctx: commands.Context) -> None:
"""Move ignored channels and servers to core"""
all_guilds = await self.settings.all_guilds()
all_channels = await self.settings.all_channels()
all_guilds = await self.config.all_guilds()
all_channels = await self.config.all_channels()
for guild_id, settings in all_guilds.items():
await self.bot._config.guild_from_id(guild_id).ignored.set(settings["ignored"])
await self.settings.guild_from_id(guild_id).ignored.clear()
await self.config.guild_from_id(guild_id).ignored.clear()
for channel_id, settings in all_channels.items():
await self.bot._config.channel_from_id(channel_id).ignored.set(settings["ignored"])
await self.settings.channel_from_id(channel_id).clear()
await self.config.channel_from_id(channel_id).clear()
await ctx.send(_("Ignored channels and guilds restored."))
@commands.command()
@ -140,10 +140,10 @@ class Mod(
"""
Move deletedelay settings to core
"""
all_guilds = await self.settings.all_guilds()
all_guilds = await self.config.all_guilds()
for guild_id, settings in all_guilds.items():
await self.bot._config.guild_from_id(guild_id).delete_delay.set(
settings["delete_delay"]
)
await self.settings.guild_from_id(guild_id).delete_delay.clear()
await self.config.guild_from_id(guild_id).delete_delay.clear()
await ctx.send(_("Delete delay settings restored."))

View File

@ -415,7 +415,7 @@ class MuteMixin(MixinMeta):
if all(getattr(permissions, p) is False for p in new_overs.keys()):
return False, _(mute_unmute_issues["already_muted"])
elif not await is_allowed_by_hierarchy(self.bot, self.settings, guild, author, user):
elif not await is_allowed_by_hierarchy(self.bot, self.config, guild, author, user):
return False, _(mute_unmute_issues["hierarchy_problem"])
old_overs = {k: getattr(overwrites, k) for k in new_overs}
@ -430,9 +430,7 @@ class MuteMixin(MixinMeta):
elif e.code == 10009:
return False, _(mute_unmute_issues["left_guild"])
else:
await self.settings.member(user).set_raw(
"perms_cache", str(channel.id), value=old_overs
)
await self.config.member(user).set_raw("perms_cache", str(channel.id), value=old_overs)
return True, None
async def unmute_user(
@ -444,7 +442,7 @@ class MuteMixin(MixinMeta):
reason: str,
) -> (bool, str):
overwrites = channel.overwrites_for(user)
perms_cache = await self.settings.member(user).perms_cache()
perms_cache = await self.config.member(user).perms_cache()
if channel.id in perms_cache:
old_values = perms_cache[channel.id]
@ -454,7 +452,7 @@ class MuteMixin(MixinMeta):
if all(getattr(overwrites, k) == v for k, v in old_values.items()):
return False, _(mute_unmute_issues["already_unmuted"])
elif not await is_allowed_by_hierarchy(self.bot, self.settings, guild, author, user):
elif not await is_allowed_by_hierarchy(self.bot, self.config, guild, author, user):
return False, _(mute_unmute_issues["hierarchy_problem"])
overwrites.update(**old_values)
@ -473,5 +471,5 @@ class MuteMixin(MixinMeta):
elif e.code == 10009:
return False, _(mute_unmute_issues["left_guild"])
else:
await self.settings.member(user).clear_raw("perms_cache", str(channel.id))
await self.config.member(user).clear_raw("perms_cache", str(channel.id))
return True, None

View File

@ -20,8 +20,8 @@ class ModInfo(MixinMeta):
"""
async def get_names_and_nicks(self, user):
names = await self.settings.user(user).past_names()
nicks = await self.settings.member(user).past_nicks()
names = await self.config.user(user).past_names()
nicks = await self.config.member(user).past_nicks()
if names:
names = [escape_spoilers_and_mass_mentions(name) for name in names if name]
if nicks:

View File

@ -21,7 +21,7 @@ class ModSettings(MixinMeta):
if ctx.invoked_subcommand is None:
guild = ctx.guild
# Display current settings
data = await self.settings.guild(guild).all()
data = await self.config.guild(guild).all()
delete_repeats = data["delete_repeats"]
ban_mention_spam = data["ban_mention_spam"]
respect_hierarchy = data["respect_hierarchy"]
@ -73,14 +73,14 @@ class ModSettings(MixinMeta):
This is enabled by default.
"""
guild = ctx.guild
toggled = await self.settings.guild(guild).respect_hierarchy()
toggled = await self.config.guild(guild).respect_hierarchy()
if not toggled:
await self.settings.guild(guild).respect_hierarchy.set(True)
await self.config.guild(guild).respect_hierarchy.set(True)
await ctx.send(
_("Role hierarchy will be checked when moderation commands are issued.")
)
else:
await self.settings.guild(guild).respect_hierarchy.set(False)
await self.config.guild(guild).respect_hierarchy.set(False)
await ctx.send(
_("Role hierarchy will be ignored when moderation commands are issued.")
)
@ -99,7 +99,7 @@ class ModSettings(MixinMeta):
if max_mentions:
if max_mentions < 5:
max_mentions = 5
await self.settings.guild(guild).ban_mention_spam.set(max_mentions)
await self.config.guild(guild).ban_mention_spam.set(max_mentions)
await ctx.send(
_(
"Autoban for mention spam enabled. "
@ -108,11 +108,11 @@ class ModSettings(MixinMeta):
).format(max_mentions=max_mentions)
)
else:
cur_setting = await self.settings.guild(guild).ban_mention_spam()
cur_setting = await self.config.guild(guild).ban_mention_spam()
if not cur_setting:
await ctx.send_help()
return
await self.settings.guild(guild).ban_mention_spam.set(False)
await self.config.guild(guild).ban_mention_spam.set(False)
await ctx.send(_("Autoban for mention spam disabled."))
@modset.command()
@ -127,11 +127,11 @@ class ModSettings(MixinMeta):
guild = ctx.guild
if repeats is not None:
if repeats == -1:
await self.settings.guild(guild).delete_repeats.set(repeats)
await self.config.guild(guild).delete_repeats.set(repeats)
self.cache.pop(guild.id, None) # remove cache with old repeat limits
await ctx.send(_("Repeated messages will be ignored."))
elif 2 <= repeats <= 20:
await self.settings.guild(guild).delete_repeats.set(repeats)
await self.config.guild(guild).delete_repeats.set(repeats)
# purge and update cache to new repeat limits
self.cache[guild.id] = defaultdict(lambda: deque(maxlen=repeats))
await ctx.send(
@ -145,7 +145,7 @@ class ModSettings(MixinMeta):
)
)
else:
repeats = await self.settings.guild(guild).delete_repeats()
repeats = await self.config.guild(guild).delete_repeats()
if repeats != -1:
await ctx.send(
_(
@ -166,16 +166,16 @@ class ModSettings(MixinMeta):
to the newly-unbanned user.
"""
guild = ctx.guild
cur_setting = await self.settings.guild(guild).reinvite_on_unban()
cur_setting = await self.config.guild(guild).reinvite_on_unban()
if not cur_setting:
await self.settings.guild(guild).reinvite_on_unban.set(True)
await self.config.guild(guild).reinvite_on_unban.set(True)
await ctx.send(
_("Users unbanned with `{command}` will be reinvited.").format(
command=f"{ctx.clean_prefix}unban"
)
)
else:
await self.settings.guild(guild).reinvite_on_unban.set(False)
await self.config.guild(guild).reinvite_on_unban.set(False)
await ctx.send(
_("Users unbanned with `{command}` will not be reinvited.").format(
command=f"{ctx.clean_prefix}unban"
@ -192,12 +192,12 @@ class ModSettings(MixinMeta):
"""
guild = ctx.guild
if enabled is None:
setting = await self.settings.guild(guild).dm_on_kickban()
setting = await self.config.guild(guild).dm_on_kickban()
await ctx.send(
_("DM when kicked/banned is currently set to: {setting}").format(setting=setting)
)
return
await self.settings.guild(guild).dm_on_kickban.set(enabled)
await self.config.guild(guild).dm_on_kickban.set(enabled)
if enabled:
await ctx.send(_("Bot will now attempt to send a DM to user before kick and ban."))
else:
@ -215,7 +215,7 @@ class ModSettings(MixinMeta):
guild = ctx.guild
if not (0 <= days <= 7):
return await ctx.send(_("Invalid number of days. Must be between 0 and 7."))
await self.settings.guild(guild).default_days.set(days)
await self.config.guild(guild).default_days.set(days)
await ctx.send(
_("{days} days worth of messages will be deleted when a user is banned.").format(
days=days

View File

@ -54,11 +54,11 @@ class Streams(commands.Cog):
def __init__(self, bot: Red):
super().__init__()
self.db: Config = Config.get_conf(self, 26262626)
self.config: Config = Config.get_conf(self, 26262626)
self.ttv_bearer_cache: dict = {}
self.db.register_global(**self.global_defaults)
self.db.register_guild(**self.guild_defaults)
self.db.register_role(**self.role_defaults)
self.config.register_global(**self.global_defaults)
self.config.register_guild(**self.guild_defaults)
self.config.register_role(**self.role_defaults)
self.bot: Red = bot
@ -95,7 +95,7 @@ class Streams(commands.Cog):
async def move_api_keys(self) -> None:
"""Move the API keys from cog stored config to core bot config if they exist."""
tokens = await self.db.tokens()
tokens = await self.config.tokens()
youtube = await self.bot.get_shared_api_tokens("youtube")
twitch = await self.bot.get_shared_api_tokens("twitch")
for token_type, token in tokens.items():
@ -104,7 +104,7 @@ class Streams(commands.Cog):
if token_type == "TwitchStream" and "client_id" not in twitch:
# Don't need to check Community since they're set the same
await self.bot.set_shared_api_tokens("twitch", client_id=token)
await self.db.tokens.clear()
await self.config.tokens.clear()
async def get_twitch_bearer_token(self) -> None:
tokens = await self.bot.get_shared_api_tokens("twitch")
@ -244,7 +244,7 @@ class Streams(commands.Cog):
else:
if isinstance(info, tuple):
embed, is_rerun = info
ignore_reruns = await self.db.guild(ctx.channel.guild).ignore_reruns()
ignore_reruns = await self.config.guild(ctx.channel.guild).ignore_reruns()
if ignore_reruns and is_rerun:
await ctx.send(_("That user is offline."))
return
@ -418,7 +418,7 @@ class Streams(commands.Cog):
if refresh_time < 60:
return await ctx.send(_("You cannot set the refresh timer to less than 60 seconds"))
await self.db.refresh_timer.set(refresh_time)
await self.config.refresh_timer.set(refresh_time)
await ctx.send(
_("Refresh timer set to {refresh_time} seconds".format(refresh_time=refresh_time))
)
@ -484,7 +484,7 @@ class Streams(commands.Cog):
"""
if message is not None:
guild = ctx.guild
await self.db.guild(guild).live_message_mention.set(message)
await self.config.guild(guild).live_message_mention.set(message)
await ctx.send(_("Stream alert message set!"))
else:
await ctx.send_help()
@ -500,7 +500,7 @@ class Streams(commands.Cog):
"""
if message is not None:
guild = ctx.guild
await self.db.guild(guild).live_message_nomention.set(message)
await self.config.guild(guild).live_message_nomention.set(message)
await ctx.send(_("Stream alert message set!"))
else:
await ctx.send_help()
@ -510,8 +510,8 @@ class Streams(commands.Cog):
async def clear_message(self, ctx: commands.Context):
"""Reset the stream alert messages in this server."""
guild = ctx.guild
await self.db.guild(guild).live_message_mention.set(False)
await self.db.guild(guild).live_message_nomention.set(False)
await self.config.guild(guild).live_message_mention.set(False)
await self.config.guild(guild).live_message_nomention.set(False)
await ctx.send(_("Stream alerts in this server will now use the default alert message."))
@streamset.group()
@ -525,12 +525,12 @@ class Streams(commands.Cog):
async def all(self, ctx: commands.Context):
"""Toggle the `@\u200beveryone` mention."""
guild = ctx.guild
current_setting = await self.db.guild(guild).mention_everyone()
current_setting = await self.config.guild(guild).mention_everyone()
if current_setting:
await self.db.guild(guild).mention_everyone.set(False)
await self.config.guild(guild).mention_everyone.set(False)
await ctx.send(_("`@\u200beveryone` will no longer be mentioned for stream alerts."))
else:
await self.db.guild(guild).mention_everyone.set(True)
await self.config.guild(guild).mention_everyone.set(True)
await ctx.send(_("When a stream is live, `@\u200beveryone` will be mentioned."))
@mention.command(aliases=["here"])
@ -538,28 +538,28 @@ class Streams(commands.Cog):
async def online(self, ctx: commands.Context):
"""Toggle the `@\u200bhere` mention."""
guild = ctx.guild
current_setting = await self.db.guild(guild).mention_here()
current_setting = await self.config.guild(guild).mention_here()
if current_setting:
await self.db.guild(guild).mention_here.set(False)
await self.config.guild(guild).mention_here.set(False)
await ctx.send(_("`@\u200bhere` will no longer be mentioned for stream alerts."))
else:
await self.db.guild(guild).mention_here.set(True)
await self.config.guild(guild).mention_here.set(True)
await ctx.send(_("When a stream is live, `@\u200bhere` will be mentioned."))
@mention.command()
@commands.guild_only()
async def role(self, ctx: commands.Context, *, role: discord.Role):
"""Toggle a role mention."""
current_setting = await self.db.role(role).mention()
current_setting = await self.config.role(role).mention()
if current_setting:
await self.db.role(role).mention.set(False)
await self.config.role(role).mention.set(False)
await ctx.send(
_("`@\u200b{role.name}` will no longer be mentioned for stream alerts.").format(
role=role
)
)
else:
await self.db.role(role).mention.set(True)
await self.config.role(role).mention.set(True)
msg = _(
"When a stream or community is live, `@\u200b{role.name}` will be mentioned."
).format(role=role)
@ -576,7 +576,7 @@ class Streams(commands.Cog):
@commands.guild_only()
async def autodelete(self, ctx: commands.Context, on_off: bool):
"""Toggle alert deletion for when streams go offline."""
await self.db.guild(ctx.guild).autodelete.set(on_off)
await self.config.guild(ctx.guild).autodelete.set(on_off)
if on_off:
await ctx.send(_("The notifications will be deleted once streams go offline."))
else:
@ -587,12 +587,12 @@ class Streams(commands.Cog):
async def ignore_reruns(self, ctx: commands.Context):
"""Toggle excluding rerun streams from alerts."""
guild = ctx.guild
current_setting = await self.db.guild(guild).ignore_reruns()
current_setting = await self.config.guild(guild).ignore_reruns()
if current_setting:
await self.db.guild(guild).ignore_reruns.set(False)
await self.config.guild(guild).ignore_reruns.set(False)
await ctx.send(_("Streams of type 'rerun' will be included in alerts."))
else:
await self.db.guild(guild).ignore_reruns.set(True)
await self.config.guild(guild).ignore_reruns.set(True)
await ctx.send(_("Streams of type 'rerun' will no longer send an alert."))
async def add_or_remove(self, ctx: commands.Context, stream):
@ -653,7 +653,7 @@ class Streams(commands.Cog):
await self.check_streams()
except asyncio.CancelledError:
pass
await asyncio.sleep(await self.db.refresh_timer())
await asyncio.sleep(await self.config.refresh_timer())
async def check_streams(self):
for stream in self.streams:
@ -670,7 +670,7 @@ class Streams(commands.Cog):
continue
for message in stream._messages_cache:
with contextlib.suppress(Exception):
autodelete = await self.db.guild(message.guild).autodelete()
autodelete = await self.config.guild(message.guild).autodelete()
if autodelete:
await message.delete()
stream._messages_cache.clear()
@ -682,13 +682,15 @@ class Streams(commands.Cog):
channel = self.bot.get_channel(channel_id)
if not channel:
continue
ignore_reruns = await self.db.guild(channel.guild).ignore_reruns()
ignore_reruns = await self.config.guild(channel.guild).ignore_reruns()
if ignore_reruns and is_rerun:
continue
mention_str, edited_roles = await self._get_mention_str(channel.guild)
if mention_str:
alert_msg = await self.db.guild(channel.guild).live_message_mention()
alert_msg = await self.config.guild(
channel.guild
).live_message_mention()
if alert_msg:
content = alert_msg.format(mention=mention_str, stream=stream)
else:
@ -699,7 +701,9 @@ class Streams(commands.Cog):
),
)
else:
alert_msg = await self.db.guild(channel.guild).live_message_nomention()
alert_msg = await self.config.guild(
channel.guild
).live_message_nomention()
if alert_msg:
content = alert_msg.format(stream=stream)
else:
@ -720,7 +724,7 @@ class Streams(commands.Cog):
"""Returns a 2-tuple with the string containing the mentions, and a list of
all roles which need to have their `mentionable` property set back to False.
"""
settings = self.db.guild(guild)
settings = self.config.guild(guild)
mentions = []
edited_roles = []
if await settings.mention_everyone():
@ -729,7 +733,7 @@ class Streams(commands.Cog):
mentions.append("@here")
can_manage_roles = guild.me.guild_permissions.manage_roles
for role in guild.roles:
if await self.db.role(role).mention():
if await self.config.role(role).mention():
if can_manage_roles and not role.mentionable:
try:
await role.edit(mentionable=True)
@ -755,7 +759,7 @@ class Streams(commands.Cog):
async def load_streams(self):
streams = []
for raw_stream in await self.db.streams():
for raw_stream in await self.config.streams():
_class = getattr(_streamtypes, raw_stream["type"], None)
if not _class:
continue
@ -786,7 +790,7 @@ class Streams(commands.Cog):
for stream in self.streams:
raw_streams.append(stream.export())
await self.db.streams.set(raw_streams)
await self.config.streams.set(raw_streams)
def cog_unload(self):
if self.task:

View File

@ -42,9 +42,9 @@ class Trivia(commands.Cog):
def __init__(self):
super().__init__()
self.trivia_sessions = []
self.conf = Config.get_conf(self, identifier=UNIQUE_ID, force_registration=True)
self.config = Config.get_conf(self, identifier=UNIQUE_ID, force_registration=True)
self.conf.register_guild(
self.config.register_guild(
max_score=10,
timeout=120.0,
delay=15.0,
@ -54,7 +54,7 @@ class Trivia(commands.Cog):
allow_override=True,
)
self.conf.register_member(wins=0, games=0, total_score=0)
self.config.register_member(wins=0, games=0, total_score=0)
@commands.group()
@commands.guild_only()
@ -62,7 +62,7 @@ class Trivia(commands.Cog):
async def triviaset(self, ctx: commands.Context):
"""Manage Trivia settings."""
if ctx.invoked_subcommand is None:
settings = self.conf.guild(ctx.guild)
settings = self.config.guild(ctx.guild)
settings_dict = await settings.all()
msg = box(
_(
@ -85,7 +85,7 @@ class Trivia(commands.Cog):
if score < 0:
await ctx.send(_("Score must be greater than 0."))
return
settings = self.conf.guild(ctx.guild)
settings = self.config.guild(ctx.guild)
await settings.max_score.set(score)
await ctx.send(_("Done. Points required to win set to {num}.").format(num=score))
@ -95,14 +95,14 @@ class Trivia(commands.Cog):
if seconds < 4.0:
await ctx.send(_("Must be at least 4 seconds."))
return
settings = self.conf.guild(ctx.guild)
settings = self.config.guild(ctx.guild)
await settings.delay.set(seconds)
await ctx.send(_("Done. Maximum seconds to answer set to {num}.").format(num=seconds))
@triviaset.command(name="stopafter")
async def triviaset_stopafter(self, ctx: commands.Context, seconds: finite_float):
"""Set how long until trivia stops due to no response."""
settings = self.conf.guild(ctx.guild)
settings = self.config.guild(ctx.guild)
if seconds < await settings.delay():
await ctx.send(_("Must be larger than the answer time limit."))
return
@ -116,7 +116,7 @@ class Trivia(commands.Cog):
@triviaset.command(name="override")
async def triviaset_allowoverride(self, ctx: commands.Context, enabled: bool):
"""Allow/disallow trivia lists to override settings."""
settings = self.conf.guild(ctx.guild)
settings = self.config.guild(ctx.guild)
await settings.allow_override.set(enabled)
if enabled:
await ctx.send(
@ -136,7 +136,7 @@ class Trivia(commands.Cog):
If enabled, the bot will gain a point if no one guesses correctly.
"""
settings = self.conf.guild(ctx.guild)
settings = self.config.guild(ctx.guild)
await settings.bot_plays.set(enabled)
if enabled:
await ctx.send(_("Done. I'll now gain a point if users don't answer in time."))
@ -150,7 +150,7 @@ class Trivia(commands.Cog):
If enabled, the bot will reveal the answer if no one guesses correctly
in time.
"""
settings = self.conf.guild(ctx.guild)
settings = self.config.guild(ctx.guild)
await settings.reveal_answer.set(enabled)
if enabled:
await ctx.send(_("Done. I'll reveal the answer if no one knows it."))
@ -170,7 +170,7 @@ class Trivia(commands.Cog):
The number of credits is determined by multiplying their total score by
this multiplier.
"""
settings = self.conf.guild(ctx.guild)
settings = self.config.guild(ctx.guild)
if multiplier < 0:
await ctx.send(_("Multiplier must be at least 0."))
return
@ -307,7 +307,7 @@ class Trivia(commands.Cog):
_("The trivia list was parsed successfully, however it appears to be empty!")
)
return
settings = await self.conf.guild(ctx.guild).all()
settings = await self.config.guild(ctx.guild).all()
config = trivia_dict.pop("CONFIG", None)
if config and settings["allow_override"]:
settings.update(config)
@ -383,7 +383,7 @@ class Trivia(commands.Cog):
)
return
guild = ctx.guild
data = await self.conf.all_members(guild)
data = await self.config.all_members(guild)
data = {guild.get_member(u): d for u, d in data.items()}
data.pop(None, None) # remove any members which aren't in the guild
await self.send_leaderboard(ctx, data, key, top)
@ -411,7 +411,7 @@ class Trivia(commands.Cog):
).format(field_name=sort_by, prefix=ctx.clean_prefix)
)
return
data = await self.conf.all_members()
data = await self.config.all_members()
collated_data = {}
for guild_id, guild_data in data.items():
guild = ctx.bot.get_guild(guild_id)
@ -555,12 +555,12 @@ class Trivia(commands.Cog):
for member, score in session.scores.items():
if member.id == session.ctx.bot.user.id:
continue
stats = await self.conf.member(member).all()
stats = await self.config.member(member).all()
if score == max_score:
stats["wins"] += 1
stats["total_score"] += score
stats["games"] += 1
await self.conf.member(member).set(stats)
await self.config.member(member).set(stats)
def get_trivia_list(self, category: str) -> dict:
"""Get the trivia list corresponding to the given category.

View File

@ -64,16 +64,16 @@ _DEFAULT_MEMBER = {"name": "", "balance": 0, "created_at": 0}
_DEFAULT_USER = _DEFAULT_MEMBER
_conf: Config = None
_config: Config = None
def _init():
global _conf
_conf = Config.get_conf(None, 384734293238749, cog_name="Bank", force_registration=True)
_conf.register_global(**_DEFAULT_GLOBAL)
_conf.register_guild(**_DEFAULT_GUILD)
_conf.register_member(**_DEFAULT_MEMBER)
_conf.register_user(**_DEFAULT_USER)
global _config
_config = Config.get_conf(None, 384734293238749, cog_name="Bank", force_registration=True)
_config.register_global(**_DEFAULT_GLOBAL)
_config.register_guild(**_DEFAULT_GUILD)
_config.register_member(**_DEFAULT_MEMBER)
_config.register_user(**_DEFAULT_USER)
class Account:
@ -211,9 +211,9 @@ async def set_balance(member: Union[discord.Member, discord.User], amount: int)
user=member.display_name, max_balance=max_bal, currency_name=currency
)
if await is_global():
group = _conf.user(member)
group = _config.user(member)
else:
group = _conf.member(member)
group = _config.member(member)
await group.balance.set(amount)
if await group.created_at() == 0:
@ -376,9 +376,9 @@ async def wipe_bank(guild: Optional[discord.Guild] = None) -> None:
"""
if await is_global():
await _conf.clear_all_users()
await _config.clear_all_users()
else:
await _conf.clear_all_members(guild)
await _config.clear_all_members(guild)
async def bank_prune(bot: Red, guild: discord.Guild = None, user_id: int = None) -> None:
@ -407,14 +407,14 @@ async def bank_prune(bot: Red, guild: discord.Guild = None, user_id: int = None)
if global_bank:
_guilds = [g for g in bot.guilds if not g.unavailable and g.large and not g.chunked]
_uguilds = [g for g in bot.guilds if g.unavailable]
group = _conf._get_base_group(_conf.USER)
group = _config._get_base_group(_config.USER)
else:
if guild is None:
raise BankPruneError("'guild' can't be None when pruning a local bank")
_guilds = [guild] if not guild.unavailable and guild.large else []
_uguilds = [guild] if guild.unavailable else []
group = _conf._get_base_group(_conf.MEMBER, str(guild.id))
group = _config._get_base_group(_config.MEMBER, str(guild.id))
if user_id is None:
await bot.request_offline_members(*_guilds)
@ -458,7 +458,7 @@ async def get_leaderboard(positions: int = None, guild: discord.Guild = None) ->
"""
if await is_global():
raw_accounts = await _conf.all_users()
raw_accounts = await _config.all_users()
if guild is not None:
tmp = raw_accounts.copy()
for acc in tmp:
@ -467,7 +467,7 @@ async def get_leaderboard(positions: int = None, guild: discord.Guild = None) ->
else:
if guild is None:
raise TypeError("Expected a guild, got NoneType object instead!")
raw_accounts = await _conf.all_members(guild)
raw_accounts = await _config.all_members(guild)
sorted_acc = sorted(raw_accounts.items(), key=lambda x: x[1]["balance"], reverse=True)
if positions is None:
return sorted_acc
@ -530,9 +530,9 @@ async def get_account(member: Union[discord.Member, discord.User]) -> Account:
"""
if await is_global():
all_accounts = await _conf.all_users()
all_accounts = await _config.all_users()
else:
all_accounts = await _conf.all_members(member.guild)
all_accounts = await _config.all_members(member.guild)
if member.id not in all_accounts:
acc_data = {"name": member.display_name, "created_at": _DEFAULT_MEMBER["created_at"]}
@ -556,7 +556,7 @@ async def is_global() -> bool:
:code:`True` if the bank is global, otherwise :code:`False`.
"""
return await _conf.is_global()
return await _config.is_global()
async def set_global(global_: bool) -> bool:
@ -586,11 +586,11 @@ async def set_global(global_: bool) -> bool:
return global_
if await is_global():
await _conf.clear_all_users()
await _config.clear_all_users()
else:
await _conf.clear_all_members()
await _config.clear_all_members()
await _conf.is_global.set(global_)
await _config.is_global.set(global_)
return global_
@ -615,9 +615,9 @@ async def get_bank_name(guild: discord.Guild = None) -> str:
"""
if await is_global():
return await _conf.bank_name()
return await _config.bank_name()
elif guild is not None:
return await _conf.guild(guild).bank_name()
return await _config.guild(guild).bank_name()
else:
raise RuntimeError("Guild parameter is required and missing.")
@ -645,9 +645,9 @@ async def set_bank_name(name: str, guild: discord.Guild = None) -> str:
"""
if await is_global():
await _conf.bank_name.set(name)
await _config.bank_name.set(name)
elif guild is not None:
await _conf.guild(guild).bank_name.set(name)
await _config.guild(guild).bank_name.set(name)
else:
raise RuntimeError("Guild must be provided if setting the name of a guild-specific bank.")
return name
@ -674,9 +674,9 @@ async def get_currency_name(guild: discord.Guild = None) -> str:
"""
if await is_global():
return await _conf.currency()
return await _config.currency()
elif guild is not None:
return await _conf.guild(guild).currency()
return await _config.guild(guild).currency()
else:
raise RuntimeError("Guild must be provided.")
@ -704,9 +704,9 @@ async def set_currency_name(name: str, guild: discord.Guild = None) -> str:
"""
if await is_global():
await _conf.currency.set(name)
await _config.currency.set(name)
elif guild is not None:
await _conf.guild(guild).currency.set(name)
await _config.guild(guild).currency.set(name)
else:
raise RuntimeError(
"Guild must be provided if setting the currency name of a guild-specific bank."
@ -735,9 +735,9 @@ async def get_max_balance(guild: discord.Guild = None) -> int:
"""
if await is_global():
return await _conf.max_balance()
return await _config.max_balance()
elif guild is not None:
return await _conf.guild(guild).max_balance()
return await _config.guild(guild).max_balance()
else:
raise RuntimeError("Guild must be provided.")
@ -773,9 +773,9 @@ async def set_max_balance(amount: int, guild: discord.Guild = None) -> int:
)
if await is_global():
await _conf.max_balance.set(amount)
await _config.max_balance.set(amount)
elif guild is not None:
await _conf.guild(guild).max_balance.set(amount)
await _config.guild(guild).max_balance.set(amount)
else:
raise RuntimeError(
"Guild must be provided if setting the maximum balance of a guild-specific bank."
@ -804,9 +804,9 @@ async def get_default_balance(guild: discord.Guild = None) -> int:
"""
if await is_global():
return await _conf.default_balance()
return await _config.default_balance()
elif guild is not None:
return await _conf.guild(guild).default_balance()
return await _config.guild(guild).default_balance()
else:
raise RuntimeError("Guild is missing and required!")
@ -846,9 +846,9 @@ async def set_default_balance(amount: int, guild: discord.Guild = None) -> int:
)
if await is_global():
await _conf.default_balance.set(amount)
await _config.default_balance.set(amount)
elif guild is not None:
await _conf.guild(guild).default_balance.set(amount)
await _config.guild(guild).default_balance.set(amount)
else:
raise RuntimeError("Guild is missing and required.")

View File

@ -38,10 +38,10 @@ class CogManager:
CORE_PATH = Path(redbot.cogs.__path__[0])
def __init__(self):
self.conf = Config.get_conf(self, 2938473984732, True)
self.config = Config.get_conf(self, 2938473984732, True)
tmp_cog_install_path = cog_data_path(self) / "cogs"
tmp_cog_install_path.mkdir(parents=True, exist_ok=True)
self.conf.register_global(paths=[], install_path=str(tmp_cog_install_path))
self.config.register_global(paths=[], install_path=str(tmp_cog_install_path))
async def paths(self) -> List[Path]:
"""Get all currently valid path directories, in order of priority
@ -68,7 +68,7 @@ class CogManager:
The path to the directory where 3rd party cogs are stored.
"""
return Path(await self.conf.install_path()).resolve()
return Path(await self.config.install_path()).resolve()
async def user_defined_paths(self) -> List[Path]:
"""Get a list of user-defined cog paths.
@ -81,7 +81,7 @@ class CogManager:
A list of user-defined paths.
"""
return list(map(Path, deduplicate_iterables(await self.conf.paths())))
return list(map(Path, deduplicate_iterables(await self.config.paths())))
async def set_install_path(self, path: Path) -> Path:
"""Set the install path for 3rd party cogs.
@ -110,7 +110,7 @@ class CogManager:
if not path.is_dir():
raise ValueError("The install path must be an existing directory.")
resolved = path.resolve()
await self.conf.install_path.set(str(resolved))
await self.config.install_path.set(str(resolved))
return resolved
@staticmethod
@ -192,7 +192,7 @@ class CogManager:
"""
str_paths = list(map(str, paths_))
await self.conf.paths.set(str_paths)
await self.config.paths.set(str_paths)
async def _find_ext_cog(self, name: str) -> ModuleSpec:
"""

View File

@ -197,11 +197,11 @@ class Value:
-------
::
foo = await conf.guild(some_guild).foo()
foo = await config.guild(some_guild).foo()
# Is equivalent to this
group_obj = conf.guild(some_guild)
group_obj = config.guild(some_guild)
value_obj = group_obj.foo
foo = await value_obj()
@ -241,10 +241,10 @@ class Value:
::
# Sets global value "foo" to False
await conf.foo.set(False)
await config.foo.set(False)
# Sets guild specific value of "bar" to True
await conf.guild(some_guild).bar.set(True)
await config.guild(some_guild).bar.set(True)
Parameters
----------
@ -367,7 +367,7 @@ class Group(Value):
For example::
await conf.clear_raw("foo", "bar")
await config.clear_raw("foo", "bar")
# is equivalent to
@ -430,7 +430,7 @@ class Group(Value):
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).foo())
await ctx.send(await self.config.user(user).get_attr(item).foo())
Parameters
----------
@ -455,7 +455,7 @@ class Group(Value):
For example::
d = await conf.get_raw("foo", "bar")
d = await config.get_raw("foo", "bar")
# is equivalent to
@ -567,7 +567,7 @@ class Group(Value):
For example::
await conf.set_raw("foo", "bar", value="baz")
await config.set_raw("foo", "bar", value="baz")
# is equivalent to
@ -602,7 +602,7 @@ class Config(metaclass=ConfigMeta):
:python:`global` method because global data is accessed by
normal attribute access::
await conf.foo()
await config.foo()
Attributes
----------
@ -821,11 +821,11 @@ class Config(metaclass=ConfigMeta):
--------
You can register a single value or multiple values::
conf.register_global(
config.register_global(
foo=True
)
conf.register_global(
config.register_global(
bar=False,
baz=None
)
@ -840,7 +840,7 @@ class Config(metaclass=ConfigMeta):
}
# Will register `foo.bar` == True and `foo.baz` == False
conf.register_global(
config.register_global(
**_defaults
)
@ -848,7 +848,7 @@ class Config(metaclass=ConfigMeta):
using double underscore as a variable name separator::
# This is equivalent to the previous example
conf.register_global(
config.register_global(
foo__bar=True,
foo__baz=False
)

View File

@ -40,7 +40,7 @@ __all__ = [
"reset_cases",
]
_conf: Optional[Config] = None
_config: Optional[Config] = None
_bot_ref: Optional[Red] = None
_CASETYPES = "CASETYPES"
@ -52,17 +52,17 @@ _ = Translator("ModLog", __file__)
async def _init(bot: Red):
global _conf
global _config
global _bot_ref
_bot_ref = bot
_conf = Config.get_conf(None, 1354799444, cog_name="ModLog")
_conf.register_global(schema_version=1)
_conf.register_guild(mod_log=None, casetypes={}, latest_case_number=0)
_conf.init_custom(_CASETYPES, 1)
_conf.init_custom(_CASES, 2)
_conf.register_custom(_CASETYPES)
_conf.register_custom(_CASES)
await _migrate_config(from_version=await _conf.schema_version(), to_version=_SCHEMA_VERSION)
_config = Config.get_conf(None, 1354799444, cog_name="ModLog")
_config.register_global(schema_version=1)
_config.register_guild(mod_log=None, casetypes={}, latest_case_number=0)
_config.init_custom(_CASETYPES, 1)
_config.init_custom(_CASES, 2)
_config.register_custom(_CASETYPES)
_config.register_custom(_CASES)
await _migrate_config(from_version=await _config.schema_version(), to_version=_SCHEMA_VERSION)
await register_casetypes(all_generics)
async def on_member_ban(guild: discord.Guild, member: discord.Member):
@ -149,9 +149,9 @@ async def handle_auditype_key():
for inner_key, inner_value in casetype_data.items()
if inner_key != "audit_type"
}
for casetype_name, casetype_data in (await _conf.custom(_CASETYPES).all()).items()
for casetype_name, casetype_data in (await _config.custom(_CASETYPES).all()).items()
}
await _conf.custom(_CASETYPES).set(all_casetypes)
await _config.custom(_CASETYPES).set(all_casetypes)
async def _migrate_config(from_version: int, to_version: int):
@ -160,40 +160,42 @@ async def _migrate_config(from_version: int, to_version: int):
if from_version < 2 <= to_version:
# casetypes go from GLOBAL -> casetypes to CASETYPES
all_casetypes = await _conf.get_raw("casetypes", default={})
all_casetypes = await _config.get_raw("casetypes", default={})
if all_casetypes:
await _conf.custom(_CASETYPES).set(all_casetypes)
await _config.custom(_CASETYPES).set(all_casetypes)
# cases go from GUILD -> guild_id -> cases to CASES -> guild_id -> cases
all_guild_data = await _conf.all_guilds()
all_guild_data = await _config.all_guilds()
all_cases = {}
for guild_id, guild_data in all_guild_data.items():
guild_cases = guild_data.pop("cases", None)
if guild_cases:
all_cases[str(guild_id)] = guild_cases
await _conf.custom(_CASES).set(all_cases)
await _config.custom(_CASES).set(all_cases)
# new schema is now in place
await _conf.schema_version.set(2)
await _config.schema_version.set(2)
# migration done, now let's delete all the old stuff
await _conf.clear_raw("casetypes")
await _config.clear_raw("casetypes")
for guild_id in all_guild_data:
await _conf.guild(cast(discord.Guild, discord.Object(id=guild_id))).clear_raw("cases")
await _config.guild(cast(discord.Guild, discord.Object(id=guild_id))).clear_raw(
"cases"
)
if from_version < 3 <= to_version:
await handle_auditype_key()
await _conf.schema_version.set(3)
await _config.schema_version.set(3)
if from_version < 4 <= to_version:
# set latest_case_number
for guild_id, cases in (await _conf.custom(_CASES).all()).items():
for guild_id, cases in (await _config.custom(_CASES).all()).items():
if cases:
await _conf.guild(
await _config.guild(
cast(discord.Guild, discord.Object(id=guild_id))
).latest_case_number.set(max(map(int, cases.keys())))
await _conf.schema_version.set(4)
await _config.schema_version.set(4)
class Case:
@ -253,7 +255,7 @@ class Case:
if not isinstance(self.user, int):
self.last_known_username = f"{self.user.name}#{self.user.discriminator}"
await _conf.custom(_CASES, str(self.guild.id), str(self.case_number)).set(self.to_json())
await _config.custom(_CASES, str(self.guild.id), str(self.case_number)).set(self.to_json())
self.bot.dispatch("modlog_case_edit", self)
if not self.message:
return
@ -538,7 +540,7 @@ class CaseType:
"image": self.image,
"case_str": self.case_str,
}
await _conf.custom(_CASETYPES, self.name).set(data)
await _config.custom(_CASETYPES, self.name).set(data)
async def is_enabled(self) -> bool:
"""
@ -555,7 +557,7 @@ class CaseType:
"""
if not self.guild:
return False
return await _conf.guild(self.guild).casetypes.get_raw(
return await _config.guild(self.guild).casetypes.get_raw(
self.name, default=self.default_setting
)
@ -569,7 +571,7 @@ class CaseType:
True if the case should be enabled, otherwise False"""
if not self.guild:
return
await _conf.guild(self.guild).casetypes.set_raw(self.name, value=enabled)
await _config.guild(self.guild).casetypes.set_raw(self.name, value=enabled)
@classmethod
def from_json(cls, name: str, data: dict, **kwargs):
@ -619,7 +621,7 @@ async def get_case(case_number: int, guild: discord.Guild, bot: Red) -> Case:
"""
case = await _conf.custom(_CASES, str(guild.id), str(case_number)).all()
case = await _config.custom(_CASES, str(guild.id), str(case_number)).all()
if not case:
raise RuntimeError("That case does not exist for guild {}".format(guild.name))
mod_channel = await get_modlog_channel(guild)
@ -642,7 +644,7 @@ async def get_latest_case(guild: discord.Guild, bot: Red) -> Optional[Case]:
The latest case object. `None` if it the guild has no cases.
"""
case_number = await _conf.guild(guild).latest_case_number()
case_number = await _config.guild(guild).latest_case_number()
if case_number:
return await get_case(case_number, guild, bot)
@ -664,7 +666,7 @@ async def get_all_cases(guild: discord.Guild, bot: Red) -> List[Case]:
A list of all cases for the guild
"""
cases = await _conf.custom(_CASES, str(guild.id)).all()
cases = await _config.custom(_CASES, str(guild.id)).all()
mod_channel = await get_modlog_channel(guild)
return [
await Case.from_json(mod_channel, bot, case_number, case_data)
@ -704,7 +706,7 @@ async def get_cases_for_member(
Fetching the user failed.
"""
cases = await _conf.custom(_CASES, str(guild.id)).all()
cases = await _config.custom(_CASES, str(guild.id)).all()
if not (member_id or member):
raise ValueError("Expected a member or a member id to be provided.") from None
@ -776,10 +778,10 @@ async def create_case(
if user == bot.user:
return
async with _conf.guild(guild).latest_case_number.get_lock():
async with _config.guild(guild).latest_case_number.get_lock():
# We're getting the case number from config, incrementing it, awaiting something, then
# setting it again. This warrants acquiring the lock.
next_case_number = await _conf.guild(guild).latest_case_number() + 1
next_case_number = await _config.guild(guild).latest_case_number() + 1
case = Case(
bot,
@ -796,8 +798,8 @@ async def create_case(
modified_at=None,
message=None,
)
await _conf.custom(_CASES, str(guild.id), str(next_case_number)).set(case.to_json())
await _conf.guild(guild).latest_case_number.set(next_case_number)
await _config.custom(_CASES, str(guild.id), str(next_case_number)).set(case.to_json())
await _config.guild(guild).latest_case_number.set(next_case_number)
bot.dispatch("modlog_case_create", case)
try:
@ -831,7 +833,7 @@ async def get_casetype(name: str, guild: Optional[discord.Guild] = None) -> Opti
Optional[CaseType]
Case type with provided name. If such case type doesn't exist this will be `None`.
"""
data = await _conf.custom(_CASETYPES, name).all()
data = await _config.custom(_CASETYPES, name).all()
if not data:
return
casetype = CaseType.from_json(name, data)
@ -851,7 +853,7 @@ async def get_all_casetypes(guild: discord.Guild = None) -> List[CaseType]:
"""
return [
CaseType.from_json(name, data, guild=guild)
for name, data in (await _conf.custom(_CASETYPES).all()).items()
for name, data in (await _config.custom(_CASETYPES).all()).items()
]
@ -985,10 +987,10 @@ async def get_modlog_channel(guild: discord.Guild) -> discord.TextChannel:
"""
if hasattr(guild, "get_channel"):
channel = guild.get_channel(await _conf.guild(guild).mod_log())
channel = guild.get_channel(await _config.guild(guild).mod_log())
else:
# For unit tests only
channel = await _conf.guild(guild).mod_log()
channel = await _config.guild(guild).mod_log()
if channel is None:
raise RuntimeError("Failed to get the mod log channel!")
return channel
@ -1013,7 +1015,7 @@ async def set_modlog_channel(
`True` if successful
"""
await _conf.guild(guild).mod_log.set(channel.id if hasattr(channel, "id") else None)
await _config.guild(guild).mod_log.set(channel.id if hasattr(channel, "id") else None)
return True
@ -1027,8 +1029,8 @@ async def reset_cases(guild: discord.Guild) -> None:
The guild to reset cases for
"""
await _conf.custom(_CASES, str(guild.id)).clear()
await _conf.guild(guild).latest_case_number.clear()
await _config.custom(_CASES, str(guild.id)).clear()
await _config.guild(guild).latest_case_number.clear()
def _strfdelta(delta):