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
22 changed files with 328 additions and 325 deletions

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