From 9c6d2894fc35478829e8852c0d668acc0d3cebb4 Mon Sep 17 00:00:00 2001 From: Lonami Exo Date: Mon, 25 Jun 2018 13:42:29 +0200 Subject: [PATCH] Allow start when the loop is not running --- telethon/client/auth.py | 25 +++++++++++++++++++++++-- telethon/client/updates.py | 9 +++++---- 2 files changed, 28 insertions(+), 6 deletions(-) diff --git a/telethon/client/auth.py b/telethon/client/auth.py index 61d7478d..ca8d24f5 100644 --- a/telethon/client/auth.py +++ b/telethon/client/auth.py @@ -14,7 +14,7 @@ class AuthMethods(MessageParseMethods, UserMethods): # region Public methods - async def start( + def start( self, phone=lambda: input('Please enter your phone: '), password=lambda: getpass.getpass('Please enter your password: '), @@ -37,6 +37,10 @@ class AuthMethods(MessageParseMethods, UserMethods): Please enter your password: ******* (You are now logged in) + If the event loop is already running, this method returns a + coroutine that you should await on your own code; otherwise + the loop is ran until said coroutine completes. + Args: phone (`str` | `int` | `callable`): The phone (or callable without arguments to get it) @@ -74,7 +78,6 @@ class AuthMethods(MessageParseMethods, UserMethods): This `TelegramClient`, so initialization can be chained with ``.start()``. """ - if code_callback is None: def code_callback(): return input('Please enter the code you received: ') @@ -91,6 +94,24 @@ class AuthMethods(MessageParseMethods, UserMethods): raise ValueError('Both a phone and a bot token provided, ' 'must only provide one of either') + coro = self._start( + phone=phone, + password=password, + bot_token=bot_token, + force_sms=force_sms, + code_callback=code_callback, + first_name=first_name, + last_name=last_name, + max_attempts=max_attempts + ) + return ( + coro if self.loop.is_running() + else self.loop.run_until_complete(coro) + ) + + async def _start( + self, phone, password, bot_token, force_sms, + code_callback, first_name, last_name, max_attempts): if not self.is_connected(): await self.connect() diff --git a/telethon/client/updates.py b/telethon/client/updates.py index c7c5a4ac..0aeec894 100644 --- a/telethon/client/updates.py +++ b/telethon/client/updates.py @@ -32,10 +32,11 @@ class UpdateMethods(UserMethods): If the loop is already running, this method returns a coroutine that you should await on your own code. """ - if self.loop.is_running(): - return self._run_until_disconnected() # Let the user await it - else: - self.loop.run_until_complete(self._run_until_disconnected()) + coro = self._run_until_disconnected() + return ( + coro if self.loop.is_running() + else self.loop.run_until_complete(coro) + ) def on(self, event): """