diff options
| author | 2019-12-20 02:30:25 -0300 | |
|---|---|---|
| committer | 2019-12-20 02:30:25 -0300 | |
| commit | 64f2c23f862f78095069f44cc7762ebd1408b31c (patch) | |
| tree | f4da2871c8b66585fda6be385faf082d5154af8e | |
| parent | Give `post_user` default values for `payload` if absent in `user` (diff) | |
Make `FetchedUser` return a `discord.Object` if user *may* exist
The FetchedUser Converter now counts with a `proxy_user` helper function (which
SHOULD NOT be there) to return a user as a last resource, in case
there was an issue fetching from the Discord API, as long as the error
isn't that there's no user with the given ID.
| -rw-r--r-- | bot/converters.py | 42 |
1 files changed, 35 insertions, 7 deletions
diff --git a/bot/converters.py b/bot/converters.py index fbe9ecd90..b33229cc7 100644 --- a/bot/converters.py +++ b/bot/converters.py @@ -281,22 +281,50 @@ class ISODateTime(Converter): class FetchedUser(Converter): - """Fetches from the Discord API and returns a `discord.User` object.""" + """ + 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. + """ + + # 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. + + 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 BadArgument + + user = discord.Object(user_id) + user.mention = user.id + user.avatar_url_as = lambda static_format: None + + return user @staticmethod - async def convert(ctx: Context, user_id: str) -> discord.User: - """Converts `user_id` to a `discord.User` object, after fetching from the Discord API.""" - # TODO: add docstring - # TODO: add remaining exceptions + async def convert(ctx: Context, user_id: str) -> t.Union[discord.User, discord.Object]: + """Convert `user_id` to a `discord.User` object, after fetching from the Discord API.""" try: user_id = int(user_id) user = await ctx.bot.fetch_user(user_id) 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 + # If the Discord error isn't `Unknown user`, save it in the log and return a proxy if e.code != 10013: - log.warning(f"Failed to fetch user:") + log.warning("Failed to fetch user, returning a proxy instead.") + # XXX: + return FetchedUser.proxy_user(user_id) raise BadArgument return user |