From 33d109228a6daf4d145ce79e3b48c04e5568acf6 Mon Sep 17 00:00:00 2001 From: Arthur Jovart Date: Sat, 28 Aug 2021 20:40:10 +0200 Subject: [PATCH] Add try_user to get a user from cache or from the gateway. --- discord/client.py | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/discord/client.py b/discord/client.py index b6198d10..e8ea5f8e 100644 --- a/discord/client.py +++ b/discord/client.py @@ -827,6 +827,37 @@ class Client: """ return self._connection.get_user(id) + async def try_user(self, id: int, /) -> Optional[User]: + """|coro| + Returns a user with the given ID. If not from cache, the user will be requested from the API. + + You do not have to share any guilds with the user to get this information from the API, + however many operations do require that you do. + + .. note:: + This method is an API call. If you have :attr:`discord.Intents.members` and member cache enabled, consider :meth:`get_user` instead. + + + Parameters + ----------- + id: :class:`int` + The ID to search for. + + Returns + -------- + Optional[:class:`~discord.User`] + The user or ``None`` if not found. + """ + maybe_user = self.get_user(id) + + if maybe_user is not None: + return maybe_user + else: + try: + return await self.fetch_user(id) + except NotFound: + return None + def get_emoji(self, id: int, /) -> Optional[Emoji]: """Returns an emoji with the given ID.