From 3398bee77a29082c2e6093f082405d57a4700f0a Mon Sep 17 00:00:00 2001 From: Lonami Exo Date: Mon, 1 Apr 2019 08:46:07 +0200 Subject: [PATCH] Handle disconnection errors more gracefully in background tasks --- telethon/client/telegrambaseclient.py | 3 ++- telethon/client/updates.py | 16 +++++++++++----- 2 files changed, 13 insertions(+), 6 deletions(-) diff --git a/telethon/client/telegrambaseclient.py b/telethon/client/telegrambaseclient.py index 36b52469..d58192ba 100644 --- a/telethon/client/telegrambaseclient.py +++ b/telethon/client/telegrambaseclient.py @@ -413,7 +413,8 @@ class TelegramBaseClient(abc.ABC): their job with the client is complete and we should clean it up all. """ await self._sender.disconnect() - await helpers._cancel(self._log, updates_handle=self._updates_handle) + await helpers._cancel(self._log[__name__], + updates_handle=self._updates_handle) async def _switch_dc(self, new_dc): """ diff --git a/telethon/client/updates.py b/telethon/client/updates.py index 8d481d1e..d836585c 100644 --- a/telethon/client/updates.py +++ b/telethon/client/updates.py @@ -141,8 +141,6 @@ class UpdateMethods(UserMethods): else: max_pts = float('inf') - print('catching up since', state, 'up to', max_pts) - # No known state -> catch up since the beginning (date is ignored). # Note: pts = 0 is invalid (and so is no date/unix timestamp = 0). if not state: @@ -195,6 +193,8 @@ class UpdateMethods(UserMethods): elif isinstance(d, types.updates.DifferenceTooLong): state.pts = d.pts break + except (ConnectionError, asyncio.CancelledError): + pass finally: self._old_state = None self._new_state = state @@ -262,12 +262,15 @@ class UpdateMethods(UserMethods): pass except asyncio.CancelledError: return - except Exception as e: + except Exception: 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())) + try: + self._sender.send(functions.PingRequest(rnd())) + except (ConnectionError, asyncio.CancelledError): + return # Entities and cached files are not saved when they are # inserted because this is a rather expensive operation @@ -286,7 +289,10 @@ class UpdateMethods(UserMethods): # long without being logged in...? continue - await self(functions.updates.GetStateRequest()) + try: + await self(functions.updates.GetStateRequest()) + except (ConnectionError, asyncio.CancelledError): + return async def _dispatch_queue_updates(self): while not self._updates_queue.empty():