From 2aa089f29c9eab4e4831f5267b0ec087681b9d1e Mon Sep 17 00:00:00 2001 From: Lonami Exo Date: Thu, 20 Dec 2018 20:33:25 +0100 Subject: [PATCH] Prevent KeyError in forward_messages --- telethon/client/messageparse.py | 4 +++- telethon/client/messages.py | 13 ++++++++++++- 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/telethon/client/messageparse.py b/telethon/client/messageparse.py index 15ceba0c..7144f720 100644 --- a/telethon/client/messageparse.py +++ b/telethon/client/messageparse.py @@ -115,7 +115,7 @@ class MessageParseMethods(UserMethods): for x in itertools.chain(result.users, result.chats)} else: - return + return None found = None for update in updates: @@ -141,5 +141,7 @@ class MessageParseMethods(UserMethods): if found: found._finish_init(self, entities, input_chat) return found + else: + return None # explicit is better than implicit # endregion diff --git a/telethon/client/messages.py b/telethon/client/messages.py index f8d07f6c..010e3909 100644 --- a/telethon/client/messages.py +++ b/telethon/client/messages.py @@ -553,6 +553,10 @@ class MessageMethods(UploadMethods, ButtonMethods, MessageParseMethods): Returns: The list of forwarded `telethon.tl.custom.message.Message`, or a single one if a list wasn't provided as input. + + Note that if all messages are invalid (i.e. deleted) the call + will fail with ``MessageIdInvalidError``. If only some are + invalid, the list will have ``None`` instead of those messages. """ single = not utils.is_list_like(messages) if single: @@ -597,7 +601,14 @@ class MessageMethods(UploadMethods, ButtonMethods, MessageParseMethods): update.message._finish_init(self, entities, entity) id_to_message[update.message.id] = update.message - result = [id_to_message[random_to_id[rnd]] for rnd in req.random_id] + # Trying to forward only deleted messages causes `MESSAGE_ID_INVALID` + # but forwarding valid and invalid messages in the same call makes the + # call succeed, although the API won't return those messages thus + # `random_to_id[rnd]` would `KeyError`. Check the key beforehand. + result = [id_to_message[random_to_id[rnd]] + if rnd in random_to_id else None + for rnd in req.random_id] + return result[0] if single else result async def edit_message(