2018-06-13 17:20:15 +03:00
|
|
|
import asyncio
|
2020-05-16 10:58:37 +03:00
|
|
|
import inspect
|
2018-06-14 23:51:57 +03:00
|
|
|
import itertools
|
2018-06-18 14:22:25 +03:00
|
|
|
import random
|
2021-01-30 15:47:28 +03:00
|
|
|
import sys
|
2018-06-18 14:22:25 +03:00
|
|
|
import time
|
2021-01-30 15:47:28 +03:00
|
|
|
import traceback
|
2019-05-03 22:37:27 +03:00
|
|
|
import typing
|
2021-01-30 15:47:28 +03:00
|
|
|
import logging
|
2022-05-13 14:17:16 +03:00
|
|
|
from collections import deque
|
2018-06-10 14:58:21 +03:00
|
|
|
|
2018-06-27 20:40:32 +03:00
|
|
|
from .. import events, utils, errors
|
2019-05-03 22:37:27 +03:00
|
|
|
from ..events.common import EventBuilder, EventCommon
|
2018-06-10 14:58:21 +03:00
|
|
|
from ..tl import types, functions
|
2022-05-23 12:41:59 +03:00
|
|
|
from .._updates import GapError, PrematureEndReason
|
2022-10-02 20:05:11 +03:00
|
|
|
from ..helpers import get_running_loop
|
|
|
|
|
2019-05-03 22:37:27 +03:00
|
|
|
|
|
|
|
if typing.TYPE_CHECKING:
|
|
|
|
from .telegramclient import TelegramClient
|
2018-06-10 14:58:21 +03:00
|
|
|
|
|
|
|
|
2021-08-03 19:33:46 +03:00
|
|
|
Callback = typing.Callable[[typing.Any], typing.Any]
|
|
|
|
|
2019-06-24 18:48:46 +03:00
|
|
|
class UpdateMethods:
|
2018-06-10 14:58:21 +03:00
|
|
|
|
|
|
|
# region Public methods
|
|
|
|
|
2019-05-03 22:37:27 +03:00
|
|
|
async def _run_until_disconnected(self: 'TelegramClient'):
|
2018-06-25 14:32:31 +03:00
|
|
|
try:
|
2019-05-23 13:11:58 +03:00
|
|
|
# Make a high-level request to notify that we want updates
|
|
|
|
await self(functions.updates.GetStateRequest())
|
2022-09-21 13:13:21 +03:00
|
|
|
result = await self.disconnected
|
|
|
|
if self._updates_error is not None:
|
|
|
|
raise self._updates_error
|
|
|
|
return result
|
2018-06-25 14:32:31 +03:00
|
|
|
except KeyboardInterrupt:
|
2019-03-21 14:25:19 +03:00
|
|
|
pass
|
|
|
|
finally:
|
2019-03-21 14:21:00 +03:00
|
|
|
await self.disconnect()
|
2018-06-25 14:32:31 +03:00
|
|
|
|
2021-08-29 12:36:08 +03:00
|
|
|
async def set_receive_updates(self: 'TelegramClient', receive_updates):
|
|
|
|
"""
|
|
|
|
Change the value of `receive_updates`.
|
|
|
|
|
|
|
|
This is an `async` method, because in order for Telegram to start
|
|
|
|
sending updates again, a request must be made.
|
|
|
|
"""
|
|
|
|
self._no_updates = not receive_updates
|
|
|
|
if receive_updates:
|
|
|
|
await self(functions.updates.GetStateRequest())
|
|
|
|
|
2019-05-03 22:37:27 +03:00
|
|
|
def run_until_disconnected(self: 'TelegramClient'):
|
2018-06-17 20:29:41 +03:00
|
|
|
"""
|
2019-05-06 12:38:26 +03:00
|
|
|
Runs the event loop until the library is disconnected.
|
|
|
|
|
2019-05-23 13:11:58 +03:00
|
|
|
It also notifies Telegram that we want to receive updates
|
|
|
|
as described in https://core.telegram.org/api/updates.
|
2022-09-21 13:13:21 +03:00
|
|
|
If an unexpected error occurs during update handling,
|
|
|
|
the client will disconnect and said error will be raised.
|
2019-05-06 12:38:26 +03:00
|
|
|
|
2019-05-23 13:11:58 +03:00
|
|
|
Manual disconnections can be made by calling `disconnect()
|
|
|
|
<telethon.client.telegrambaseclient.TelegramBaseClient.disconnect>`
|
|
|
|
or sending a ``KeyboardInterrupt`` (e.g. by pressing ``Ctrl+C`` on
|
|
|
|
the console window running the script).
|
|
|
|
|
|
|
|
If a disconnection error occurs (i.e. the library fails to reconnect
|
|
|
|
automatically), said error will be raised through here, so you have a
|
|
|
|
chance to ``except`` it on your own code.
|
2018-06-17 20:29:41 +03:00
|
|
|
|
2018-06-25 14:32:31 +03:00
|
|
|
If the loop is already running, this method returns a coroutine
|
|
|
|
that you should await on your own code.
|
2019-05-20 12:38:26 +03:00
|
|
|
|
2019-05-23 13:11:58 +03:00
|
|
|
.. note::
|
|
|
|
|
|
|
|
If you want to handle ``KeyboardInterrupt`` in your code,
|
|
|
|
simply run the event loop in your code too in any way, such as
|
|
|
|
``loop.run_forever()`` or ``await client.disconnected`` (e.g.
|
|
|
|
``loop.run_until_complete(client.disconnected)``).
|
|
|
|
|
2019-05-20 12:38:26 +03:00
|
|
|
Example
|
|
|
|
.. code-block:: python
|
|
|
|
|
|
|
|
# Blocks the current task here until a disconnection occurs.
|
|
|
|
#
|
|
|
|
# You will still receive updates, since this prevents the
|
|
|
|
# script from exiting.
|
2019-08-14 00:33:39 +03:00
|
|
|
await client.run_until_disconnected()
|
2018-06-17 20:29:41 +03:00
|
|
|
"""
|
2018-06-26 16:48:38 +03:00
|
|
|
if self.loop.is_running():
|
|
|
|
return self._run_until_disconnected()
|
|
|
|
try:
|
2019-05-23 13:11:58 +03:00
|
|
|
return self.loop.run_until_complete(self._run_until_disconnected())
|
2018-06-26 16:48:38 +03:00
|
|
|
except KeyboardInterrupt:
|
2019-03-21 14:25:19 +03:00
|
|
|
pass
|
|
|
|
finally:
|
2019-03-22 20:20:02 +03:00
|
|
|
# No loop.run_until_complete; it's already syncified
|
|
|
|
self.disconnect()
|
2018-06-17 20:29:41 +03:00
|
|
|
|
2019-05-03 22:37:27 +03:00
|
|
|
def on(self: 'TelegramClient', event: EventBuilder):
|
2018-06-10 14:58:21 +03:00
|
|
|
"""
|
2019-05-06 12:38:26 +03:00
|
|
|
Decorator used to `add_event_handler` more conveniently.
|
2018-06-20 12:05:33 +03:00
|
|
|
|
2018-06-10 14:58:21 +03:00
|
|
|
|
2019-05-20 12:38:26 +03:00
|
|
|
Arguments
|
2018-06-10 14:58:21 +03:00
|
|
|
event (`_EventBuilder` | `type`):
|
|
|
|
The event builder class or instance to be used,
|
|
|
|
for instance ``events.NewMessage``.
|
2019-05-20 12:38:26 +03:00
|
|
|
|
|
|
|
Example
|
|
|
|
.. code-block:: python
|
|
|
|
|
|
|
|
from telethon import TelegramClient, events
|
|
|
|
client = TelegramClient(...)
|
|
|
|
|
|
|
|
# Here we use client.on
|
|
|
|
@client.on(events.NewMessage)
|
|
|
|
async def handler(event):
|
|
|
|
...
|
2018-06-10 14:58:21 +03:00
|
|
|
"""
|
|
|
|
def decorator(f):
|
|
|
|
self.add_event_handler(f, event)
|
|
|
|
return f
|
|
|
|
|
|
|
|
return decorator
|
|
|
|
|
2019-05-03 22:37:27 +03:00
|
|
|
def add_event_handler(
|
|
|
|
self: 'TelegramClient',
|
2021-08-03 19:33:46 +03:00
|
|
|
callback: Callback,
|
2019-05-03 22:37:27 +03:00
|
|
|
event: EventBuilder = None):
|
2018-06-10 14:58:21 +03:00
|
|
|
"""
|
2019-05-06 12:38:26 +03:00
|
|
|
Registers a new event handler callback.
|
|
|
|
|
|
|
|
The callback will be called when the specified event occurs.
|
2018-06-10 14:58:21 +03:00
|
|
|
|
2019-05-20 12:38:26 +03:00
|
|
|
Arguments
|
2018-06-10 14:58:21 +03:00
|
|
|
callback (`callable`):
|
|
|
|
The callable function accepting one parameter to be used.
|
|
|
|
|
2018-09-22 13:51:58 +03:00
|
|
|
Note that if you have used `telethon.events.register` in
|
|
|
|
the callback, ``event`` will be ignored, and instead the
|
|
|
|
events you previously registered will be used.
|
|
|
|
|
2018-06-10 14:58:21 +03:00
|
|
|
event (`_EventBuilder` | `type`, optional):
|
|
|
|
The event builder class or instance to be used,
|
|
|
|
for instance ``events.NewMessage``.
|
|
|
|
|
|
|
|
If left unspecified, `telethon.events.raw.Raw` (the
|
|
|
|
:tl:`Update` objects with no further processing) will
|
|
|
|
be passed instead.
|
2019-05-20 12:38:26 +03:00
|
|
|
|
|
|
|
Example
|
|
|
|
.. code-block:: python
|
|
|
|
|
|
|
|
from telethon import TelegramClient, events
|
|
|
|
client = TelegramClient(...)
|
|
|
|
|
|
|
|
async def handler(event):
|
|
|
|
...
|
|
|
|
|
|
|
|
client.add_event_handler(handler, events.NewMessage)
|
2018-06-10 14:58:21 +03:00
|
|
|
"""
|
2018-09-22 13:51:58 +03:00
|
|
|
builders = events._get_handlers(callback)
|
|
|
|
if builders is not None:
|
|
|
|
for event in builders:
|
|
|
|
self._event_builders.append((event, callback))
|
|
|
|
return
|
|
|
|
|
2018-06-10 14:58:21 +03:00
|
|
|
if isinstance(event, type):
|
|
|
|
event = event()
|
|
|
|
elif not event:
|
|
|
|
event = events.Raw()
|
|
|
|
|
|
|
|
self._event_builders.append((event, callback))
|
|
|
|
|
2019-05-03 22:37:27 +03:00
|
|
|
def remove_event_handler(
|
|
|
|
self: 'TelegramClient',
|
2021-08-03 19:33:46 +03:00
|
|
|
callback: Callback,
|
2019-05-03 22:37:27 +03:00
|
|
|
event: EventBuilder = None) -> int:
|
2018-06-10 14:58:21 +03:00
|
|
|
"""
|
2019-05-09 13:24:37 +03:00
|
|
|
Inverse operation of `add_event_handler()`.
|
2018-06-10 14:58:21 +03:00
|
|
|
|
|
|
|
If no event is given, all events for this callback are removed.
|
|
|
|
Returns how many callbacks were removed.
|
2019-05-20 12:38:26 +03:00
|
|
|
|
|
|
|
Example
|
|
|
|
.. code-block:: python
|
|
|
|
|
|
|
|
@client.on(events.Raw)
|
|
|
|
@client.on(events.NewMessage)
|
|
|
|
async def handler(event):
|
|
|
|
...
|
|
|
|
|
|
|
|
# Removes only the "Raw" handling
|
|
|
|
# "handler" will still receive "events.NewMessage"
|
|
|
|
client.remove_event_handler(handler, events.Raw)
|
|
|
|
|
|
|
|
# "handler" will stop receiving anything
|
|
|
|
client.remove_event_handler(handler)
|
2018-06-10 14:58:21 +03:00
|
|
|
"""
|
|
|
|
found = 0
|
|
|
|
if event and not isinstance(event, type):
|
|
|
|
event = type(event)
|
|
|
|
|
|
|
|
i = len(self._event_builders)
|
|
|
|
while i:
|
|
|
|
i -= 1
|
|
|
|
ev, cb = self._event_builders[i]
|
|
|
|
if cb == callback and (not event or isinstance(ev, event)):
|
|
|
|
del self._event_builders[i]
|
|
|
|
found += 1
|
|
|
|
|
|
|
|
return found
|
|
|
|
|
2019-05-03 22:37:27 +03:00
|
|
|
def list_event_handlers(self: 'TelegramClient')\
|
2021-08-03 19:33:46 +03:00
|
|
|
-> 'typing.Sequence[typing.Tuple[Callback, EventBuilder]]':
|
2018-06-10 14:58:21 +03:00
|
|
|
"""
|
2019-05-06 12:38:26 +03:00
|
|
|
Lists all registered event handlers.
|
|
|
|
|
2019-05-20 12:38:26 +03:00
|
|
|
Returns
|
|
|
|
A list of pairs consisting of ``(callback, event)``.
|
|
|
|
|
|
|
|
Example
|
|
|
|
.. code-block:: python
|
|
|
|
|
|
|
|
@client.on(events.NewMessage(pattern='hello'))
|
|
|
|
async def on_greeting(event):
|
|
|
|
'''Greets someone'''
|
|
|
|
await event.reply('Hi')
|
|
|
|
|
|
|
|
for callback, event in client.list_event_handlers():
|
|
|
|
print(id(callback), type(event))
|
2018-06-10 14:58:21 +03:00
|
|
|
"""
|
|
|
|
return [(callback, event) for event, callback in self._event_builders]
|
|
|
|
|
2019-05-03 22:37:27 +03:00
|
|
|
async def catch_up(self: 'TelegramClient'):
|
2018-08-14 19:48:56 +03:00
|
|
|
"""
|
|
|
|
"Catches up" on the missed updates while the client was offline.
|
|
|
|
You should call this method after registering the event handlers
|
|
|
|
so that the updates it loads can by processed by your script.
|
|
|
|
|
|
|
|
This can also be used to forcibly fetch new updates if there are any.
|
2019-05-20 12:38:26 +03:00
|
|
|
|
|
|
|
Example
|
|
|
|
.. code-block:: python
|
|
|
|
|
2019-08-14 00:33:39 +03:00
|
|
|
await client.catch_up()
|
2018-08-14 19:48:56 +03:00
|
|
|
"""
|
2022-05-13 14:17:16 +03:00
|
|
|
await self._updates_queue.put(types.UpdatesTooLong())
|
|
|
|
|
|
|
|
# endregion
|
|
|
|
|
|
|
|
# region Private methods
|
2019-05-08 19:15:57 +03:00
|
|
|
|
2022-05-13 14:17:16 +03:00
|
|
|
async def _update_loop(self: 'TelegramClient'):
|
2022-09-21 13:13:21 +03:00
|
|
|
self._updates_error = None
|
2018-06-10 14:58:21 +03:00
|
|
|
try:
|
2022-05-25 16:31:39 +03:00
|
|
|
if self._catch_up:
|
|
|
|
# User wants to catch up as soon as the client is up and running,
|
|
|
|
# so this is the best place to do it.
|
|
|
|
await self.catch_up()
|
|
|
|
|
2022-05-13 14:17:16 +03:00
|
|
|
updates_to_dispatch = deque()
|
|
|
|
|
|
|
|
while self.is_connected():
|
|
|
|
if updates_to_dispatch:
|
|
|
|
if self._sequential_updates:
|
|
|
|
await self._dispatch_update(updates_to_dispatch.popleft())
|
2018-06-10 14:58:21 +03:00
|
|
|
else:
|
2022-05-13 14:17:16 +03:00
|
|
|
while updates_to_dispatch:
|
2022-09-14 17:53:56 +03:00
|
|
|
# TODO if _dispatch_update fails for whatever reason, it's not logged! this should be fixed
|
2022-05-13 14:17:16 +03:00
|
|
|
task = self.loop.create_task(self._dispatch_update(updates_to_dispatch.popleft()))
|
|
|
|
self._event_handler_tasks.add(task)
|
2022-12-15 23:21:58 +03:00
|
|
|
task.add_done_callback(self._event_handler_tasks.discard)
|
2018-06-10 14:58:21 +03:00
|
|
|
|
2022-05-13 14:17:16 +03:00
|
|
|
continue
|
2018-06-10 14:58:21 +03:00
|
|
|
|
2022-05-13 14:17:16 +03:00
|
|
|
get_diff = self._message_box.get_difference()
|
|
|
|
if get_diff:
|
2022-10-02 17:07:14 +03:00
|
|
|
self._log[__name__].debug('Getting difference for account updates')
|
2022-09-20 12:35:59 +03:00
|
|
|
try:
|
|
|
|
diff = await self(get_diff)
|
2022-09-21 13:17:24 +03:00
|
|
|
except (errors.ServerError, ValueError) as e:
|
|
|
|
# Telegram is having issues
|
|
|
|
self._log[__name__].info('Cannot get difference since Telegram is having issues: %s', type(e).__name__)
|
|
|
|
self._message_box.end_difference()
|
|
|
|
continue
|
2022-09-20 12:35:59 +03:00
|
|
|
except (errors.UnauthorizedError, errors.AuthKeyError) as e:
|
|
|
|
# Not logged in or broken authorization key, can't get difference
|
|
|
|
self._log[__name__].info('Cannot get difference since the account is not logged in: %s', type(e).__name__)
|
|
|
|
self._message_box.end_difference()
|
|
|
|
continue
|
2022-10-25 13:28:40 +03:00
|
|
|
except OSError as e:
|
|
|
|
# Network is likely down, but it's unclear for how long.
|
|
|
|
# If disconnect is called this task will be cancelled along with the sleep.
|
|
|
|
# If disconnect is not called, getting difference should be retried after a few seconds.
|
|
|
|
self._log[__name__].info('Cannot get difference since the network is down: %s: %s', type(e).__name__, e)
|
|
|
|
await asyncio.sleep(5)
|
|
|
|
continue
|
2022-05-13 14:17:16 +03:00
|
|
|
updates, users, chats = self._message_box.apply_difference(diff, self._mb_entity_cache)
|
2022-10-02 17:07:14 +03:00
|
|
|
if updates:
|
|
|
|
self._log[__name__].info('Got difference for account updates')
|
|
|
|
|
2022-05-13 18:40:03 +03:00
|
|
|
updates_to_dispatch.extend(self._preprocess_updates(updates, users, chats))
|
2022-05-13 14:17:16 +03:00
|
|
|
continue
|
|
|
|
|
|
|
|
get_diff = self._message_box.get_channel_difference(self._mb_entity_cache)
|
|
|
|
if get_diff:
|
2022-10-02 17:07:14 +03:00
|
|
|
self._log[__name__].debug('Getting difference for channel %s updates', get_diff.channel.channel_id)
|
2022-05-23 12:10:46 +03:00
|
|
|
try:
|
|
|
|
diff = await self(get_diff)
|
2022-09-20 12:35:59 +03:00
|
|
|
except (
|
|
|
|
errors.PersistentTimestampOutdatedError,
|
|
|
|
errors.PersistentTimestampInvalidError,
|
2022-09-21 13:17:24 +03:00
|
|
|
errors.ServerError,
|
2022-09-20 12:35:59 +03:00
|
|
|
errors.UnauthorizedError,
|
|
|
|
errors.AuthKeyError,
|
|
|
|
ValueError
|
|
|
|
) as e:
|
2022-05-23 12:10:46 +03:00
|
|
|
# According to Telegram's docs:
|
|
|
|
# "Channel internal replication issues, try again later (treat this like an RPC_CALL_FAIL)."
|
|
|
|
# We can treat this as "empty difference" and not update the local pts.
|
|
|
|
# Then this same call will be retried when another gap is detected or timeout expires.
|
|
|
|
#
|
|
|
|
# Another option would be to literally treat this like an RPC_CALL_FAIL and retry after a few
|
|
|
|
# seconds, but if Telegram is having issues it's probably best to wait for it to send another
|
|
|
|
# update (hinting it may be okay now) and retry then.
|
|
|
|
#
|
|
|
|
# This is a bit hacky because MessageBox doesn't really have a way to "not update" the pts.
|
|
|
|
# Instead we manually extract the previously-known pts and use that.
|
2022-08-16 13:09:21 +03:00
|
|
|
#
|
|
|
|
# For PersistentTimestampInvalidError:
|
2022-05-23 14:56:10 +03:00
|
|
|
# Somehow our pts is either too new or the server does not know about this.
|
|
|
|
# We treat this as PersistentTimestampOutdatedError for now.
|
|
|
|
# TODO investigate why/when this happens and if this is the proper solution
|
|
|
|
self._log[__name__].warning(
|
2022-09-27 12:31:26 +03:00
|
|
|
'Getting difference for channel updates %s caused %s;'
|
2022-09-20 12:35:59 +03:00
|
|
|
' ending getting difference prematurely until server issues are resolved',
|
2022-09-27 12:31:26 +03:00
|
|
|
get_diff.channel.channel_id, type(e).__name__
|
2022-05-23 14:56:10 +03:00
|
|
|
)
|
|
|
|
self._message_box.end_channel_difference(
|
|
|
|
get_diff,
|
|
|
|
PrematureEndReason.TEMPORARY_SERVER_ISSUES,
|
|
|
|
self._mb_entity_cache
|
|
|
|
)
|
|
|
|
continue
|
2022-08-30 13:06:59 +03:00
|
|
|
except (errors.ChannelPrivateError, errors.ChannelInvalidError):
|
2022-05-23 12:41:59 +03:00
|
|
|
# Timeout triggered a get difference, but we have been banned in the channel since then.
|
|
|
|
# Because we can no longer fetch updates from this channel, we should stop keeping track
|
|
|
|
# of it entirely.
|
|
|
|
self._log[__name__].info(
|
|
|
|
'Account is now banned in %d so we can no longer fetch updates from it',
|
|
|
|
get_diff.channel.channel_id
|
|
|
|
)
|
|
|
|
self._message_box.end_channel_difference(
|
|
|
|
get_diff,
|
|
|
|
PrematureEndReason.BANNED,
|
|
|
|
self._mb_entity_cache
|
|
|
|
)
|
|
|
|
continue
|
2022-10-25 13:28:40 +03:00
|
|
|
except OSError as e:
|
|
|
|
self._log[__name__].info(
|
|
|
|
'Cannot get difference for channel %d since the network is down: %s: %s',
|
|
|
|
get_diff.channel.channel_id, type(e).__name__, e
|
|
|
|
)
|
|
|
|
await asyncio.sleep(5)
|
|
|
|
continue
|
2022-05-23 12:41:59 +03:00
|
|
|
|
2022-05-13 14:17:16 +03:00
|
|
|
updates, users, chats = self._message_box.apply_channel_difference(get_diff, diff, self._mb_entity_cache)
|
2022-10-02 17:07:14 +03:00
|
|
|
if updates:
|
|
|
|
self._log[__name__].info('Got difference for channel %d updates', get_diff.channel.channel_id)
|
|
|
|
|
2022-05-13 18:40:03 +03:00
|
|
|
updates_to_dispatch.extend(self._preprocess_updates(updates, users, chats))
|
2022-05-13 14:17:16 +03:00
|
|
|
continue
|
|
|
|
|
|
|
|
deadline = self._message_box.check_deadlines()
|
2022-10-02 20:05:11 +03:00
|
|
|
deadline_delay = deadline - get_running_loop().time()
|
2022-08-11 11:53:21 +03:00
|
|
|
if deadline_delay > 0:
|
|
|
|
# Don't bother sleeping and timing out if the delay is already 0 (pollutes the logs).
|
|
|
|
try:
|
|
|
|
updates = await asyncio.wait_for(self._updates_queue.get(), deadline_delay)
|
|
|
|
except asyncio.TimeoutError:
|
2022-10-02 17:07:14 +03:00
|
|
|
self._log[__name__].debug('Timeout waiting for updates expired')
|
2022-08-11 11:53:21 +03:00
|
|
|
continue
|
|
|
|
else:
|
2022-05-13 14:17:16 +03:00
|
|
|
continue
|
|
|
|
|
|
|
|
processed = []
|
|
|
|
try:
|
|
|
|
users, chats = self._message_box.process_updates(updates, self._mb_entity_cache, processed)
|
|
|
|
except GapError:
|
|
|
|
continue # get(_channel)_difference will start returning requests
|
|
|
|
|
2022-05-13 18:40:03 +03:00
|
|
|
updates_to_dispatch.extend(self._preprocess_updates(processed, users, chats))
|
2022-09-14 18:11:13 +03:00
|
|
|
except asyncio.CancelledError:
|
|
|
|
pass
|
2022-09-21 13:13:21 +03:00
|
|
|
except Exception as e:
|
2022-05-13 14:17:16 +03:00
|
|
|
self._log[__name__].exception('Fatal error handling updates (this is a bug in Telethon, please report it)')
|
2022-09-21 13:13:21 +03:00
|
|
|
self._updates_error = e
|
|
|
|
await self.disconnect()
|
2018-06-10 14:58:21 +03:00
|
|
|
|
2022-05-13 18:40:03 +03:00
|
|
|
def _preprocess_updates(self, updates, users, chats):
|
2022-05-13 14:17:16 +03:00
|
|
|
self._mb_entity_cache.extend(users, chats)
|
|
|
|
entities = {utils.get_peer_id(x): x
|
|
|
|
for x in itertools.chain(users, chats)}
|
|
|
|
for u in updates:
|
|
|
|
u._entities = entities
|
|
|
|
return updates
|
2018-06-13 17:20:15 +03:00
|
|
|
|
2022-05-13 14:17:16 +03:00
|
|
|
async def _keepalive_loop(self: 'TelegramClient'):
|
2018-06-18 14:22:25 +03:00
|
|
|
# Pings' ID don't really need to be secure, just "random"
|
|
|
|
rnd = lambda: random.randrange(-2**63, 2**63)
|
|
|
|
while self.is_connected():
|
|
|
|
try:
|
2018-06-18 15:27:40 +03:00
|
|
|
await asyncio.wait_for(
|
2020-07-25 19:39:35 +03:00
|
|
|
self.disconnected, timeout=60
|
2018-06-18 15:27:40 +03:00
|
|
|
)
|
2018-06-18 14:22:25 +03:00
|
|
|
continue # We actually just want to act upon timeout
|
|
|
|
except asyncio.TimeoutError:
|
|
|
|
pass
|
2018-07-09 21:54:43 +03:00
|
|
|
except asyncio.CancelledError:
|
|
|
|
return
|
2019-04-01 09:46:07 +03:00
|
|
|
except Exception:
|
2018-06-18 14:22:25 +03:00
|
|
|
continue # Any disconnected exception should be ignored
|
|
|
|
|
2020-04-05 13:34:33 +03:00
|
|
|
# Check if we have any exported senders to clean-up periodically
|
|
|
|
await self._clean_exported_senders()
|
|
|
|
|
2019-12-02 20:32:31 +03:00
|
|
|
# Don't bother sending pings until the low-level connection is
|
|
|
|
# ready, otherwise a lot of pings will be batched to be sent upon
|
|
|
|
# reconnect, when we really don't care about that.
|
|
|
|
if not self._sender._transport_connected():
|
|
|
|
continue
|
|
|
|
|
2018-06-18 14:22:25 +03:00
|
|
|
# We also don't really care about their result.
|
|
|
|
# Just send them periodically.
|
2019-04-01 09:46:07 +03:00
|
|
|
try:
|
2020-12-11 19:18:25 +03:00
|
|
|
self._sender._keepalive_ping(rnd())
|
2019-04-01 09:46:07 +03:00
|
|
|
except (ConnectionError, asyncio.CancelledError):
|
|
|
|
return
|
2018-06-18 14:22:25 +03:00
|
|
|
|
2018-06-24 13:21:58 +03:00
|
|
|
# Entities and cached files are not saved when they are
|
|
|
|
# inserted because this is a rather expensive operation
|
|
|
|
# (default's sqlite3 takes ~0.1s to commit changes). Do
|
|
|
|
# it every minute instead. No-op if there's nothing new.
|
2022-08-30 13:32:21 +03:00
|
|
|
self.session.save()
|
2018-06-24 13:21:58 +03:00
|
|
|
|
2022-05-13 14:17:16 +03:00
|
|
|
async def _dispatch_update(self: 'TelegramClient', update):
|
|
|
|
# TODO only used for AlbumHack, and MessageBox is not really designed for this
|
|
|
|
others = None
|
2019-05-01 15:02:27 +03:00
|
|
|
|
2019-08-07 01:46:19 +03:00
|
|
|
if not self._self_input_peer:
|
|
|
|
# Some updates require our own ID, so we must make sure
|
|
|
|
# that the event builder has offline access to it. Calling
|
|
|
|
# `get_me()` will cache it under `self._self_input_peer`.
|
2020-06-05 22:17:09 +03:00
|
|
|
#
|
|
|
|
# It will return `None` if we haven't logged in yet which is
|
|
|
|
# fine, we will just retry next time anyway.
|
2020-10-11 10:33:05 +03:00
|
|
|
try:
|
|
|
|
await self.get_me(input_peer=True)
|
|
|
|
except OSError:
|
|
|
|
pass # might not have connection
|
2019-08-07 01:46:19 +03:00
|
|
|
|
2019-06-30 17:32:18 +03:00
|
|
|
built = EventBuilderDict(self, update, others)
|
2019-06-03 20:41:22 +03:00
|
|
|
for conv_set in self._conversations.values():
|
|
|
|
for conv in conv_set:
|
2019-04-23 21:15:27 +03:00
|
|
|
ev = built[events.NewMessage]
|
|
|
|
if ev:
|
|
|
|
conv._on_new_message(ev)
|
|
|
|
|
|
|
|
ev = built[events.MessageEdited]
|
|
|
|
if ev:
|
|
|
|
conv._on_edit(ev)
|
|
|
|
|
|
|
|
ev = built[events.MessageRead]
|
|
|
|
if ev:
|
|
|
|
conv._on_read(ev)
|
|
|
|
|
2018-08-05 02:55:41 +03:00
|
|
|
if conv._custom:
|
2019-05-01 18:07:12 +03:00
|
|
|
await conv._check_custom(built)
|
2018-08-05 02:55:41 +03:00
|
|
|
|
2018-06-10 14:58:21 +03:00
|
|
|
for builder, callback in self._event_builders:
|
2019-04-23 21:15:27 +03:00
|
|
|
event = built[type(builder)]
|
2018-08-21 12:08:08 +03:00
|
|
|
if not event:
|
|
|
|
continue
|
|
|
|
|
2018-08-27 02:19:37 +03:00
|
|
|
if not builder.resolved:
|
2018-08-27 11:58:06 +03:00
|
|
|
await builder.resolve(self)
|
2018-08-21 12:08:08 +03:00
|
|
|
|
2020-05-16 10:58:37 +03:00
|
|
|
filter = builder.filter(event)
|
|
|
|
if inspect.isawaitable(filter):
|
|
|
|
filter = await filter
|
|
|
|
if not filter:
|
2018-07-11 12:22:43 +03:00
|
|
|
continue
|
|
|
|
|
|
|
|
try:
|
|
|
|
await callback(event)
|
2018-10-12 23:17:07 +03:00
|
|
|
except errors.AlreadyInConversationError:
|
|
|
|
name = getattr(callback, '__name__', repr(callback))
|
2019-01-11 17:52:30 +03:00
|
|
|
self._log[__name__].debug(
|
|
|
|
'Event handler "%s" already has an open conversation, '
|
|
|
|
'ignoring new one', name)
|
2018-07-11 12:22:43 +03:00
|
|
|
except events.StopPropagation:
|
2018-07-21 18:52:42 +03:00
|
|
|
name = getattr(callback, '__name__', repr(callback))
|
2019-01-11 17:52:30 +03:00
|
|
|
self._log[__name__].debug(
|
2020-06-06 22:01:02 +03:00
|
|
|
'Event handler "%s" stopped chain of propagation '
|
|
|
|
'for event %s.', name, type(event).__name__
|
|
|
|
)
|
|
|
|
break
|
|
|
|
except Exception as e:
|
|
|
|
if not isinstance(e, asyncio.CancelledError) or self.is_connected():
|
|
|
|
name = getattr(callback, '__name__', repr(callback))
|
2021-02-02 22:47:02 +03:00
|
|
|
self._log[__name__].exception('Unhandled exception on %s', name)
|
2020-06-06 22:01:02 +03:00
|
|
|
|
|
|
|
async def _dispatch_event(self: 'TelegramClient', event):
|
|
|
|
"""
|
|
|
|
Dispatches a single, out-of-order event. Used by `AlbumHack`.
|
|
|
|
"""
|
|
|
|
# We're duplicating a most logic from `_dispatch_update`, but all in
|
|
|
|
# the name of speed; we don't want to make it worse for all updates
|
|
|
|
# just because albums may need it.
|
|
|
|
for builder, callback in self._event_builders:
|
2020-09-10 17:25:44 +03:00
|
|
|
if isinstance(builder, events.Raw):
|
|
|
|
continue
|
2020-06-06 22:01:02 +03:00
|
|
|
if not isinstance(event, builder.Event):
|
|
|
|
continue
|
|
|
|
|
|
|
|
if not builder.resolved:
|
|
|
|
await builder.resolve(self)
|
|
|
|
|
|
|
|
filter = builder.filter(event)
|
|
|
|
if inspect.isawaitable(filter):
|
|
|
|
filter = await filter
|
|
|
|
if not filter:
|
|
|
|
continue
|
|
|
|
|
|
|
|
try:
|
|
|
|
await callback(event)
|
|
|
|
except errors.AlreadyInConversationError:
|
|
|
|
name = getattr(callback, '__name__', repr(callback))
|
|
|
|
self._log[__name__].debug(
|
|
|
|
'Event handler "%s" already has an open conversation, '
|
|
|
|
'ignoring new one', name)
|
|
|
|
except events.StopPropagation:
|
|
|
|
name = getattr(callback, '__name__', repr(callback))
|
|
|
|
self._log[__name__].debug(
|
2018-07-21 18:52:42 +03:00
|
|
|
'Event handler "%s" stopped chain of propagation '
|
|
|
|
'for event %s.', name, type(event).__name__
|
2018-07-11 12:22:43 +03:00
|
|
|
)
|
|
|
|
break
|
2019-05-04 22:02:07 +03:00
|
|
|
except Exception as e:
|
|
|
|
if not isinstance(e, asyncio.CancelledError) or self.is_connected():
|
|
|
|
name = getattr(callback, '__name__', repr(callback))
|
2021-02-02 22:47:02 +03:00
|
|
|
self._log[__name__].exception('Unhandled exception on %s', name)
|
2018-06-10 14:58:21 +03:00
|
|
|
|
2019-05-03 22:37:27 +03:00
|
|
|
async def _handle_auto_reconnect(self: 'TelegramClient'):
|
2019-04-22 17:56:32 +03:00
|
|
|
# TODO Catch-up
|
2020-01-04 19:22:53 +03:00
|
|
|
# For now we make a high-level request to let Telegram
|
|
|
|
# know we are still interested in receiving more updates.
|
|
|
|
try:
|
|
|
|
await self.get_me()
|
|
|
|
except Exception as e:
|
|
|
|
self._log[__name__].warning('Error executing high-level request '
|
|
|
|
'after reconnect: %s: %s', type(e), e)
|
|
|
|
|
2019-04-22 17:56:32 +03:00
|
|
|
return
|
2018-06-27 20:40:32 +03:00
|
|
|
try:
|
2019-01-11 17:52:30 +03:00
|
|
|
self._log[__name__].info(
|
|
|
|
'Asking for the current state after reconnect...')
|
2019-03-28 14:32:02 +03:00
|
|
|
|
|
|
|
# TODO consider:
|
|
|
|
# If there aren't many updates while the client is disconnected
|
|
|
|
# (I tried with up to 20), Telegram seems to send them without
|
|
|
|
# asking for them (via updates.getDifference).
|
|
|
|
#
|
|
|
|
# On disconnection, the library should probably set a "need
|
|
|
|
# difference" or "catching up" flag so that any new updates are
|
|
|
|
# ignored, and then the library should call updates.getDifference
|
|
|
|
# itself to fetch them.
|
|
|
|
#
|
|
|
|
# In any case (either there are too many updates and Telegram
|
|
|
|
# didn't send them, or there isn't a lot and Telegram sent them
|
|
|
|
# but we dropped them), we fetch the new difference to get all
|
|
|
|
# missed updates. I feel like this would be the best solution.
|
|
|
|
|
|
|
|
# If a disconnection occurs, the old known state will be
|
|
|
|
# the latest one we were aware of, so we can catch up since
|
|
|
|
# the most recent state we were aware of.
|
|
|
|
await self.catch_up()
|
|
|
|
|
|
|
|
self._log[__name__].info('Successfully fetched missed updates')
|
2018-06-27 20:40:32 +03:00
|
|
|
except errors.RPCError as e:
|
2019-03-28 14:32:02 +03:00
|
|
|
self._log[__name__].warning('Failed to get missed updates after '
|
|
|
|
'reconnect: %r', e)
|
|
|
|
except Exception:
|
2021-02-02 22:47:02 +03:00
|
|
|
self._log[__name__].exception(
|
|
|
|
'Unhandled exception while getting update difference after reconnect')
|
2018-06-27 20:40:32 +03:00
|
|
|
|
2018-06-10 14:58:21 +03:00
|
|
|
# endregion
|
2018-08-21 11:27:12 +03:00
|
|
|
|
|
|
|
|
|
|
|
class EventBuilderDict:
|
|
|
|
"""
|
|
|
|
Helper "dictionary" to return events from types and cache them.
|
|
|
|
"""
|
2019-06-30 17:32:18 +03:00
|
|
|
def __init__(self, client: 'TelegramClient', update, others):
|
2018-08-21 11:27:12 +03:00
|
|
|
self.client = client
|
|
|
|
self.update = update
|
2019-06-30 17:32:18 +03:00
|
|
|
self.others = others
|
2018-08-21 11:27:12 +03:00
|
|
|
|
|
|
|
def __getitem__(self, builder):
|
|
|
|
try:
|
|
|
|
return self.__dict__[builder]
|
|
|
|
except KeyError:
|
2019-08-07 01:46:19 +03:00
|
|
|
event = self.__dict__[builder] = builder.build(
|
2020-10-02 11:23:04 +03:00
|
|
|
self.update, self.others, self.client._self_id)
|
2019-08-07 01:46:19 +03:00
|
|
|
|
2019-03-27 18:21:17 +03:00
|
|
|
if isinstance(event, EventCommon):
|
2018-08-21 11:27:12 +03:00
|
|
|
event.original_update = self.update
|
2019-06-30 14:23:18 +03:00
|
|
|
event._entities = self.update._entities
|
2019-03-27 18:21:17 +03:00
|
|
|
event._set_client(self.client)
|
|
|
|
elif event:
|
|
|
|
event._client = self.client
|
2018-08-21 11:27:12 +03:00
|
|
|
|
|
|
|
return event
|