diff options
| author | 2019-12-20 23:04:07 -0300 | |
|---|---|---|
| committer | 2019-12-20 23:04:07 -0300 | |
| commit | 3d6113e0eef031f0788a64de46395f3a4af4f921 (patch) | |
| tree | 2fe354abc3063e245243403a02b521201bbb73e9 | |
| parent | Make post_user take default values for payload from `getattr` (diff) | |
Move `utils.proxy_user` to Converters and do minor refactoring
The `proxy_user` function now belongs to the `Converters` module,
since its use is directly related to it. `FetchedUser` uses this
function if there's an error trying to fetch and it doesn't indicate
a non existing user.
Technically finished and working.
| -rw-r--r-- | bot/cogs/moderation/management.py | 4 | ||||
| -rw-r--r-- | bot/cogs/moderation/utils.py | 33 | ||||
| -rw-r--r-- | bot/converters.py | 47 |
3 files changed, 29 insertions, 55 deletions
diff --git a/bot/cogs/moderation/management.py b/bot/cogs/moderation/management.py index 9605d47b2..fff86e9ea 100644 --- a/bot/cogs/moderation/management.py +++ b/bot/cogs/moderation/management.py @@ -10,7 +10,7 @@ from discord.ext.commands import Context from bot import constants from bot.bot import Bot -from bot.converters import InfractionSearchQuery, allowed_strings +from bot.converters import InfractionSearchQuery, allowed_strings, proxy_user from bot.pagination import LinePaginator from bot.utils import time from bot.utils.checks import in_channel_check, with_role_check @@ -20,7 +20,7 @@ from .modlog import ModLog log = logging.getLogger(__name__) -UserConverter = t.Union[discord.User, utils.proxy_user] +UserConverter = t.Union[discord.User, proxy_user] class ModManagement(commands.Cog): diff --git a/bot/cogs/moderation/utils.py b/bot/cogs/moderation/utils.py index 604ce5ce4..5b5aacb16 100644 --- a/bot/cogs/moderation/utils.py +++ b/bot/cogs/moderation/utils.py @@ -4,7 +4,6 @@ import typing as t from datetime import datetime import discord -from discord.ext import commands from discord.ext.commands import Context from bot.api import ResponseCodeError @@ -42,45 +41,23 @@ async def post_user(ctx: Context, user: t.Union[discord.User, discord.Object]) - if not isinstance(user, discord.User): log.warn("The given user is not a discord.User object.") - # XXX: Not sure if these default values are ideal. payload = { 'avatar_hash': getattr(user, 'avatar', 0), 'discriminator': int(getattr(user, 'discriminator', 0)), 'id': user.id, 'in_guild': False, - 'name': getattr(user, 'name', 'No name'), + 'name': getattr(user, 'name', 'Name unknown'), 'roles': [] } try: response = await ctx.bot.api_client.post('bot/users', json=payload) + log.trace(f"User {user.id} added to the DB.") return response except ResponseCodeError as e: - # TODO: Add details, and specific information per possible situation. - # Potential race condition if someone joins and the bot syncs before the API replies! - log.info("Couldn't post user.") - # NOTE: `e.status` is probably not enough for a good message - await ctx.send(f"The attempt to add the user to the DB failed: {e.status}") - - -def proxy_user(user_id: str) -> discord.Object: - """ - Create a proxy user object from the given id. - - Used when a Member or User object cannot be resolved. - """ - log.trace(f"Attempting to create a proxy user for the user id {user_id}.") - - try: - user_id = int(user_id) - except ValueError: - raise commands.BadArgument - - user = discord.Object(user_id) - user.mention = user.id - user.avatar_url_as = lambda static_format: None - - return user + log.warn("Couldn't post user.") + await ctx.send("The attempt to add the user to the DB failed: " + f"{e.status}, {e.response_text if e.response_text else 'no message received'}.") async def post_infraction( diff --git a/bot/converters.py b/bot/converters.py index b33229cc7..28bf58cf4 100644 --- a/bot/converters.py +++ b/bot/converters.py @@ -280,36 +280,34 @@ class ISODateTime(Converter): return dt -class FetchedUser(Converter): +def proxy_user(user_id: str) -> discord.Object: """ - Fetches from the Discord API and returns a `discord.User` or `discord.Object` object, given an ID. + Create a proxy user object from the given id. - If the fetching is successful, a `discord.User` object is returned. If it fails and - the error doesn't imply the user doesn't exist, then a `discord.Object` is returned - via the `user_proxy` function. + Used when a Member or User object cannot be resolved. """ + log.trace(f"Attempting to create a proxy user for the user id {user_id}.") - # XXX: `proxy_user` shouldn't be here as a helper. - # Should wait for PR #651 to import from bot.utils.whatever, maybe? - @staticmethod - def proxy_user(user_id: str) -> discord.Object: - """ - Create a proxy user object from the given id. + try: + user_id = int(user_id) + except ValueError: + raise BadArgument - Used when a Member or User object cannot be resolved. - """ - log.trace(f"Attempting to create a proxy user for the user id {user_id}.") + user = discord.Object(user_id) + user.mention = user.id + user.avatar_url_as = lambda static_format: None - try: - user_id = int(user_id) - except ValueError: - raise BadArgument + return user - user = discord.Object(user_id) - user.mention = user.id - user.avatar_url_as = lambda static_format: None - return user +class FetchedUser(Converter): + """ + Fetches from the Discord API and returns a `discord.User` or `discord.Object` object, given an ID. + + If the fetching is successful, a `discord.User` object is returned. If it fails and + the error doesn't imply the user doesn't exist, then a `discord.Object` is returned + via the `user_proxy` function. + """ @staticmethod async def convert(ctx: Context, user_id: str) -> t.Union[discord.User, discord.Object]: @@ -320,11 +318,10 @@ class FetchedUser(Converter): except ValueError: raise BadArgument(f"The provided argument can't be turned into integer: `{user_id}`") except discord.HTTPException as e: - # If the Discord error isn't `Unknown user`, save it in the log and return a proxy + # If the Discord error isn't `Unknown user`, save it in the log and return a proxy instead if e.code != 10013: log.warning("Failed to fetch user, returning a proxy instead.") - # XXX: - return FetchedUser.proxy_user(user_id) + return proxy_user(user_id) raise BadArgument return user |