Change the way no_updates mode is enabled

See discussion on https://github.com/LonamiWebs/Telethon/commit/49713b2.

The problem with the automatic approach is that some scripts may do
some "fancier" things with the way they register updates, so it was
prone to failure (a handler could be added but since the last request
was without updates, nothing would be received).

This new approach is a bit more annoying to opt-into but also more
explicit.
This commit is contained in:
Lonami Exo 2021-08-29 11:36:08 +02:00
parent befba11657
commit 2cb6cd5dad
3 changed files with 25 additions and 2 deletions

View File

@ -199,6 +199,15 @@ class TelegramBaseClient(abc.ABC):
If a `str` is given, it'll be passed to `logging.getLogger()`. If a
`logging.Logger` is given, it'll be used directly. If something
else or nothing is given, the default logger will be used.
receive_updates (`bool`, optional):
Whether the client will receive updates or not. By default, updates
will be received from Telegram as they occur.
Turning this off means that Telegram will not send updates at all
so event handlers, conversations, and QR login will not work.
However, certain scripts don't need updates, so this will reduce
the amount of bandwidth used.
"""
# Current TelegramClient version
@ -234,7 +243,9 @@ class TelegramBaseClient(abc.ABC):
lang_code: str = 'en',
system_lang_code: str = 'en',
loop: asyncio.AbstractEventLoop = None,
base_logger: typing.Union[str, logging.Logger] = None):
base_logger: typing.Union[str, logging.Logger] = None,
receive_updates: bool = True
):
if not api_id or not api_hash:
raise ValueError(
"Your API ID or Hash cannot be empty or None. "
@ -388,6 +399,7 @@ class TelegramBaseClient(abc.ABC):
self._updates_handle = None
self._last_request = time.time()
self._channel_pts = {}
self._no_updates = not receive_updates
if sequential_updates:
self._updates_queue = asyncio.Queue()

View File

@ -32,6 +32,17 @@ class UpdateMethods:
finally:
await self.disconnect()
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())
def run_until_disconnected(self: 'TelegramClient'):
"""
Runs the event loop until the library is disconnected.

View File

@ -51,7 +51,7 @@ class UserMethods:
else:
raise errors.FloodWaitError(request=r, capture=diff)
if not self._event_builders and not self._conversations:
if self._no_updates:
r = functions.InvokeWithoutUpdatesRequest(r)
request_index = 0