2018-06-10 12:30:51 +03:00
|
|
|
import itertools
|
|
|
|
import re
|
2019-05-03 22:37:27 +03:00
|
|
|
import typing
|
2018-06-10 12:30:51 +03:00
|
|
|
|
2019-12-23 15:52:07 +03:00
|
|
|
from .. import helpers, utils
|
2018-10-05 15:20:50 +03:00
|
|
|
from ..tl import types
|
2018-06-10 12:30:51 +03:00
|
|
|
|
2019-05-03 22:37:27 +03:00
|
|
|
if typing.TYPE_CHECKING:
|
|
|
|
from .telegramclient import TelegramClient
|
|
|
|
|
2018-06-10 12:30:51 +03:00
|
|
|
|
2019-06-24 18:48:46 +03:00
|
|
|
class MessageParseMethods:
|
2018-06-10 12:30:51 +03:00
|
|
|
|
|
|
|
# region Public properties
|
|
|
|
|
|
|
|
@property
|
2019-05-03 22:37:27 +03:00
|
|
|
def parse_mode(self: 'TelegramClient'):
|
2018-06-10 12:30:51 +03:00
|
|
|
"""
|
|
|
|
This property is the default parse mode used when sending messages.
|
|
|
|
Defaults to `telethon.extensions.markdown`. It will always
|
2019-07-06 13:10:25 +03:00
|
|
|
be either `None` or an object with ``parse`` and ``unparse``
|
2018-06-10 12:30:51 +03:00
|
|
|
methods.
|
|
|
|
|
|
|
|
When setting a different value it should be one of:
|
|
|
|
|
|
|
|
* Object with ``parse`` and ``unparse`` methods.
|
|
|
|
* A ``callable`` to act as the parse method.
|
2019-07-06 13:10:25 +03:00
|
|
|
* A `str` indicating the ``parse_mode``. For Markdown ``'md'``
|
2018-06-10 12:30:51 +03:00
|
|
|
or ``'markdown'`` may be used. For HTML, ``'htm'`` or ``'html'``
|
|
|
|
may be used.
|
|
|
|
|
|
|
|
The ``parse`` method should be a function accepting a single
|
|
|
|
parameter, the text to parse, and returning a tuple consisting
|
|
|
|
of ``(parsed message str, [MessageEntity instances])``.
|
|
|
|
|
|
|
|
The ``unparse`` method should be the inverse of ``parse`` such
|
|
|
|
that ``assert text == unparse(*parse(text))``.
|
|
|
|
|
|
|
|
See :tl:`MessageEntity` for allowed message entities.
|
2019-05-20 12:38:26 +03:00
|
|
|
|
|
|
|
Example
|
|
|
|
.. code-block:: python
|
|
|
|
|
|
|
|
# Disabling default formatting
|
|
|
|
client.parse_mode = None
|
|
|
|
|
|
|
|
# Enabling HTML as the default format
|
|
|
|
client.parse_mode = 'html'
|
2018-06-10 12:30:51 +03:00
|
|
|
"""
|
|
|
|
return self._parse_mode
|
|
|
|
|
|
|
|
@parse_mode.setter
|
2019-05-03 22:37:27 +03:00
|
|
|
def parse_mode(self: 'TelegramClient', mode: str):
|
2018-06-10 12:30:51 +03:00
|
|
|
self._parse_mode = utils.sanitize_parse_mode(mode)
|
|
|
|
|
|
|
|
# endregion
|
|
|
|
|
|
|
|
# region Private methods
|
|
|
|
|
2019-05-03 22:37:27 +03:00
|
|
|
async def _replace_with_mention(self: 'TelegramClient', entities, i, user):
|
2018-06-22 17:18:23 +03:00
|
|
|
"""
|
|
|
|
Helper method to replace ``entities[i]`` to mention ``user``,
|
|
|
|
or do nothing if it can't be found.
|
|
|
|
"""
|
|
|
|
try:
|
|
|
|
entities[i] = types.InputMessageEntityMentionName(
|
|
|
|
entities[i].offset, entities[i].length,
|
|
|
|
await self.get_input_entity(user)
|
|
|
|
)
|
2018-11-24 21:39:05 +03:00
|
|
|
return True
|
2018-06-22 17:18:23 +03:00
|
|
|
except (ValueError, TypeError):
|
2018-11-24 21:39:05 +03:00
|
|
|
return False
|
2018-06-22 17:18:23 +03:00
|
|
|
|
2019-05-03 22:37:27 +03:00
|
|
|
async def _parse_message_text(self: 'TelegramClient', message, parse_mode):
|
2018-06-10 12:30:51 +03:00
|
|
|
"""
|
|
|
|
Returns a (parsed message, entities) tuple depending on ``parse_mode``.
|
|
|
|
"""
|
2019-12-05 13:14:02 +03:00
|
|
|
if parse_mode == ():
|
2018-06-10 12:30:51 +03:00
|
|
|
parse_mode = self._parse_mode
|
|
|
|
else:
|
|
|
|
parse_mode = utils.sanitize_parse_mode(parse_mode)
|
|
|
|
|
|
|
|
if not parse_mode:
|
|
|
|
return message, []
|
|
|
|
|
|
|
|
message, msg_entities = parse_mode.parse(message)
|
2018-11-24 21:39:05 +03:00
|
|
|
for i in reversed(range(len(msg_entities))):
|
|
|
|
e = msg_entities[i]
|
2018-06-10 12:30:51 +03:00
|
|
|
if isinstance(e, types.MessageEntityTextUrl):
|
|
|
|
m = re.match(r'^@|\+|tg://user\?id=(\d+)', e.url)
|
|
|
|
if m:
|
2018-06-22 17:18:23 +03:00
|
|
|
user = int(m.group(1)) if m.group(1) else e.url
|
2018-11-24 21:39:05 +03:00
|
|
|
is_mention = await self._replace_with_mention(msg_entities, i, user)
|
|
|
|
if not is_mention:
|
|
|
|
del msg_entities[i]
|
2018-06-22 17:18:23 +03:00
|
|
|
elif isinstance(e, (types.MessageEntityMentionName,
|
|
|
|
types.InputMessageEntityMentionName)):
|
2018-11-24 21:39:05 +03:00
|
|
|
is_mention = await self._replace_with_mention(msg_entities, i, e.user_id)
|
|
|
|
if not is_mention:
|
|
|
|
del msg_entities[i]
|
2018-06-10 12:30:51 +03:00
|
|
|
|
|
|
|
return message, msg_entities
|
|
|
|
|
2019-05-03 22:37:27 +03:00
|
|
|
def _get_response_message(self: 'TelegramClient', request, result, input_chat):
|
2018-06-10 12:30:51 +03:00
|
|
|
"""
|
|
|
|
Extracts the response message known a request and Update result.
|
|
|
|
The request may also be the ID of the message to match.
|
|
|
|
|
2019-04-09 15:55:33 +03:00
|
|
|
If ``request is None`` this method returns ``{id: message}``.
|
|
|
|
|
2019-04-02 11:44:42 +03:00
|
|
|
If ``request.random_id`` is a list, this method returns a list too.
|
|
|
|
"""
|
2018-06-10 12:30:51 +03:00
|
|
|
if isinstance(result, types.UpdateShort):
|
|
|
|
updates = [result.update]
|
|
|
|
entities = {}
|
|
|
|
elif isinstance(result, (types.Updates, types.UpdatesCombined)):
|
|
|
|
updates = result.updates
|
|
|
|
entities = {utils.get_peer_id(x): x
|
|
|
|
for x in
|
|
|
|
itertools.chain(result.users, result.chats)}
|
|
|
|
else:
|
2018-12-20 22:33:25 +03:00
|
|
|
return None
|
2018-06-10 12:30:51 +03:00
|
|
|
|
2019-04-02 11:44:42 +03:00
|
|
|
random_to_id = {}
|
|
|
|
id_to_message = {}
|
2019-09-06 14:45:31 +03:00
|
|
|
sched_to_message = {} # scheduled IDs may collide with normal IDs
|
2018-06-10 12:30:51 +03:00
|
|
|
for update in updates:
|
2019-04-02 11:44:42 +03:00
|
|
|
if isinstance(update, types.UpdateMessageID):
|
|
|
|
random_to_id[update.random_id] = update.id
|
|
|
|
|
|
|
|
elif isinstance(update, (
|
2018-06-10 12:30:51 +03:00
|
|
|
types.UpdateNewChannelMessage, types.UpdateNewMessage)):
|
2019-04-02 11:44:42 +03:00
|
|
|
update.message._finish_init(self, entities, input_chat)
|
|
|
|
id_to_message[update.message.id] = update.message
|
2018-06-10 12:30:51 +03:00
|
|
|
|
|
|
|
elif (isinstance(update, types.UpdateEditMessage)
|
2019-12-23 15:52:07 +03:00
|
|
|
and helpers._entity_type(request.peer) != helpers._EntityType.CHANNEL):
|
2018-06-10 12:30:51 +03:00
|
|
|
if request.id == update.message.id:
|
2019-04-02 11:44:42 +03:00
|
|
|
update.message._finish_init(self, entities, input_chat)
|
|
|
|
return update.message
|
2018-06-10 12:30:51 +03:00
|
|
|
|
|
|
|
elif (isinstance(update, types.UpdateEditChannelMessage)
|
|
|
|
and utils.get_peer_id(request.peer) ==
|
2019-04-02 11:44:42 +03:00
|
|
|
utils.get_peer_id(update.message.to_id)):
|
2018-06-10 12:30:51 +03:00
|
|
|
if request.id == update.message.id:
|
2019-04-02 11:44:42 +03:00
|
|
|
update.message._finish_init(self, entities, input_chat)
|
|
|
|
return update.message
|
|
|
|
|
2019-09-06 14:45:31 +03:00
|
|
|
elif isinstance(update, types.UpdateNewScheduledMessage):
|
|
|
|
update.message._finish_init(self, entities, input_chat)
|
|
|
|
sched_to_message[update.message.id] = update.message
|
|
|
|
|
2019-12-27 00:00:41 +03:00
|
|
|
elif isinstance(update, types.UpdateMessagePoll):
|
|
|
|
if request.media.poll.id == update.poll_id:
|
|
|
|
m = types.Message(
|
|
|
|
id=request.id,
|
|
|
|
to_id=utils.get_peer(request.peer),
|
|
|
|
media=types.MessageMediaPoll(
|
|
|
|
poll=update.poll,
|
|
|
|
results=update.results
|
|
|
|
)
|
|
|
|
)
|
|
|
|
m._finish_init(self, entities, input_chat)
|
|
|
|
return m
|
|
|
|
|
2019-04-09 15:55:33 +03:00
|
|
|
if request is None:
|
|
|
|
return id_to_message
|
|
|
|
|
2019-09-06 14:45:31 +03:00
|
|
|
# Use the scheduled mapping if we got a request with a scheduled message
|
|
|
|
#
|
|
|
|
# This breaks if the schedule date is too young, however, since the message
|
|
|
|
# is sent immediately, so have a fallback.
|
|
|
|
if getattr(request, 'schedule_date', None) is None:
|
|
|
|
mapping = id_to_message
|
|
|
|
opposite = {} # if there's no schedule it can never be scheduled
|
|
|
|
else:
|
|
|
|
mapping = sched_to_message
|
|
|
|
opposite = id_to_message # scheduled may be treated as normal, though
|
|
|
|
|
2019-11-10 16:56:28 +03:00
|
|
|
random_id = request if isinstance(request, (int, list)) else request.random_id
|
2019-04-09 15:31:50 +03:00
|
|
|
if not utils.is_list_like(random_id):
|
2019-09-06 14:45:31 +03:00
|
|
|
msg = mapping.get(random_to_id.get(random_id))
|
|
|
|
if not msg:
|
|
|
|
msg = opposite.get(random_to_id.get(random_id))
|
|
|
|
|
2019-05-17 13:18:31 +03:00
|
|
|
if not msg:
|
|
|
|
self._log[__name__].warning(
|
|
|
|
'Request %s had missing message mapping %s', request, result)
|
|
|
|
|
|
|
|
return msg
|
|
|
|
|
|
|
|
try:
|
2019-09-06 14:45:31 +03:00
|
|
|
return [mapping[random_to_id[rnd]] for rnd in random_id]
|
2019-05-17 13:18:31 +03:00
|
|
|
except KeyError:
|
2019-09-06 14:45:31 +03:00
|
|
|
try:
|
|
|
|
return [opposite[random_to_id[rnd]] for rnd in random_id]
|
|
|
|
except KeyError:
|
|
|
|
# Sometimes forwards fail (`MESSAGE_ID_INVALID` if a message gets
|
|
|
|
# deleted or `WORKER_BUSY_TOO_LONG_RETRY` if there are issues at
|
|
|
|
# Telegram), in which case we get some "missing" message mappings.
|
|
|
|
# Log them with the hope that we can better work around them.
|
|
|
|
self._log[__name__].warning(
|
|
|
|
'Request %s had missing message mappings %s', request, result)
|
|
|
|
|
|
|
|
return [
|
|
|
|
mapping.get(random_to_id.get(rnd))
|
|
|
|
or opposite.get(random_to_id.get(rnd))
|
|
|
|
for rnd in random_to_id
|
|
|
|
]
|
2018-06-10 12:30:51 +03:00
|
|
|
|
|
|
|
# endregion
|