From 5ca1edb228989f30fd0cbacc7cbd6e7ead4cac17 Mon Sep 17 00:00:00 2001 From: Lonami Exo Date: Sun, 26 Aug 2018 12:00:17 +0200 Subject: [PATCH] Return the correct entity from .get_entity(username) The precedence of the or operator made the check succeed always out of pure luck, since `''.lower()` would never be the chosen username, but a present username is truthy. This presumably worked because Telegram only returns one result from the call, or puts the right entity the first one. --- telethon/client/users.py | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/telethon/client/users.py b/telethon/client/users.py index 2120fde2..757fa7f9 100644 --- a/telethon/client/users.py +++ b/telethon/client/users.py @@ -381,10 +381,14 @@ class UserMethods(TelegramBaseClient): raise ValueError('No user has "{}" as username' .format(username)) from e - for entity in itertools.chain(result.users, result.chats): - if getattr(entity, 'username', None) or '' \ - .lower() == username: - return entity + try: + pid = utils.get_peer_id(result.peer, add_mark=False) + if isinstance(result.peer, types.PeerUser): + return next(x for x in result.users if x.id == pid) + else: + return next(x for x in result.chats if x.id == pid) + except StopIteration: + pass try: # Nobody with this username, maybe it's an exact name/title return await self.get_entity(