Audio converters - Remove all da fetches (#3089)

* Removes `MAX_BALANCE` from bank, user `bank.get_max_balance()` now
`[p]bankset maxbal` can be used to set the maximum bank balance

Signed-off-by: Guy <guyreis96@gmail.com>

* Update Audio Scope converters to respect changes done in #3075
To be merged after #3075

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

* Change logs

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

* Fix Typo

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

* Fix an attribute error when the converter returned None

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

* 🤦

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

* 🤦 2x

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

* Address Aika's review

Signed-off-by: Drapersniper <27962761+drapersniper@users.noreply.github.com>
This commit is contained in:
Draper 2019-12-20 06:55:34 +00:00 committed by Michael H
parent 02bb1fc390
commit 61f467a323
3 changed files with 177 additions and 142 deletions

View File

@ -0,0 +1 @@
Remove API calls from Audio converters.

View File

@ -1,9 +1,11 @@
import argparse import argparse
import functools import functools
import re
from typing import Optional, Tuple, Union from typing import Optional, Tuple, Union
import discord import discord
from redbot.cogs.audio.errors import TooManyMatches, NoMatchesFound
from redbot.core import Config, commands from redbot.core import Config, commands
from redbot.core.bot import Red from redbot.core.bot import Red
from redbot.core.i18n import Translator from redbot.core.i18n import Translator
@ -43,6 +45,8 @@ Guild must be a valid version of one of the following:
Exact guild name Exact guild name
""" """
MENTION_RE = re.compile(r"^<?(?:(?:@[!&]?)?|#)(\d{15,21})>?$")
def _pass_config_to_converters(config: Config, bot: Red): def _pass_config_to_converters(config: Config, bot: Red):
global _config, _bot global _config, _bot
@ -52,6 +56,86 @@ def _pass_config_to_converters(config: Config, bot: Red):
_bot = bot _bot = bot
def _match_id(arg: str) -> Optional[int]:
m = MENTION_RE.match(arg)
if m:
return int(m.group(1))
async def global_unique_guild_finder(ctx: commands.Context, arg: str) -> discord.Guild:
bot: commands.Bot = ctx.bot
_id = _match_id(arg)
if _id is not None:
guild: discord.Guild = bot.get_guild(_id)
if guild is not None:
return guild
maybe_matches = []
for obj in bot.guilds:
if obj.name == arg or str(obj) == arg:
maybe_matches.append(obj)
if not maybe_matches:
raise NoMatchesFound(
_(
'"{arg}" was not found. It must be the ID or '
"complete name of a server which the bot can see."
).format(arg=arg)
)
elif len(maybe_matches) == 1:
return maybe_matches[0]
else:
raise TooManyMatches(
_(
'"{arg}" does not refer to a unique server. '
"Please use the ID for the server you're trying to specify."
).format(arg=arg)
)
async def global_unique_user_finder(
ctx: commands.Context, arg: str, guild: discord.guild = None
) -> discord.abc.User:
bot: commands.Bot = ctx.bot
guild = guild or ctx.guild
_id = _match_id(arg)
if _id is not None:
user: discord.User = bot.get_user(_id)
if user is not None:
return user
objects = bot.users
maybe_matches = []
for obj in objects:
if obj.name == arg or str(obj) == arg:
maybe_matches.append(obj)
if guild is not None:
for member in guild.members:
if member.nick == arg and not any(obj.id == member.id for obj in maybe_matches):
maybe_matches.append(member)
if not maybe_matches:
raise NoMatchesFound(
_(
'"{arg}" was not found. It must be the ID or name or '
"mention a user which the bot can see."
).format(arg=arg)
)
elif len(maybe_matches) == 1:
return maybe_matches[0]
else:
raise TooManyMatches(
_(
'"{arg}" does not refer to a unique server. '
"Please use the ID for the server you're trying to specify."
).format(arg=arg)
)
class PlaylistConverter(commands.Converter): class PlaylistConverter(commands.Converter):
async def convert(self, ctx: commands.Context, arg: str) -> dict: async def convert(self, ctx: commands.Context, arg: str) -> dict:
global_scope = await _config.custom(PlaylistScope.GLOBAL.value).all() global_scope = await _config.custom(PlaylistScope.GLOBAL.value).all()
@ -94,9 +178,10 @@ class ScopeParser(commands.Converter):
async def convert( async def convert(
self, ctx: commands.Context, argument: str self, ctx: commands.Context, argument: str
) -> Tuple[str, discord.User, Optional[discord.Guild], bool]: ) -> Tuple[str, discord.User, Optional[discord.Guild], bool]:
target_scope: str = PlaylistScope.GUILD.value
target_user: Optional[Union[discord.Member, discord.User]] = ctx.author target_scope: Optional[str] = None
target_guild: Optional[discord.Guild] = ctx.guild target_user: Optional[Union[discord.Member, discord.User]] = None
target_guild: Optional[discord.Guild] = None
specified_user = False specified_user = False
argument = argument.replace("", "--") argument = argument.replace("", "--")
@ -108,7 +193,6 @@ class ScopeParser(commands.Converter):
command = None command = None
parser = NoExitParser(description="Playlist Scope Parsing.", add_help=False) parser = NoExitParser(description="Playlist Scope Parsing.", add_help=False)
parser.add_argument("--scope", nargs="*", dest="scope", default=[]) parser.add_argument("--scope", nargs="*", dest="scope", default=[])
parser.add_argument("--guild", nargs="*", dest="guild", default=[]) parser.add_argument("--guild", nargs="*", dest="guild", default=[])
parser.add_argument("--server", nargs="*", dest="guild", default=[]) parser.add_argument("--server", nargs="*", dest="guild", default=[])
@ -145,27 +229,20 @@ class ScopeParser(commands.Converter):
is_owner = await ctx.bot.is_owner(ctx.author) is_owner = await ctx.bot.is_owner(ctx.author)
guild = vals.get("guild", None) or vals.get("server", None) guild = vals.get("guild", None) or vals.get("server", None)
if is_owner and guild: if is_owner and guild:
server_error = ""
target_guild = None target_guild = None
guild_raw = " ".join(guild).strip() guild_raw = " ".join(guild).strip()
if guild_raw.isnumeric():
guild_raw = int(guild_raw)
try: try:
target_guild = ctx.bot.get_guild(guild_raw) target_guild = await global_unique_guild_finder(ctx, guild_raw)
except Exception: except TooManyMatches as err:
target_guild = None server_error = f"{err}\n"
guild_raw = str(guild_raw) except NoMatchesFound as err:
server_error = f"{err}\n"
if target_guild is None: if target_guild is None:
try: raise commands.ArgParserFailure(
target_guild = await commands.GuildConverter.convert(ctx, guild_raw) "--guild", guild_raw, custom_help=f"{server_error}{_GUILD_HELP}"
except Exception: )
target_guild = None
if target_guild is None:
try:
target_guild = await ctx.bot.fetch_guild(guild_raw)
except Exception:
target_guild = None
if target_guild is None:
raise commands.ArgParserFailure("--guild", guild_raw, custom_help=_GUILD_HELP)
elif not is_owner and (guild or any(x in argument for x in ["--guild", "--server"])): elif not is_owner and (guild or any(x in argument for x in ["--guild", "--server"])):
raise commands.BadArgument("You cannot use `--guild`") raise commands.BadArgument("You cannot use `--guild`")
elif any(x in argument for x in ["--guild", "--server"]): elif any(x in argument for x in ["--guild", "--server"]):
@ -173,37 +250,28 @@ class ScopeParser(commands.Converter):
author = vals.get("author", None) or vals.get("user", None) or vals.get("member", None) author = vals.get("author", None) or vals.get("user", None) or vals.get("member", None)
if author: if author:
user_error = ""
target_user = None target_user = None
user_raw = " ".join(author).strip() user_raw = " ".join(author).strip()
if user_raw.isnumeric():
user_raw = int(user_raw)
try: try:
target_user = ctx.bot.get_user(user_raw) target_user = await global_unique_user_finder(ctx, user_raw, guild=target_guild)
except Exception:
target_user = None
user_raw = str(user_raw)
if target_user is None:
member_converter = commands.MemberConverter()
user_converter = commands.UserConverter()
try:
target_user = await member_converter.convert(ctx, user_raw)
except Exception:
try:
target_user = await user_converter.convert(ctx, user_raw)
except Exception:
target_user = None
if target_user is None:
try:
target_user = await ctx.bot.fetch_user(user_raw)
except Exception:
target_user = None
if target_user is None:
raise commands.ArgParserFailure("--author", user_raw, custom_help=_USER_HELP)
else:
specified_user = True specified_user = True
except TooManyMatches as err:
user_error = f"{err}\n"
except NoMatchesFound as err:
user_error = f"{err}\n"
if target_user is None:
raise commands.ArgParserFailure(
"--author", user_raw, custom_help=f"{user_error}{_USER_HELP}"
)
elif any(x in argument for x in ["--author", "--user", "--member"]): elif any(x in argument for x in ["--author", "--user", "--member"]):
raise commands.ArgParserFailure("--scope", "Nothing", custom_help=_USER_HELP) raise commands.ArgParserFailure("--scope", "Nothing", custom_help=_USER_HELP)
target_scope: str = target_scope or PlaylistScope.GUILD.value
target_user: Union[discord.Member, discord.User] = target_user or ctx.author
target_guild: discord.Guild = target_guild or ctx.guild
return target_scope, target_user, target_guild, specified_user return target_scope, target_user, target_guild, specified_user
@ -221,14 +289,14 @@ class ComplexScopeParser(commands.Converter):
bool, bool,
]: ]:
target_scope: str = PlaylistScope.GUILD.value target_scope: Optional[str] = None
target_user: Optional[Union[discord.Member, discord.User]] = ctx.author target_user: Optional[Union[discord.Member, discord.User]] = None
target_guild: Optional[discord.Guild] = ctx.guild target_guild: Optional[discord.Guild] = None
specified_target_user = False specified_target_user = False
source_scope: str = PlaylistScope.GUILD.value source_scope: Optional[str] = None
source_user: Optional[Union[discord.Member, discord.User]] = ctx.author source_user: Optional[Union[discord.Member, discord.User]] = None
source_guild: Optional[discord.Guild] = ctx.guild source_guild: Optional[discord.Guild] = None
specified_source_user = False specified_source_user = False
argument = argument.replace("", "--") argument = argument.replace("", "--")
@ -299,28 +367,18 @@ class ComplexScopeParser(commands.Converter):
to_guild = vals.get("to_guild", None) or vals.get("to_server", None) to_guild = vals.get("to_guild", None) or vals.get("to_server", None)
if is_owner and to_guild: if is_owner and to_guild:
target_server_error = ""
target_guild = None target_guild = None
to_guild_raw = " ".join(to_guild).strip() to_guild_raw = " ".join(to_guild).strip()
if to_guild_raw.isnumeric():
to_guild_raw = int(to_guild_raw)
try: try:
target_guild = ctx.bot.get_guild(to_guild_raw) target_guild = await global_unique_guild_finder(ctx, to_guild_raw)
except Exception: except TooManyMatches as err:
target_guild = None target_server_error = f"{err}\n"
to_guild_raw = str(to_guild_raw) except NoMatchesFound as err:
if target_guild is None: target_server_error = f"{err}\n"
try:
target_guild = await commands.GuildConverter.convert(ctx, to_guild_raw)
except Exception:
target_guild = None
if target_guild is None:
try:
target_guild = await ctx.bot.fetch_guild(to_guild_raw)
except Exception:
target_guild = None
if target_guild is None: if target_guild is None:
raise commands.ArgParserFailure( raise commands.ArgParserFailure(
"--to-guild", to_guild_raw, custom_help=_GUILD_HELP "--to-guild", to_guild_raw, custom_help=f"{target_server_error}{_GUILD_HELP}"
) )
elif not is_owner and ( elif not is_owner and (
to_guild or any(x in argument for x in ["--to-guild", "--to-server"]) to_guild or any(x in argument for x in ["--to-guild", "--to-server"])
@ -331,28 +389,20 @@ class ComplexScopeParser(commands.Converter):
from_guild = vals.get("from_guild", None) or vals.get("from_server", None) from_guild = vals.get("from_guild", None) or vals.get("from_server", None)
if is_owner and from_guild: if is_owner and from_guild:
source_server_error = ""
source_guild = None source_guild = None
from_guild_raw = " ".join(from_guild).strip() from_guild_raw = " ".join(to_guild).strip()
if from_guild_raw.isnumeric():
from_guild_raw = int(from_guild_raw)
try: try:
source_guild = ctx.bot.get_guild(from_guild_raw) source_guild = await global_unique_guild_finder(ctx, from_guild_raw)
except Exception: except TooManyMatches as err:
source_guild = None source_server_error = f"{err}\n"
from_guild_raw = str(from_guild_raw) except NoMatchesFound as err:
if source_guild is None: source_server_error = f"{err}\n"
try:
source_guild = await commands.GuildConverter.convert(ctx, from_guild_raw)
except Exception:
source_guild = None
if source_guild is None:
try:
source_guild = await ctx.bot.fetch_guild(from_guild_raw)
except Exception:
source_guild = None
if source_guild is None: if source_guild is None:
raise commands.ArgParserFailure( raise commands.ArgParserFailure(
"--from-guild", from_guild_raw, custom_help=_GUILD_HELP "--from-guild",
from_guild_raw,
custom_help=f"{source_server_error}{_GUILD_HELP}",
) )
elif not is_owner and ( elif not is_owner and (
from_guild or any(x in argument for x in ["--from-guild", "--from-server"]) from_guild or any(x in argument for x in ["--from-guild", "--from-server"])
@ -365,34 +415,20 @@ class ComplexScopeParser(commands.Converter):
vals.get("to_author", None) or vals.get("to_user", None) or vals.get("to_member", None) vals.get("to_author", None) or vals.get("to_user", None) or vals.get("to_member", None)
) )
if to_author: if to_author:
target_user_error = ""
target_user = None target_user = None
to_user_raw = " ".join(to_author).strip() to_user_raw = " ".join(to_author).strip()
if to_user_raw.isnumeric():
to_user_raw = int(to_user_raw)
try: try:
source_user = ctx.bot.get_user(to_user_raw) target_user = await global_unique_user_finder(ctx, to_user_raw, guild=target_guild)
except Exception:
source_user = None
to_user_raw = str(to_user_raw)
if target_user is None:
member_converter = commands.MemberConverter()
user_converter = commands.UserConverter()
try:
target_user = await member_converter.convert(ctx, to_user_raw)
except Exception:
try:
target_user = await user_converter.convert(ctx, to_user_raw)
except Exception:
target_user = None
if target_user is None:
try:
target_user = await ctx.bot.fetch_user(to_user_raw)
except Exception:
target_user = None
if target_user is None:
raise commands.ArgParserFailure("--to-author", to_user_raw, custom_help=_USER_HELP)
else:
specified_target_user = True specified_target_user = True
except TooManyMatches as err:
target_user_error = f"{err}\n"
except NoMatchesFound as err:
target_user_error = f"{err}\n"
if target_user is None:
raise commands.ArgParserFailure(
"--to-author", to_user_raw, custom_help=f"{target_user_error}{_USER_HELP}"
)
elif any(x in argument for x in ["--to-author", "--to-user", "--to-member"]): elif any(x in argument for x in ["--to-author", "--to-user", "--to-member"]):
raise commands.ArgParserFailure("--to-user", "Nothing", custom_help=_USER_HELP) raise commands.ArgParserFailure("--to-user", "Nothing", custom_help=_USER_HELP)
@ -402,39 +438,33 @@ class ComplexScopeParser(commands.Converter):
or vals.get("from_member", None) or vals.get("from_member", None)
) )
if from_author: if from_author:
source_user_error = ""
source_user = None source_user = None
from_user_raw = " ".join(from_author).strip() from_user_raw = " ".join(to_author).strip()
if from_user_raw.isnumeric():
from_user_raw = int(from_user_raw)
try: try:
target_user = ctx.bot.get_user(from_user_raw) source_user = await global_unique_user_finder(
except Exception: ctx, from_user_raw, guild=target_guild
source_user = None )
from_user_raw = str(from_user_raw) specified_target_user = True
if source_user is None: except TooManyMatches as err:
member_converter = commands.MemberConverter() source_user_error = f"{err}\n"
user_converter = commands.UserConverter() except NoMatchesFound as err:
try: source_user_error = f"{err}\n"
source_user = await member_converter.convert(ctx, from_user_raw)
except Exception:
try:
source_user = await user_converter.convert(ctx, from_user_raw)
except Exception:
source_user = None
if source_user is None:
try:
source_user = await ctx.bot.fetch_user(from_user_raw)
except Exception:
source_user = None
if source_user is None: if source_user is None:
raise commands.ArgParserFailure( raise commands.ArgParserFailure(
"--from-author", from_user_raw, custom_help=_USER_HELP "--from-author", from_user_raw, custom_help=f"{source_user_error}{_USER_HELP}"
) )
else:
specified_source_user = True
elif any(x in argument for x in ["--from-author", "--from-user", "--from-member"]): elif any(x in argument for x in ["--from-author", "--from-user", "--from-member"]):
raise commands.ArgParserFailure("--from-user", "Nothing", custom_help=_USER_HELP) raise commands.ArgParserFailure("--from-user", "Nothing", custom_help=_USER_HELP)
target_scope: str = target_scope or PlaylistScope.GUILD.value
target_user: Union[discord.Member, discord.User] = target_user or ctx.author
target_guild: discord.Guild = target_guild or ctx.guild
source_scope: str = source_scope or PlaylistScope.GUILD.value
source_user: Union[discord.Member, discord.User] = source_user or ctx.author
source_guild: discord.Guild = source_guild or ctx.guild
return ( return (
source_scope, source_scope,
source_user, source_user,

View File

@ -53,6 +53,10 @@ class TooManyMatches(PlayListError):
"""Too many playlist match user input.""" """Too many playlist match user input."""
class NoMatchesFound(PlayListError):
"""No entries found for this input."""
class NotAllowed(PlayListError): class NotAllowed(PlayListError):
"""Too many playlist match user input.""" """Too many playlist match user input."""