2018-06-13 17:20:15 +03:00
|
|
|
import asyncio
|
2018-06-14 23:51:57 +03:00
|
|
|
import itertools
|
2018-06-18 14:22:25 +03:00
|
|
|
import random
|
|
|
|
import time
|
2018-06-10 14:58:21 +03:00
|
|
|
|
|
|
|
from .users import UserMethods
|
2018-06-27 20:40:32 +03:00
|
|
|
from .. import events, utils, errors
|
2018-06-10 14:58:21 +03:00
|
|
|
from ..tl import types, functions
|
|
|
|
|
|
|
|
|
|
|
|
class UpdateMethods(UserMethods):
|
|
|
|
|
|
|
|
# region Public methods
|
|
|
|
|
2018-06-25 14:32:31 +03:00
|
|
|
async def _run_until_disconnected(self):
|
|
|
|
try:
|
|
|
|
await self.disconnected
|
|
|
|
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
|
|
|
|
2018-06-17 20:29:41 +03:00
|
|
|
def run_until_disconnected(self):
|
|
|
|
"""
|
|
|
|
Runs the event loop until `disconnect` is called or if an error
|
|
|
|
while connecting/sending/receiving occurs in the background. In
|
|
|
|
the latter case, said error will ``raise`` so you have a chance
|
|
|
|
to ``except`` it on your own code.
|
|
|
|
|
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.
|
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:
|
|
|
|
return self.loop.run_until_complete(self.disconnected)
|
|
|
|
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
|
|
|
|
2018-06-10 14:58:21 +03:00
|
|
|
def on(self, event):
|
|
|
|
"""
|
2018-06-20 12:05:33 +03:00
|
|
|
Decorator helper method around `add_event_handler`. Example:
|
|
|
|
|
|
|
|
>>> from telethon import TelegramClient, events
|
|
|
|
>>> client = TelegramClient(...)
|
|
|
|
>>>
|
|
|
|
>>> @client.on(events.NewMessage)
|
|
|
|
... async def handler(event):
|
|
|
|
... ...
|
|
|
|
...
|
|
|
|
>>>
|
2018-06-10 14:58:21 +03:00
|
|
|
|
|
|
|
Args:
|
|
|
|
event (`_EventBuilder` | `type`):
|
|
|
|
The event builder class or instance to be used,
|
|
|
|
for instance ``events.NewMessage``.
|
|
|
|
"""
|
|
|
|
def decorator(f):
|
|
|
|
self.add_event_handler(f, event)
|
|
|
|
return f
|
|
|
|
|
|
|
|
return decorator
|
|
|
|
|
|
|
|
def add_event_handler(self, callback, event=None):
|
|
|
|
"""
|
|
|
|
Registers the given callback to be called on the specified event.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
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.
|
|
|
|
"""
|
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))
|
|
|
|
|
|
|
|
def remove_event_handler(self, callback, event=None):
|
|
|
|
"""
|
|
|
|
Inverse operation of :meth:`add_event_handler`.
|
|
|
|
|
|
|
|
If no event is given, all events for this callback are removed.
|
|
|
|
Returns how many callbacks were removed.
|
|
|
|
"""
|
|
|
|
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
|
|
|
|
|
|
|
|
def list_event_handlers(self):
|
|
|
|
"""
|
|
|
|
Lists all added event handlers, returning a list of pairs
|
|
|
|
consisting of (callback, event).
|
|
|
|
"""
|
|
|
|
return [(callback, event) for event, callback in self._event_builders]
|
|
|
|
|
|
|
|
async def catch_up(self):
|
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.
|
|
|
|
"""
|
2018-12-06 18:07:11 +03:00
|
|
|
state = self._state
|
|
|
|
if state.pts == 0:
|
|
|
|
# pts = 0 is invalid, pts = 1 will catch up since the beginning
|
|
|
|
state.pts = 1
|
2018-06-10 14:58:21 +03:00
|
|
|
|
|
|
|
self.session.catching_up = True
|
|
|
|
try:
|
|
|
|
while True:
|
|
|
|
d = await self(functions.updates.GetDifferenceRequest(
|
2018-08-13 13:32:12 +03:00
|
|
|
state.pts, state.date, state.qts
|
|
|
|
))
|
|
|
|
if isinstance(d, (types.updates.DifferenceSlice,
|
|
|
|
types.updates.Difference)):
|
2018-06-10 14:58:21 +03:00
|
|
|
if isinstance(d, types.updates.Difference):
|
|
|
|
state = d.state
|
|
|
|
else:
|
2018-08-13 13:32:12 +03:00
|
|
|
state = d.intermediate_state
|
2018-06-10 14:58:21 +03:00
|
|
|
|
2018-10-06 13:39:07 +03:00
|
|
|
await self._handle_update(types.Updates(
|
2018-06-10 14:58:21 +03:00
|
|
|
users=d.users,
|
|
|
|
chats=d.chats,
|
|
|
|
date=state.date,
|
|
|
|
seq=state.seq,
|
|
|
|
updates=d.other_updates + [
|
|
|
|
types.UpdateNewMessage(m, 0, 0)
|
|
|
|
for m in d.new_messages
|
|
|
|
]
|
|
|
|
))
|
2018-08-13 13:32:12 +03:00
|
|
|
else:
|
|
|
|
if isinstance(d, types.updates.DifferenceEmpty):
|
|
|
|
state.date = d.date
|
|
|
|
state.seq = d.seq
|
|
|
|
elif isinstance(d, types.updates.DifferenceTooLong):
|
|
|
|
state.pts = d.pts
|
2018-06-10 14:58:21 +03:00
|
|
|
break
|
|
|
|
finally:
|
2018-12-06 18:07:11 +03:00
|
|
|
self._state = state
|
2018-10-12 23:00:02 +03:00
|
|
|
self.session.set_update_state(0, state)
|
2018-06-10 14:58:21 +03:00
|
|
|
self.session.catching_up = False
|
|
|
|
|
|
|
|
# endregion
|
|
|
|
|
|
|
|
# region Private methods
|
|
|
|
|
2018-10-05 21:25:49 +03:00
|
|
|
async def _handle_update(self, update):
|
2018-10-12 23:00:02 +03:00
|
|
|
self.session.process_entities(update)
|
2018-06-14 23:51:57 +03:00
|
|
|
if isinstance(update, (types.Updates, types.UpdatesCombined)):
|
|
|
|
entities = {utils.get_peer_id(x): x for x in
|
|
|
|
itertools.chain(update.users, update.chats)}
|
|
|
|
for u in update.updates:
|
|
|
|
u._entities = entities
|
2018-10-06 13:39:07 +03:00
|
|
|
await self._handle_update(u)
|
2018-07-12 10:45:29 +03:00
|
|
|
elif isinstance(update, types.UpdateShort):
|
2018-10-06 13:39:07 +03:00
|
|
|
await self._handle_update(update.update)
|
2018-06-20 20:48:00 +03:00
|
|
|
else:
|
|
|
|
update._entities = getattr(update, '_entities', {})
|
2018-06-29 11:45:04 +03:00
|
|
|
if self._updates_queue is None:
|
|
|
|
self._loop.create_task(self._dispatch_update(update))
|
|
|
|
else:
|
|
|
|
self._updates_queue.put_nowait(update)
|
|
|
|
if not self._dispatching_updates_queue.is_set():
|
|
|
|
self._dispatching_updates_queue.set()
|
|
|
|
self._loop.create_task(self._dispatch_queue_updates())
|
2018-06-20 20:48:00 +03:00
|
|
|
|
|
|
|
need_diff = False
|
2018-07-10 17:59:40 +03:00
|
|
|
if hasattr(update, 'pts') and update.pts is not None:
|
2018-06-20 20:48:00 +03:00
|
|
|
if self._state.pts and (update.pts - self._state.pts) > 1:
|
|
|
|
need_diff = True
|
|
|
|
self._state.pts = update.pts
|
|
|
|
if hasattr(update, 'date'):
|
|
|
|
self._state.date = update.date
|
|
|
|
if hasattr(update, 'seq'):
|
|
|
|
self._state.seq = update.seq
|
|
|
|
|
|
|
|
# TODO make use of need_diff
|
2018-06-13 17:20:15 +03:00
|
|
|
|
2018-06-18 14:22:25 +03:00
|
|
|
async def _update_loop(self):
|
|
|
|
# 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(
|
2018-06-18 16:55:24 +03:00
|
|
|
self.disconnected, timeout=60, loop=self._loop
|
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
|
|
|
|
except Exception as e:
|
2018-06-18 14:22:25 +03:00
|
|
|
continue # Any disconnected exception should be ignored
|
|
|
|
|
|
|
|
# We also don't really care about their result.
|
|
|
|
# Just send them periodically.
|
|
|
|
self._sender.send(functions.PingRequest(rnd()))
|
|
|
|
|
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.
|
2018-10-12 23:00:02 +03:00
|
|
|
self.session.save()
|
2018-06-24 13:21:58 +03:00
|
|
|
|
2018-06-18 14:22:25 +03:00
|
|
|
# We need to send some content-related request at least hourly
|
|
|
|
# for Telegram to keep delivering updates, otherwise they will
|
|
|
|
# just stop even if we're connected. Do so every 30 minutes.
|
|
|
|
#
|
|
|
|
# TODO Call getDifference instead since it's more relevant
|
|
|
|
if time.time() - self._last_request > 30 * 60:
|
|
|
|
if not await self.is_user_authorized():
|
|
|
|
# What can be the user doing for so
|
|
|
|
# long without being logged in...?
|
|
|
|
continue
|
|
|
|
|
|
|
|
await self(functions.updates.GetStateRequest())
|
|
|
|
|
2018-06-29 11:45:04 +03:00
|
|
|
async def _dispatch_queue_updates(self):
|
|
|
|
while not self._updates_queue.empty():
|
|
|
|
await self._dispatch_update(self._updates_queue.get_nowait())
|
|
|
|
|
|
|
|
self._dispatching_updates_queue.clear()
|
|
|
|
|
2018-06-13 17:20:15 +03:00
|
|
|
async def _dispatch_update(self, update):
|
2018-08-21 11:27:12 +03:00
|
|
|
built = EventBuilderDict(self, update)
|
2018-08-03 18:51:56 +03:00
|
|
|
if self._conversations:
|
|
|
|
for conv in self._conversations.values():
|
|
|
|
if built[events.NewMessage]:
|
|
|
|
conv._on_new_message(built[events.NewMessage])
|
|
|
|
if built[events.MessageEdited]:
|
|
|
|
conv._on_edit(built[events.MessageEdited])
|
|
|
|
if built[events.MessageRead]:
|
|
|
|
conv._on_read(built[events.MessageRead])
|
2018-08-05 02:55:41 +03:00
|
|
|
if conv._custom:
|
2018-08-21 11:27: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:
|
2018-07-11 12:22:43 +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
|
|
|
|
|
|
|
if not builder.filter(event):
|
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(
|
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
|
|
|
|
except Exception:
|
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__].exception('Unhandled exception on %s',
|
|
|
|
name)
|
2018-06-10 14:58:21 +03:00
|
|
|
|
2018-06-27 20:40:32 +03:00
|
|
|
async def _handle_auto_reconnect(self):
|
|
|
|
# Upon reconnection, we want to send getState
|
|
|
|
# for Telegram to keep sending us updates.
|
|
|
|
try:
|
2019-01-11 17:52:30 +03:00
|
|
|
self._log[__name__].info(
|
|
|
|
'Asking for the current state after reconnect...')
|
2018-06-27 20:40:32 +03:00
|
|
|
state = await self(functions.updates.GetStateRequest())
|
2019-01-11 17:52:30 +03:00
|
|
|
self._log[__name__].info('Got new state! %s', state)
|
2018-06-27 20:40:32 +03:00
|
|
|
except errors.RPCError as e:
|
2019-01-11 17:52:30 +03:00
|
|
|
self._log[__name__].info('Failed to get current state: %r', e)
|
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.
|
|
|
|
"""
|
|
|
|
def __init__(self, client, update):
|
|
|
|
self.client = client
|
|
|
|
self.update = update
|
|
|
|
|
|
|
|
def __getitem__(self, builder):
|
|
|
|
try:
|
|
|
|
return self.__dict__[builder]
|
|
|
|
except KeyError:
|
|
|
|
event = self.__dict__[builder] = builder.build(self.update)
|
|
|
|
if event:
|
|
|
|
event.original_update = self.update
|
|
|
|
if hasattr(event, '_set_client'):
|
|
|
|
event._set_client(self.client)
|
|
|
|
else:
|
|
|
|
event._client = self.client
|
|
|
|
|
|
|
|
return event
|