aboutsummaryrefslogtreecommitdiffstats
path: root/bot/converters.py
diff options
context:
space:
mode:
Diffstat (limited to 'bot/converters.py')
-rw-r--r--bot/converters.py47
1 files changed, 47 insertions, 0 deletions
diff --git a/bot/converters.py b/bot/converters.py
index 8d2ab7eb8..28bf58cf4 100644
--- a/bot/converters.py
+++ b/bot/converters.py
@@ -278,3 +278,50 @@ class ISODateTime(Converter):
dt = dt.replace(tzinfo=None)
return dt
+
+
+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
+
+
+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]:
+ """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 and return a proxy instead
+ if e.code != 10013:
+ log.warning("Failed to fetch user, returning a proxy instead.")
+ return proxy_user(user_id)
+ raise BadArgument
+
+ return user