From d788d30de20bdb3cd1f3b53054c55fb5c5a24f40 Mon Sep 17 00:00:00 2001 From: Lonami Exo Date: Thu, 8 Jun 2017 16:23:05 +0200 Subject: [PATCH] Move connect() parameters to init and ignore signature warnings --- telethon/telegram_bare_client.py | 25 +++---------- telethon/telegram_client.py | 41 +++++++++++++++------ telethon_examples/auto_replier.py | 60 +++++++++++++++++++++++++++++++ 3 files changed, 96 insertions(+), 30 deletions(-) create mode 100644 telethon_examples/auto_replier.py diff --git a/telethon/telegram_bare_client.py b/telethon/telegram_bare_client.py index a8c5c180..9a8f1407 100644 --- a/telethon/telegram_bare_client.py +++ b/telethon/telegram_bare_client.py @@ -71,18 +71,11 @@ class TelegramBareClient: # region Connecting - def connect(self, device_model=None, system_version=None, - app_version=None, lang_code=None): + def connect(self, device_model, system_version, app_version, lang_code): """Connects to the Telegram servers, executing authentication if required. Note that authenticating to the Telegram servers is not the same as authenticating the desired user itself, which may require a call (or several) to 'sign_in' for the first time. - - Default values for the optional parameters if left as None are: - device_model = platform.node() - system_version = platform.system() - app_version = TelegramClient.__version__ - lang_code = 'en' """ transport = TcpTransport(self.session.server_address, self.session.port, proxy=self.proxy) @@ -97,16 +90,6 @@ class TelegramBareClient: self.sender = MtProtoSender(transport, self.session) self.sender.connect() - # Set the default parameters if left unspecified - if not device_model: - device_model = platform.node() - if not system_version: - system_version = platform.system() - if not app_version: - app_version = self.__version__ - if not lang_code: - lang_code = 'en' - # Now it's time to send an InitConnectionRequest # This must always be invoked with the layer we'll be using query = InitConnectionRequest( @@ -140,7 +123,7 @@ class TelegramBareClient: self.session.server_address = dc.ip_address self.session.port = dc.port self.session.save() - self.connect() + self.connect(device_model, system_version, app_version, lang_code) except (RPCError, ConnectionError) as error: # Probably errors from the previous session, ignore them @@ -158,7 +141,9 @@ class TelegramBareClient: def reconnect(self): """Disconnects and connects again (effectively reconnecting)""" self.disconnect() - self.connect() + # TODO Don't use these parameters + self.connect( + platform.node(), platform.system(), self.__version__, 'en') # endregion diff --git a/telethon/telegram_client.py b/telethon/telegram_client.py index d154e76a..19ee48dc 100644 --- a/telethon/telegram_client.py +++ b/telethon/telegram_client.py @@ -63,15 +63,22 @@ class TelegramClient(TelegramBareClient): # region Initialization - def __init__(self, session, api_id, api_hash, proxy=None): + def __init__(self, session, api_id, api_hash, proxy=None, + device_model=None, system_version=None, + app_version=None, lang_code=None): """Initializes the Telegram client with the specified API ID and Hash. - Session can either be a `str` object (the filename for the loaded/saved .session) - or it can be a `Session` instance (in which case list_sessions() would probably not work). - If you don't want any file to be saved, pass `None` + Session can either be a `str` object (filename for the .session) + or it can be a `Session` instance (in which case list_sessions() + would probably not work). Pass 'None' for it to be a temporary + session - remember to '.log_out()'! - In the later case, you are free to override the `Session` class to provide different - .save() and .load() implementations to suit your needs.""" + Default values for the optional parameters if left as None are: + device_model = platform.node() + system_version = platform.system() + app_version = TelegramClient.__version__ + lang_code = 'en' + """ if not api_id or not api_hash: raise PermissionError( @@ -96,6 +103,16 @@ class TelegramClient(TelegramBareClient): self._updates_thread_running = Event() self._updates_thread_receiving = Event() + # Used on connection - the user may modify these and reconnect + self.device_model = \ + device_model if device_model else platform.node() + + self.system_version = \ + system_version if system_version else platform.system() + + self.app_version = app_version if app_version else self.__version__ + self.lang_code = lang_code if lang_code else 'en' + # Cache "exported" senders 'dc_id: MtProtoSender' and # their corresponding sessions not to recreate them all # the time since it's a (somewhat expensive) process. @@ -108,6 +125,13 @@ class TelegramClient(TelegramBareClient): # region Connecting + def connect(self): + return super(TelegramClient, self).connect( + device_model=self.device_model, + system_version=self.system_version, + app_version=self.app_version, + lang_code=self.lang_code) + def disconnect(self): """Disconnects from the Telegram server and stops all the spawned threads""" @@ -193,14 +217,11 @@ class TelegramClient(TelegramBareClient): # region Telegram requests functions - def invoke(self, request, timeout=timedelta(seconds=5), updates=None): + def invoke(self, request, timeout=timedelta(seconds=5)): """Invokes (sends) a MTProtoRequest and returns (receives) its result. An optional timeout can be specified to cancel the operation if no result is received within such time, or None to disable any timeout. - - The 'updates' parameter will be ignored, although it's kept for - both function signatures (base class and this) to be the same. """ if not issubclass(type(request), MTProtoRequest): raise ValueError('You can only invoke MtProtoRequests') diff --git a/telethon_examples/auto_replier.py b/telethon_examples/auto_replier.py new file mode 100644 index 00000000..7c1d24eb --- /dev/null +++ b/telethon_examples/auto_replier.py @@ -0,0 +1,60 @@ +# Example demonstrating how to make an automatic replier +from telethon import TelegramClient +from telethon.tl.types import UpdateShortMessage, UpdateShortChatMessage + +from time import sleep + + +def get_config(): + """Returns (session_name, user_phone, api_id, api_hash)""" + result = {} + with open('../api/settings', 'r', encoding='utf-8') as file: + for line in file: + value_pair = line.split('=') + left = value_pair[0].strip() + right = value_pair[1].strip() + result[left] = right + + return ( + '../' + result.get('session_name', 'anonymous'), + result.get('user_phone'), + int(result.get('api_id')), + result.get('api_hash') + ) + + +# Connection +user_id, user_phone, api_id, api_hash = get_config() +client = TelegramClient('session_id', api_id, api_hash) +client.connect() + +if not client.is_user_authorized(): + client.send_code_request(user_phone) + client.sign_in('+34600000000', input('Enter code: ')) + +number_of_auto_replies = int(input('Auto-reply how many times?: ')) + + +# Real work here +def auto_reply_thread(update_object): + print(type(update_object), update_object) + return +''' +if isinstance(update_object, UpdateShortMessage): + if not update_object.out: + client.send_message() + + print('[User #{} sent {}]'.format( + update_object.user_id, update_object.message)) + +elif isinstance(update_object, UpdateShortChatMessage): + if not update_object.out: + print('[Chat #{}, user #{} sent {}]'.format( + update_object.chat_id, update_object.from_id, + update_object.message)) +''' + +client.add_update_handler(auto_reply_thread) +while number_of_auto_replies > 0: + # A real application would do more work here + sleep(1) \ No newline at end of file