Let forward_messages work with messages from different chats

Previously it would take the first chat it found and use the IDs
of all messages, even if they belonged to different chats, resulting
in unexpected messages to be forwarded.

Another solution would be to check that all the chats are the same,
but this solves the issue more nicely and makes it more powerful.
This commit is contained in:
Lonami Exo 2019-04-02 10:46:37 +02:00
parent a9ab3e1211
commit 41e4d0f788

View File

@ -644,30 +644,43 @@ class MessageMethods(UploadMethods, ButtonMethods, MessageParseMethods):
if single: if single:
messages = (messages,) messages = (messages,)
if not from_peer: entity = await self.get_input_entity(entity)
try:
# On private chats (to_id = PeerUser), if the message is if from_peer:
# not outgoing, we actually need to use "from_id" to get from_peer = await self.get_input_entity(from_peer)
# the conversation on which the message was sent. from_peer_id = await self.get_peer_id(from_peer)
from_peer = next( else:
m.from_id from_peer_id = None
if not m.out and isinstance(m.to_id, types.PeerUser)
else m.to_id for m in messages def get_key(m):
if isinstance(m, types.Message) if isinstance(m, int):
) if from_peer_id is not None:
except StopIteration: return from_peer_id
raise ValueError(
'from_peer must be given if integer IDs are used' raise ValueError('from_peer must be given if integer IDs are used')
) from None elif isinstance(m, types.Message):
return m.chat_id
else:
raise TypeError('Cannot forward messages of type {}'.format(type(m)))
sent = []
for chat_id, group in itertools.groupby(messages, key=get_key):
group = list(group)
if isinstance(group[0], int):
chat = from_peer
else:
chat = await group[0].get_input_chat()
group = [m.id for m in group]
req = functions.messages.ForwardMessagesRequest( req = functions.messages.ForwardMessagesRequest(
from_peer=from_peer, from_peer=chat,
id=[m if isinstance(m, int) else m.id for m in messages], id=group,
to_peer=entity, to_peer=entity,
silent=silent silent=silent
) )
result = await self(req) result = await self(req)
sent = self._get_response_message(req, result, entity) sent.extend(self._get_response_message(req, result, entity))
return sent[0] if single else sent return sent[0] if single else sent
async def edit_message( async def edit_message(