2017-08-21 10:00:23 +03:00
|
|
|
import errno
|
2017-05-20 16:58:44 +03:00
|
|
|
from datetime import timedelta
|
2016-10-09 13:57:38 +03:00
|
|
|
from mimetypes import guess_type
|
2017-05-29 22:24:47 +03:00
|
|
|
from threading import Event, RLock, Thread
|
2017-06-20 10:46:20 +03:00
|
|
|
from time import sleep, time
|
2017-06-08 14:12:57 +03:00
|
|
|
|
|
|
|
from . import TelegramBareClient
|
2016-10-09 13:57:38 +03:00
|
|
|
|
|
|
|
# Import some externalized utilities to work with the Telegram types and more
|
2017-05-21 14:02:54 +03:00
|
|
|
from . import helpers as utils
|
2017-06-10 12:47:51 +03:00
|
|
|
from .errors import (RPCError, UnauthorizedError, InvalidParameterError,
|
2017-07-04 11:21:15 +03:00
|
|
|
ReadCancelledError, PhoneCodeEmptyError,
|
|
|
|
PhoneMigrateError, NetworkMigrateError, UserMigrateError,
|
2017-06-10 12:47:51 +03:00
|
|
|
PhoneCodeExpiredError, PhoneCodeHashEmptyError,
|
2017-06-16 15:59:10 +03:00
|
|
|
PhoneCodeInvalidError, InvalidChecksumError)
|
2017-06-10 12:47:51 +03:00
|
|
|
|
2016-11-30 00:29:42 +03:00
|
|
|
# For sending and receiving requests
|
2017-07-24 17:54:48 +03:00
|
|
|
from .tl import Session, JsonSession
|
2017-06-05 19:00:43 +03:00
|
|
|
|
2017-06-04 18:24:08 +03:00
|
|
|
# Required to get the password salt
|
2017-05-21 14:02:54 +03:00
|
|
|
from .tl.functions.account import GetPasswordRequest
|
2017-06-04 18:24:08 +03:00
|
|
|
|
|
|
|
# Logging in and out
|
2017-05-21 14:02:54 +03:00
|
|
|
from .tl.functions.auth import (CheckPasswordRequest, LogOutRequest,
|
|
|
|
SendCodeRequest, SignInRequest,
|
2017-05-21 14:59:16 +03:00
|
|
|
SignUpRequest, ImportBotAuthorizationRequest)
|
2017-06-04 18:24:08 +03:00
|
|
|
|
|
|
|
# Easier access to common methods
|
2017-05-21 14:02:54 +03:00
|
|
|
from .tl.functions.messages import (
|
2016-11-30 00:29:42 +03:00
|
|
|
GetDialogsRequest, GetHistoryRequest, ReadHistoryRequest, SendMediaRequest,
|
|
|
|
SendMessageRequest)
|
2017-06-04 18:24:08 +03:00
|
|
|
|
|
|
|
# For .get_me() and ensuring we're authorized
|
2017-06-05 19:00:43 +03:00
|
|
|
from .tl.functions.users import GetUsersRequest
|
2017-06-04 18:24:08 +03:00
|
|
|
|
2017-06-20 10:46:20 +03:00
|
|
|
# So the server doesn't stop sending updates to us
|
|
|
|
from .tl.functions import PingRequest
|
|
|
|
|
2016-11-30 00:29:42 +03:00
|
|
|
# All the types we need to work with
|
2017-05-21 14:02:54 +03:00
|
|
|
from .tl.types import (
|
2016-11-30 00:29:42 +03:00
|
|
|
ChatPhotoEmpty, DocumentAttributeAudio, DocumentAttributeFilename,
|
2017-06-08 14:12:57 +03:00
|
|
|
InputDocumentFileLocation, InputFileLocation,
|
2016-11-30 00:29:42 +03:00
|
|
|
InputMediaUploadedDocument, InputMediaUploadedPhoto, InputPeerEmpty,
|
|
|
|
MessageMediaContact, MessageMediaDocument, MessageMediaPhoto,
|
2017-06-04 18:24:08 +03:00
|
|
|
UserProfilePhotoEmpty, InputUserSelf)
|
|
|
|
|
2017-06-08 14:12:57 +03:00
|
|
|
from .utils import find_user_or_chat, get_input_peer, get_extension
|
|
|
|
|
2016-09-04 12:07:18 +03:00
|
|
|
|
2017-06-08 14:12:57 +03:00
|
|
|
class TelegramClient(TelegramBareClient):
|
|
|
|
"""Full featured TelegramClient meant to extend the basic functionality -
|
2016-09-04 12:07:18 +03:00
|
|
|
|
2017-06-08 14:12:57 +03:00
|
|
|
As opposed to the TelegramBareClient, this one features downloading
|
|
|
|
media from different data centers, starting a second thread to
|
|
|
|
handle updates, and some very common functionality.
|
2016-09-07 12:36:34 +03:00
|
|
|
|
2017-06-08 14:12:57 +03:00
|
|
|
This should be used when the (slight) overhead of having locks,
|
|
|
|
threads, and possibly multiple connections is not an issue.
|
|
|
|
"""
|
2016-09-18 12:59:12 +03:00
|
|
|
|
2017-05-08 17:01:53 +03:00
|
|
|
# region Initialization
|
2016-09-07 12:36:34 +03:00
|
|
|
|
2017-06-08 17:23:05 +03:00
|
|
|
def __init__(self, session, api_id, api_hash, proxy=None,
|
|
|
|
device_model=None, system_version=None,
|
2017-06-22 12:43:42 +03:00
|
|
|
app_version=None, lang_code=None,
|
2017-06-30 12:48:45 +03:00
|
|
|
system_lang_code=None,
|
2017-06-22 12:43:42 +03:00
|
|
|
timeout=timedelta(seconds=5)):
|
2016-11-30 17:36:59 +03:00
|
|
|
"""Initializes the Telegram client with the specified API ID and Hash.
|
|
|
|
|
2017-06-08 17:23:05 +03:00
|
|
|
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()'!
|
2016-11-30 17:36:59 +03:00
|
|
|
|
2017-06-08 17:23:05 +03:00
|
|
|
Default values for the optional parameters if left as None are:
|
2017-06-30 12:48:45 +03:00
|
|
|
device_model = platform.node()
|
|
|
|
system_version = platform.system()
|
|
|
|
app_version = TelegramClient.__version__
|
|
|
|
lang_code = 'en'
|
|
|
|
system_lang_code = lang_code
|
2017-06-08 17:23:05 +03:00
|
|
|
"""
|
2017-06-08 14:12:57 +03:00
|
|
|
if not api_id or not api_hash:
|
2016-11-30 00:29:42 +03:00
|
|
|
raise PermissionError(
|
2017-06-08 14:12:57 +03:00
|
|
|
"Your API ID or Hash cannot be empty or None. "
|
|
|
|
"Refer to Telethon's README.rst for more information.")
|
2016-09-04 12:07:18 +03:00
|
|
|
|
2016-11-30 17:36:59 +03:00
|
|
|
# Determine what session object we have
|
2017-06-07 13:48:54 +03:00
|
|
|
# TODO JsonSession until migration is complete (by v1.0)
|
2017-05-11 15:08:38 +03:00
|
|
|
if isinstance(session, str) or session is None:
|
2017-06-08 14:12:57 +03:00
|
|
|
session = JsonSession.try_load_or_create_new(session)
|
2017-08-07 01:54:23 +03:00
|
|
|
elif not isinstance(session, Session) and not isinstance(session, JsonSession):
|
2016-11-30 17:56:30 +03:00
|
|
|
raise ValueError(
|
2017-06-08 14:12:57 +03:00
|
|
|
'The given session must be a str or a Session instance.')
|
2016-11-30 17:36:59 +03:00
|
|
|
|
2017-06-22 12:43:42 +03:00
|
|
|
super().__init__(session, api_id, api_hash, proxy, timeout=timeout)
|
2017-06-07 21:08:16 +03:00
|
|
|
|
2017-05-29 22:24:47 +03:00
|
|
|
# Safety across multiple threads (for the updates thread)
|
|
|
|
self._lock = RLock()
|
|
|
|
|
2017-06-20 10:46:20 +03:00
|
|
|
# Updates-related members
|
2017-06-07 21:08:16 +03:00
|
|
|
self._update_handlers = []
|
2017-05-29 22:24:47 +03:00
|
|
|
self._updates_thread_running = Event()
|
|
|
|
self._updates_thread_receiving = Event()
|
|
|
|
|
2017-06-20 10:46:20 +03:00
|
|
|
self._next_ping_at = 0
|
|
|
|
self.ping_interval = 60 # Seconds
|
|
|
|
|
2017-06-08 17:23:05 +03:00
|
|
|
# Used on connection - the user may modify these and reconnect
|
2017-06-10 14:15:04 +03:00
|
|
|
if device_model:
|
|
|
|
self.session.device_model = device_model
|
2017-06-08 17:23:05 +03:00
|
|
|
|
2017-06-10 14:15:04 +03:00
|
|
|
if system_version:
|
|
|
|
self.session.system_version = system_version
|
2017-06-08 17:23:05 +03:00
|
|
|
|
2017-06-10 14:15:04 +03:00
|
|
|
self.session.app_version = \
|
|
|
|
app_version if app_version else self.__version__
|
|
|
|
|
|
|
|
if lang_code:
|
|
|
|
self.session.lang_code = lang_code
|
2017-06-08 17:23:05 +03:00
|
|
|
|
2017-06-30 12:48:45 +03:00
|
|
|
self.session.system_lang_code = \
|
|
|
|
system_lang_code if system_lang_code else self.session.lang_code
|
|
|
|
|
2017-05-29 22:24:47 +03:00
|
|
|
self._updates_thread = None
|
2017-06-08 14:12:57 +03:00
|
|
|
self._phone_code_hashes = {}
|
2016-09-07 12:36:34 +03:00
|
|
|
|
|
|
|
# endregion
|
|
|
|
|
|
|
|
# region Connecting
|
2016-09-04 12:07:18 +03:00
|
|
|
|
2017-06-22 12:43:42 +03:00
|
|
|
def connect(self, *args):
|
2017-06-08 17:59:47 +03:00
|
|
|
"""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.
|
|
|
|
|
2017-06-22 11:39:00 +03:00
|
|
|
The specified timeout will be used on internal .invoke()'s.
|
|
|
|
|
2017-06-08 17:59:47 +03:00
|
|
|
*args will be ignored.
|
|
|
|
"""
|
2017-06-23 11:15:11 +03:00
|
|
|
return super().connect()
|
2017-06-08 17:23:05 +03:00
|
|
|
|
2016-09-09 12:47:37 +03:00
|
|
|
def disconnect(self):
|
2017-06-08 14:12:57 +03:00
|
|
|
"""Disconnects from the Telegram server
|
|
|
|
and stops all the spawned threads"""
|
2017-05-29 22:24:47 +03:00
|
|
|
self._set_updates_thread(running=False)
|
2017-06-23 11:15:11 +03:00
|
|
|
super().disconnect()
|
2016-09-09 12:47:37 +03:00
|
|
|
|
2017-05-30 14:03:14 +03:00
|
|
|
# Also disconnect all the cached senders
|
2017-06-09 11:35:19 +03:00
|
|
|
for sender in self._cached_clients.values():
|
2017-05-30 14:03:14 +03:00
|
|
|
sender.disconnect()
|
|
|
|
|
2017-06-09 11:35:19 +03:00
|
|
|
self._cached_clients.clear()
|
2017-05-30 14:03:14 +03:00
|
|
|
|
2016-09-07 12:36:34 +03:00
|
|
|
# endregion
|
2016-09-04 12:07:18 +03:00
|
|
|
|
2017-06-15 16:50:44 +03:00
|
|
|
# region Working with different connections
|
2017-05-30 13:14:29 +03:00
|
|
|
|
2017-06-15 16:50:44 +03:00
|
|
|
def create_new_connection(self, on_dc=None):
|
|
|
|
"""Creates a new connection which can be used in parallel
|
|
|
|
with the original TelegramClient. A TelegramBareClient
|
|
|
|
will be returned already connected, and the caller is
|
|
|
|
responsible to disconnect it.
|
|
|
|
|
|
|
|
If 'on_dc' is None, the new client will run on the same
|
|
|
|
data center as the current client (most common case).
|
|
|
|
|
|
|
|
If the client is meant to be used on a different data
|
|
|
|
center, the data center ID should be specified instead.
|
|
|
|
"""
|
|
|
|
if on_dc is None:
|
2017-07-04 11:21:15 +03:00
|
|
|
client = TelegramBareClient(
|
|
|
|
self.session, self.api_id, self.api_hash, proxy=self.proxy)
|
2017-06-15 16:50:44 +03:00
|
|
|
client.connect()
|
|
|
|
else:
|
|
|
|
client = self._get_exported_client(on_dc, bypass_cache=True)
|
|
|
|
|
|
|
|
return client
|
|
|
|
|
2017-05-30 13:14:29 +03:00
|
|
|
# endregion
|
|
|
|
|
2016-09-07 12:36:34 +03:00
|
|
|
# region Telegram requests functions
|
2016-09-04 12:07:18 +03:00
|
|
|
|
2017-06-22 12:43:42 +03:00
|
|
|
def invoke(self, request, *args):
|
2017-06-08 14:12:57 +03:00
|
|
|
"""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.
|
2017-06-08 17:59:47 +03:00
|
|
|
|
|
|
|
*args will be ignored.
|
2017-06-08 14:12:57 +03:00
|
|
|
"""
|
2017-05-29 22:24:47 +03:00
|
|
|
if self._updates_thread_receiving.is_set():
|
2017-06-22 12:43:42 +03:00
|
|
|
self._sender.cancel_receive()
|
2017-05-29 22:24:47 +03:00
|
|
|
|
2017-03-20 14:23:53 +03:00
|
|
|
try:
|
2017-05-29 22:24:47 +03:00
|
|
|
self._lock.acquire()
|
2017-03-20 14:23:53 +03:00
|
|
|
|
2017-06-08 14:12:57 +03:00
|
|
|
updates = [] if self._update_handlers else None
|
2017-06-23 11:15:11 +03:00
|
|
|
result = super().invoke(
|
2017-06-22 12:43:42 +03:00
|
|
|
request, updates=updates
|
|
|
|
)
|
2016-09-11 17:24:03 +03:00
|
|
|
|
2017-06-08 14:12:57 +03:00
|
|
|
if updates:
|
|
|
|
for update in updates:
|
|
|
|
for handler in self._update_handlers:
|
|
|
|
handler(update)
|
2017-03-20 14:23:53 +03:00
|
|
|
|
2017-06-08 14:12:57 +03:00
|
|
|
# TODO Retry if 'result' is None?
|
|
|
|
return result
|
2016-09-11 17:24:03 +03:00
|
|
|
|
2017-06-10 12:47:51 +03:00
|
|
|
except (PhoneMigrateError, NetworkMigrateError, UserMigrateError) as e:
|
2017-07-10 16:21:20 +03:00
|
|
|
self._logger.debug('DC error when invoking request, '
|
2017-06-10 12:47:51 +03:00
|
|
|
'attempting to reconnect at DC {}'
|
|
|
|
.format(e.new_dc))
|
2017-06-08 17:51:20 +03:00
|
|
|
|
2017-06-10 12:47:51 +03:00
|
|
|
self.reconnect(new_dc=e.new_dc)
|
2017-06-22 12:43:42 +03:00
|
|
|
return self.invoke(request)
|
2017-05-29 22:24:47 +03:00
|
|
|
|
|
|
|
finally:
|
|
|
|
self._lock.release()
|
|
|
|
|
2017-07-02 12:56:40 +03:00
|
|
|
# Let people use client(SomeRequest()) instead client.invoke(...)
|
|
|
|
__call__ = invoke
|
|
|
|
|
2017-06-22 12:43:42 +03:00
|
|
|
def invoke_on_dc(self, request, dc_id, reconnect=False):
|
2017-05-30 14:03:14 +03:00
|
|
|
"""Invokes the given request on a different DC
|
|
|
|
by making use of the exported MtProtoSenders.
|
|
|
|
|
2017-06-03 14:36:41 +03:00
|
|
|
If 'reconnect=True', then the a reconnection will be performed and
|
|
|
|
ConnectionResetError will be raised if it occurs a second time.
|
2017-05-30 14:03:14 +03:00
|
|
|
"""
|
|
|
|
try:
|
2017-06-09 11:35:19 +03:00
|
|
|
client = self._get_exported_client(
|
2017-05-30 14:03:14 +03:00
|
|
|
dc_id, init_connection=reconnect)
|
|
|
|
|
2017-06-09 11:35:19 +03:00
|
|
|
return client.invoke(request)
|
2017-05-30 14:03:14 +03:00
|
|
|
|
|
|
|
except ConnectionResetError:
|
|
|
|
if reconnect:
|
|
|
|
raise
|
|
|
|
else:
|
2017-06-22 12:43:42 +03:00
|
|
|
return self.invoke_on_dc(request, dc_id, reconnect=True)
|
2017-05-30 14:03:14 +03:00
|
|
|
|
2016-09-11 17:24:03 +03:00
|
|
|
# region Authorization requests
|
|
|
|
|
2016-09-07 12:36:34 +03:00
|
|
|
def is_user_authorized(self):
|
2017-06-04 18:24:08 +03:00
|
|
|
"""Has the user been authorized yet
|
|
|
|
(code request sent and confirmed)?"""
|
|
|
|
return self.session and self.get_me() is not None
|
2016-09-04 12:07:18 +03:00
|
|
|
|
2016-09-04 13:42:11 +03:00
|
|
|
def send_code_request(self, phone_number):
|
2016-09-07 12:36:34 +03:00
|
|
|
"""Sends a code request to the specified phone number"""
|
2017-07-02 12:56:40 +03:00
|
|
|
result = self(
|
2017-06-08 14:12:57 +03:00
|
|
|
SendCodeRequest(phone_number, self.api_id, self.api_hash))
|
|
|
|
|
|
|
|
self._phone_code_hashes[phone_number] = result.phone_code_hash
|
|
|
|
|
|
|
|
def sign_in(self, phone_number=None, code=None,
|
|
|
|
password=None, bot_token=None):
|
|
|
|
"""Completes the sign in process with the phone number + code pair.
|
2016-09-05 19:35:12 +03:00
|
|
|
|
2017-06-08 14:12:57 +03:00
|
|
|
If no phone or code is provided, then the sole password will be used.
|
|
|
|
The password should be used after a normal authorization attempt
|
|
|
|
has happened and an RPCError with `.password_required = True` was
|
|
|
|
raised.
|
2016-09-04 12:07:18 +03:00
|
|
|
|
2017-06-08 14:12:57 +03:00
|
|
|
To login as a bot, only `bot_token` should be provided.
|
|
|
|
This should equal to the bot access hash provided by
|
|
|
|
https://t.me/BotFather during your bot creation.
|
2017-03-20 14:31:13 +03:00
|
|
|
|
2017-06-08 14:12:57 +03:00
|
|
|
If the login succeeds, the logged in user is returned.
|
|
|
|
"""
|
2016-11-26 14:04:02 +03:00
|
|
|
if phone_number and code:
|
2017-06-08 14:12:57 +03:00
|
|
|
if phone_number not in self._phone_code_hashes:
|
2016-11-30 00:29:42 +03:00
|
|
|
raise ValueError(
|
2017-06-08 14:12:57 +03:00
|
|
|
'Please make sure to call send_code_request first.')
|
2016-09-16 14:35:14 +03:00
|
|
|
|
2016-11-26 14:04:02 +03:00
|
|
|
try:
|
2017-07-02 12:56:40 +03:00
|
|
|
result = self(SignInRequest(
|
2017-06-08 14:12:57 +03:00
|
|
|
phone_number, self._phone_code_hashes[phone_number], code))
|
2016-11-26 14:04:02 +03:00
|
|
|
|
2017-06-10 12:47:51 +03:00
|
|
|
except (PhoneCodeEmptyError, PhoneCodeExpiredError,
|
|
|
|
PhoneCodeHashEmptyError, PhoneCodeInvalidError):
|
|
|
|
return None
|
2017-06-08 14:12:57 +03:00
|
|
|
|
2016-11-26 14:04:02 +03:00
|
|
|
elif password:
|
2017-07-02 12:56:40 +03:00
|
|
|
salt = self(GetPasswordRequest()).current_salt
|
|
|
|
result = self(
|
2016-11-30 00:29:42 +03:00
|
|
|
CheckPasswordRequest(utils.get_password_hash(password, salt)))
|
2017-06-08 14:12:57 +03:00
|
|
|
|
2017-03-20 14:31:13 +03:00
|
|
|
elif bot_token:
|
2017-07-02 12:56:40 +03:00
|
|
|
result = self(ImportBotAuthorizationRequest(
|
2017-06-08 14:12:57 +03:00
|
|
|
flags=0, bot_auth_token=bot_token,
|
|
|
|
api_id=self.api_id, api_hash=self.api_hash))
|
|
|
|
|
2016-11-26 14:04:02 +03:00
|
|
|
else:
|
2016-11-30 00:29:42 +03:00
|
|
|
raise ValueError(
|
2017-06-08 14:12:57 +03:00
|
|
|
'You must provide a phone_number and a code the first time, '
|
2016-11-30 00:29:42 +03:00
|
|
|
'and a password only if an RPCError was raised before.')
|
2016-09-04 12:07:18 +03:00
|
|
|
|
2017-06-08 14:12:57 +03:00
|
|
|
return result.user
|
2016-09-04 12:07:18 +03:00
|
|
|
|
2016-09-16 14:35:14 +03:00
|
|
|
def sign_up(self, phone_number, code, first_name, last_name=''):
|
|
|
|
"""Signs up to Telegram. Make sure you sent a code request first!"""
|
2017-07-02 12:56:40 +03:00
|
|
|
result = self(
|
2016-11-30 00:29:42 +03:00
|
|
|
SignUpRequest(
|
|
|
|
phone_number=phone_number,
|
2017-06-08 14:12:57 +03:00
|
|
|
phone_code_hash=self._phone_code_hashes[phone_number],
|
2016-11-30 00:29:42 +03:00
|
|
|
phone_code=code,
|
|
|
|
first_name=first_name,
|
|
|
|
last_name=last_name))
|
2016-09-16 14:35:14 +03:00
|
|
|
|
|
|
|
self.session.user = result.user
|
|
|
|
self.session.save()
|
|
|
|
|
|
|
|
def log_out(self):
|
2017-06-08 14:12:57 +03:00
|
|
|
"""Logs out and deletes the current session.
|
|
|
|
Returns True if everything went okay."""
|
2017-04-14 16:28:15 +03:00
|
|
|
# Special flag when logging out (so the ack request confirms it)
|
2017-06-22 12:43:42 +03:00
|
|
|
self._sender.logging_out = True
|
2017-08-21 10:00:23 +03:00
|
|
|
|
2016-09-16 14:35:14 +03:00
|
|
|
try:
|
2017-07-02 12:56:40 +03:00
|
|
|
self(LogOutRequest())
|
2017-04-14 16:28:15 +03:00
|
|
|
self.disconnect()
|
2017-08-21 10:00:23 +03:00
|
|
|
except OSError as e:
|
|
|
|
# macOS issue: https://github.com/veusz/veusz/issues/54
|
|
|
|
# Socket has been already closed (Errno 57)
|
|
|
|
# Fail on any other error
|
|
|
|
if e.errno != errno.ENOTCONN:
|
|
|
|
raise
|
2017-05-21 14:59:16 +03:00
|
|
|
except (RPCError, ConnectionError):
|
2017-04-11 10:52:44 +03:00
|
|
|
# Something happened when logging out, restore the state back
|
2017-06-22 12:43:42 +03:00
|
|
|
self._sender.logging_out = False
|
2016-09-16 14:35:14 +03:00
|
|
|
return False
|
|
|
|
|
2017-08-21 10:00:23 +03:00
|
|
|
self.session.delete()
|
|
|
|
self.session = None
|
|
|
|
return True
|
|
|
|
|
2017-06-04 18:24:08 +03:00
|
|
|
def get_me(self):
|
|
|
|
"""Gets "me" (the self user) which is currently authenticated,
|
|
|
|
or None if the request fails (hence, not authenticated)."""
|
|
|
|
try:
|
2017-07-02 12:56:40 +03:00
|
|
|
return self(GetUsersRequest([InputUserSelf()]))[0]
|
2017-06-10 12:47:51 +03:00
|
|
|
except UnauthorizedError:
|
|
|
|
return None
|
2017-06-04 18:24:08 +03:00
|
|
|
|
2016-09-11 17:24:03 +03:00
|
|
|
# endregion
|
|
|
|
|
|
|
|
# region Dialogs ("chats") requests
|
|
|
|
|
2016-11-30 00:29:42 +03:00
|
|
|
def get_dialogs(self,
|
2017-05-05 16:11:48 +03:00
|
|
|
limit=10,
|
2016-11-30 00:29:42 +03:00
|
|
|
offset_date=None,
|
|
|
|
offset_id=0,
|
|
|
|
offset_peer=InputPeerEmpty()):
|
2017-06-08 14:12:57 +03:00
|
|
|
"""Returns a tuple of lists ([dialogs], [entities])
|
|
|
|
with at least 'limit' items each.
|
|
|
|
|
|
|
|
If `limit` is 0, all dialogs will (should) retrieved.
|
|
|
|
The `entities` represent the user, chat or channel
|
|
|
|
corresponding to that dialog.
|
|
|
|
"""
|
2016-09-06 19:54:49 +03:00
|
|
|
|
2017-07-02 12:56:40 +03:00
|
|
|
r = self(
|
2016-11-30 00:29:42 +03:00
|
|
|
GetDialogsRequest(
|
|
|
|
offset_date=offset_date,
|
|
|
|
offset_id=offset_id,
|
|
|
|
offset_peer=offset_peer,
|
2017-05-05 16:11:48 +03:00
|
|
|
limit=limit))
|
2016-11-30 00:29:42 +03:00
|
|
|
return (
|
|
|
|
r.dialogs,
|
|
|
|
[find_user_or_chat(d.peer, r.users, r.chats) for d in r.dialogs])
|
2016-09-06 19:54:49 +03:00
|
|
|
|
2016-09-11 17:24:03 +03:00
|
|
|
# endregion
|
|
|
|
|
|
|
|
# region Message requests
|
|
|
|
|
2016-11-30 00:29:42 +03:00
|
|
|
def send_message(self,
|
2017-01-17 22:22:47 +03:00
|
|
|
entity,
|
2016-11-30 00:29:42 +03:00
|
|
|
message,
|
2017-07-07 11:37:19 +03:00
|
|
|
link_preview=True):
|
2017-06-08 14:12:57 +03:00
|
|
|
"""Sends a message to the given entity (or input peer)
|
|
|
|
and returns the sent message ID"""
|
2017-07-04 17:53:07 +03:00
|
|
|
request = SendMessageRequest(
|
2017-06-11 20:16:59 +03:00
|
|
|
peer=get_input_peer(entity),
|
|
|
|
message=message,
|
|
|
|
entities=[],
|
2017-07-07 11:37:19 +03:00
|
|
|
no_webpage=not link_preview
|
2017-07-04 17:53:07 +03:00
|
|
|
)
|
|
|
|
result = self(request)
|
|
|
|
for handler in self._update_handlers:
|
|
|
|
handler(result)
|
|
|
|
return request.random_id
|
2016-09-06 19:54:49 +03:00
|
|
|
|
2016-11-30 00:29:42 +03:00
|
|
|
def get_message_history(self,
|
2017-01-17 22:22:47 +03:00
|
|
|
entity,
|
2016-11-30 00:29:42 +03:00
|
|
|
limit=20,
|
|
|
|
offset_date=None,
|
|
|
|
offset_id=0,
|
|
|
|
max_id=0,
|
|
|
|
min_id=0,
|
|
|
|
add_offset=0):
|
2016-09-08 13:13:31 +03:00
|
|
|
"""
|
2017-01-17 22:22:47 +03:00
|
|
|
Gets the message history for the specified entity
|
2016-09-08 13:13:31 +03:00
|
|
|
|
2017-01-17 22:22:47 +03:00
|
|
|
:param entity: The entity (or input peer) from whom to retrieve the message history
|
2016-09-08 13:13:31 +03:00
|
|
|
:param limit: Number of messages to be retrieved
|
|
|
|
:param offset_date: Offset date (messages *previous* to this date will be retrieved)
|
|
|
|
:param offset_id: Offset message ID (only messages *previous* to the given ID will be retrieved)
|
|
|
|
:param max_id: All the messages with a higher (newer) ID or equal to this will be excluded
|
|
|
|
:param min_id: All the messages with a lower (older) ID or equal to this will be excluded
|
|
|
|
:param add_offset: Additional message offset (all of the specified offsets + this offset = older messages)
|
|
|
|
|
|
|
|
:return: A tuple containing total message count and two more lists ([messages], [senders]).
|
|
|
|
Note that the sender can be null if it was not found!
|
|
|
|
"""
|
2017-07-02 12:56:40 +03:00
|
|
|
result = self(GetHistoryRequest(
|
|
|
|
get_input_peer(entity),
|
|
|
|
limit=limit,
|
|
|
|
offset_date=offset_date,
|
|
|
|
offset_id=offset_id,
|
|
|
|
max_id=max_id,
|
|
|
|
min_id=min_id,
|
|
|
|
add_offset=add_offset
|
|
|
|
))
|
2016-09-08 13:13:31 +03:00
|
|
|
|
2017-06-14 15:06:35 +03:00
|
|
|
# The result may be a messages slice (not all messages were retrieved)
|
|
|
|
# or simply a messages TLObject. In the later case, no "count"
|
|
|
|
# attribute is specified, so the total messages count is simply
|
|
|
|
# the count of retrieved messages
|
2016-09-08 13:13:31 +03:00
|
|
|
total_messages = getattr(result, 'count', len(result.messages))
|
2016-09-11 11:35:02 +03:00
|
|
|
|
2016-09-12 15:07:45 +03:00
|
|
|
# Iterate over all the messages and find the sender User
|
2017-06-15 10:41:01 +03:00
|
|
|
entities = [find_user_or_chat(m.from_id, result.users, result.chats)
|
|
|
|
if m.from_id is not None else
|
|
|
|
find_user_or_chat(m.to_id, result.users, result.chats)
|
|
|
|
for m in result.messages]
|
2017-06-14 15:06:35 +03:00
|
|
|
|
|
|
|
return total_messages, result.messages, entities
|
2016-09-12 15:07:45 +03:00
|
|
|
|
2017-01-17 22:22:47 +03:00
|
|
|
def send_read_acknowledge(self, entity, messages=None, max_id=None):
|
2016-10-02 14:57:03 +03:00
|
|
|
"""Sends a "read acknowledge" (i.e., notifying the given peer that we've
|
2017-06-10 14:39:37 +03:00
|
|
|
read their messages, also known as the "double check").
|
2016-10-02 14:57:03 +03:00
|
|
|
|
|
|
|
Either a list of messages (or a single message) can be given,
|
|
|
|
or the maximum message ID (until which message we want to send the read acknowledge).
|
|
|
|
|
|
|
|
Returns an AffectedMessages TLObject"""
|
|
|
|
if max_id is None:
|
|
|
|
if not messages:
|
2016-11-30 00:29:42 +03:00
|
|
|
raise InvalidParameterError(
|
|
|
|
'Either a message list or a max_id must be provided.')
|
2016-10-02 14:57:03 +03:00
|
|
|
|
|
|
|
if isinstance(messages, list):
|
|
|
|
max_id = max(msg.id for msg in messages)
|
|
|
|
else:
|
|
|
|
max_id = messages.id
|
|
|
|
|
2017-07-02 12:56:40 +03:00
|
|
|
return self(ReadHistoryRequest(
|
|
|
|
peer=get_input_peer(entity),
|
|
|
|
max_id=max_id
|
|
|
|
))
|
2016-10-02 14:57:03 +03:00
|
|
|
|
2016-09-11 17:24:03 +03:00
|
|
|
# endregion
|
|
|
|
|
2017-06-15 16:50:44 +03:00
|
|
|
# region Uploading files
|
|
|
|
|
2017-01-17 22:22:47 +03:00
|
|
|
def send_photo_file(self, input_file, entity, caption=''):
|
2016-09-11 14:10:27 +03:00
|
|
|
"""Sends a previously uploaded input_file
|
2017-01-17 22:22:47 +03:00
|
|
|
(which should be a photo) to the given entity (or input peer)"""
|
2016-09-11 14:10:27 +03:00
|
|
|
self.send_media_file(
|
2017-01-17 22:22:47 +03:00
|
|
|
InputMediaUploadedPhoto(input_file, caption), entity)
|
2016-09-11 14:10:27 +03:00
|
|
|
|
2017-01-17 22:22:47 +03:00
|
|
|
def send_document_file(self, input_file, entity, caption=''):
|
2016-09-12 20:32:16 +03:00
|
|
|
"""Sends a previously uploaded input_file
|
2017-01-17 22:22:47 +03:00
|
|
|
(which should be a document) to the given entity (or input peer)"""
|
2016-09-12 20:32:16 +03:00
|
|
|
|
|
|
|
# Determine mime-type and attributes
|
|
|
|
# Take the first element by using [0] since it returns a tuple
|
|
|
|
mime_type = guess_type(input_file.name)[0]
|
|
|
|
attributes = [
|
|
|
|
DocumentAttributeFilename(input_file.name)
|
|
|
|
# TODO If the input file is an audio, find out:
|
|
|
|
# Performer and song title and add DocumentAttributeAudio
|
|
|
|
]
|
2016-09-16 17:37:45 +03:00
|
|
|
# Ensure we have a mime type, any; but it cannot be None
|
2017-06-10 14:39:37 +03:00
|
|
|
# 'The "octet-stream" subtype is used to indicate that a body
|
|
|
|
# contains arbitrary binary data.'
|
2016-09-16 17:37:45 +03:00
|
|
|
if not mime_type:
|
|
|
|
mime_type = 'application/octet-stream'
|
2016-11-30 00:29:42 +03:00
|
|
|
self.send_media_file(
|
|
|
|
InputMediaUploadedDocument(
|
|
|
|
file=input_file,
|
|
|
|
mime_type=mime_type,
|
|
|
|
attributes=attributes,
|
|
|
|
caption=caption),
|
2017-01-17 22:22:47 +03:00
|
|
|
entity)
|
2016-09-12 20:32:16 +03:00
|
|
|
|
2017-01-17 22:22:47 +03:00
|
|
|
def send_media_file(self, input_media, entity):
|
2017-05-20 16:58:44 +03:00
|
|
|
"""Sends any input_media (contact, document, photo...) to the given entity"""
|
2017-07-02 12:56:40 +03:00
|
|
|
self(SendMediaRequest(
|
2017-06-11 20:16:59 +03:00
|
|
|
peer=get_input_peer(entity),
|
|
|
|
media=input_media
|
|
|
|
))
|
2016-09-11 14:10:27 +03:00
|
|
|
|
2016-09-12 20:32:16 +03:00
|
|
|
# endregion
|
|
|
|
|
|
|
|
# region Downloading media requests
|
|
|
|
|
2016-11-30 00:29:42 +03:00
|
|
|
def download_profile_photo(self,
|
|
|
|
profile_photo,
|
|
|
|
file_path,
|
|
|
|
add_extension=True,
|
|
|
|
download_big=True):
|
2016-10-03 20:44:01 +03:00
|
|
|
"""Downloads the profile photo for an user or a chat (including channels).
|
2017-05-21 14:59:16 +03:00
|
|
|
Returns False if no photo was provided, or if it was Empty"""
|
2016-10-03 20:44:01 +03:00
|
|
|
|
|
|
|
if (not profile_photo or
|
2016-11-30 00:29:42 +03:00
|
|
|
isinstance(profile_photo, UserProfilePhotoEmpty) or
|
2016-10-03 20:44:01 +03:00
|
|
|
isinstance(profile_photo, ChatPhotoEmpty)):
|
|
|
|
return False
|
|
|
|
|
|
|
|
if add_extension:
|
2016-10-09 13:57:38 +03:00
|
|
|
file_path += get_extension(profile_photo)
|
2016-10-03 20:44:01 +03:00
|
|
|
|
|
|
|
if download_big:
|
|
|
|
photo_location = profile_photo.photo_big
|
|
|
|
else:
|
|
|
|
photo_location = profile_photo.photo_small
|
|
|
|
|
|
|
|
# Download the media with the largest size input file location
|
2017-06-08 14:12:57 +03:00
|
|
|
self.download_file(
|
2016-11-30 00:29:42 +03:00
|
|
|
InputFileLocation(
|
|
|
|
volume_id=photo_location.volume_id,
|
|
|
|
local_id=photo_location.local_id,
|
2017-06-08 14:12:57 +03:00
|
|
|
secret=photo_location.secret
|
|
|
|
),
|
|
|
|
file_path
|
|
|
|
)
|
2016-10-03 20:44:01 +03:00
|
|
|
return True
|
|
|
|
|
2016-11-30 00:29:42 +03:00
|
|
|
def download_msg_media(self,
|
|
|
|
message_media,
|
2017-07-20 10:37:19 +03:00
|
|
|
file,
|
2016-11-30 00:29:42 +03:00
|
|
|
add_extension=True,
|
|
|
|
progress_callback=None):
|
2016-09-12 20:32:16 +03:00
|
|
|
"""Downloads the given MessageMedia (Photo, Document or Contact)
|
2017-07-23 18:08:04 +03:00
|
|
|
into the desired file (a stream or str), optionally finding its
|
|
|
|
extension automatically.
|
|
|
|
|
|
|
|
The progress_callback should be a callback function which takes
|
|
|
|
two parameters, uploaded size and total file size (both in bytes).
|
|
|
|
This will be called every time a part is downloaded
|
|
|
|
"""
|
2016-09-12 20:32:16 +03:00
|
|
|
if type(message_media) == MessageMediaPhoto:
|
2017-07-20 10:37:19 +03:00
|
|
|
return self.download_photo(message_media, file, add_extension,
|
2016-11-30 00:29:42 +03:00
|
|
|
progress_callback)
|
2016-09-12 20:32:16 +03:00
|
|
|
|
|
|
|
elif type(message_media) == MessageMediaDocument:
|
2017-07-20 10:37:19 +03:00
|
|
|
return self.download_document(message_media, file,
|
2016-11-30 00:29:42 +03:00
|
|
|
add_extension, progress_callback)
|
2016-09-12 20:32:16 +03:00
|
|
|
|
|
|
|
elif type(message_media) == MessageMediaContact:
|
2017-07-20 10:37:19 +03:00
|
|
|
return self.download_contact(message_media, file,
|
2016-11-30 00:29:42 +03:00
|
|
|
add_extension)
|
2016-09-12 20:32:16 +03:00
|
|
|
|
2016-11-30 00:29:42 +03:00
|
|
|
def download_photo(self,
|
|
|
|
message_media_photo,
|
2017-07-20 10:37:19 +03:00
|
|
|
file,
|
2016-11-30 00:29:42 +03:00
|
|
|
add_extension=False,
|
2016-09-17 18:04:30 +03:00
|
|
|
progress_callback=None):
|
2017-07-23 19:38:27 +03:00
|
|
|
"""Downloads MessageMediaPhoto's largest size into the desired file
|
|
|
|
(a stream or str), optionally finding its extension automatically.
|
|
|
|
|
|
|
|
The progress_callback should be a callback function which takes
|
|
|
|
two parameters, uploaded size and total file size (both in bytes).
|
|
|
|
This will be called every time a part is downloaded
|
|
|
|
"""
|
2016-09-17 18:04:30 +03:00
|
|
|
|
2016-09-11 17:24:03 +03:00
|
|
|
# Determine the photo and its largest size
|
|
|
|
photo = message_media_photo.photo
|
2016-09-17 18:04:30 +03:00
|
|
|
largest_size = photo.sizes[-1]
|
|
|
|
file_size = largest_size.size
|
|
|
|
largest_size = largest_size.location
|
2016-09-10 19:05:20 +03:00
|
|
|
|
2017-07-20 10:37:19 +03:00
|
|
|
if isinstance(file, str) and add_extension:
|
|
|
|
file += get_extension(message_media_photo)
|
2016-09-10 19:05:20 +03:00
|
|
|
|
2016-09-12 20:32:16 +03:00
|
|
|
# Download the media with the largest size input file location
|
2017-06-08 14:12:57 +03:00
|
|
|
self.download_file(
|
2016-11-30 00:29:42 +03:00
|
|
|
InputFileLocation(
|
|
|
|
volume_id=largest_size.volume_id,
|
|
|
|
local_id=largest_size.local_id,
|
2017-06-08 14:12:57 +03:00
|
|
|
secret=largest_size.secret
|
|
|
|
),
|
2017-07-20 10:37:19 +03:00
|
|
|
file,
|
2016-11-30 00:29:42 +03:00
|
|
|
file_size=file_size,
|
2017-06-08 14:12:57 +03:00
|
|
|
progress_callback=progress_callback
|
|
|
|
)
|
2017-07-20 10:37:19 +03:00
|
|
|
return file
|
2016-09-12 20:32:16 +03:00
|
|
|
|
2016-11-30 00:29:42 +03:00
|
|
|
def download_document(self,
|
|
|
|
message_media_document,
|
2017-07-20 10:37:19 +03:00
|
|
|
file=None,
|
2016-11-30 00:29:42 +03:00
|
|
|
add_extension=True,
|
2016-09-17 18:04:30 +03:00
|
|
|
progress_callback=None):
|
2017-07-23 19:38:27 +03:00
|
|
|
"""Downloads the given MessageMediaDocument into the desired file
|
|
|
|
(a stream or str), optionally finding its extension automatically.
|
|
|
|
|
|
|
|
If no file_path is given it will try to be guessed from the document.
|
|
|
|
|
|
|
|
The progress_callback should be a callback function which takes
|
|
|
|
two parameters, uploaded size and total file size (both in bytes).
|
|
|
|
This will be called every time a part is downloaded
|
|
|
|
"""
|
2016-09-12 20:32:16 +03:00
|
|
|
document = message_media_document.document
|
2016-09-17 18:04:30 +03:00
|
|
|
file_size = document.size
|
2016-09-12 20:32:16 +03:00
|
|
|
|
|
|
|
# If no file path was given, try to guess it from the attributes
|
2017-07-20 10:37:19 +03:00
|
|
|
if file is None:
|
2016-09-12 20:32:16 +03:00
|
|
|
for attr in document.attributes:
|
|
|
|
if type(attr) == DocumentAttributeFilename:
|
2017-07-20 10:37:19 +03:00
|
|
|
file = attr.file_name
|
2016-09-12 20:32:16 +03:00
|
|
|
break # This attribute has higher preference
|
|
|
|
|
|
|
|
elif type(attr) == DocumentAttributeAudio:
|
2017-07-20 10:37:19 +03:00
|
|
|
file = '{} - {}'.format(attr.performer, attr.title)
|
2016-09-12 20:32:16 +03:00
|
|
|
|
2017-07-20 10:37:19 +03:00
|
|
|
if file is None:
|
2017-05-30 11:24:08 +03:00
|
|
|
raise ValueError('Could not infer a file_path for the document'
|
|
|
|
'. Please provide a valid file_path manually')
|
2016-09-12 20:32:16 +03:00
|
|
|
|
2017-07-20 10:37:19 +03:00
|
|
|
if isinstance(file, str) and add_extension:
|
|
|
|
file += get_extension(message_media_document)
|
2016-09-12 20:32:16 +03:00
|
|
|
|
2017-06-08 14:12:57 +03:00
|
|
|
self.download_file(
|
2016-11-30 00:29:42 +03:00
|
|
|
InputDocumentFileLocation(
|
|
|
|
id=document.id,
|
|
|
|
access_hash=document.access_hash,
|
2017-06-08 14:12:57 +03:00
|
|
|
version=document.version
|
|
|
|
),
|
2017-07-20 10:37:19 +03:00
|
|
|
file,
|
2016-11-30 00:29:42 +03:00
|
|
|
file_size=file_size,
|
2017-06-08 14:12:57 +03:00
|
|
|
progress_callback=progress_callback
|
|
|
|
)
|
2017-07-20 10:37:19 +03:00
|
|
|
return file
|
2016-09-12 20:32:16 +03:00
|
|
|
|
|
|
|
@staticmethod
|
2017-07-20 10:37:19 +03:00
|
|
|
def download_contact(message_media_contact, file, add_extension=True):
|
2016-09-12 20:32:16 +03:00
|
|
|
"""Downloads a media contact using the vCard 4.0 format"""
|
|
|
|
|
|
|
|
first_name = message_media_contact.first_name
|
|
|
|
last_name = message_media_contact.last_name
|
|
|
|
phone_number = message_media_contact.phone_number
|
|
|
|
|
2017-07-20 10:37:19 +03:00
|
|
|
if isinstance(file, str):
|
|
|
|
# The only way we can save a contact in an understandable
|
|
|
|
# way by phones is by using the .vCard format
|
|
|
|
if add_extension:
|
|
|
|
file += '.vcard'
|
|
|
|
|
|
|
|
# Ensure that we'll be able to download the contact
|
|
|
|
utils.ensure_parent_dir_exists(file)
|
2017-07-23 18:08:04 +03:00
|
|
|
f = open(file, 'w', encoding='utf-8')
|
2017-07-20 10:37:19 +03:00
|
|
|
else:
|
2017-07-23 18:08:04 +03:00
|
|
|
f = file
|
|
|
|
|
|
|
|
try:
|
|
|
|
f.write('BEGIN:VCARD\n')
|
|
|
|
f.write('VERSION:4.0\n')
|
|
|
|
f.write('N:{};{};;;\n'.format(
|
|
|
|
first_name, last_name if last_name else '')
|
|
|
|
)
|
|
|
|
f.write('FN:{}\n'.format(' '.join((first_name, last_name))))
|
|
|
|
f.write('TEL;TYPE=cell;VALUE=uri:tel:+{}\n'.format(
|
2016-11-30 00:29:42 +03:00
|
|
|
phone_number))
|
2017-07-23 18:08:04 +03:00
|
|
|
f.write('END:VCARD\n')
|
|
|
|
finally:
|
|
|
|
# Only close the stream if we opened it
|
|
|
|
if isinstance(file, str):
|
|
|
|
f.close()
|
2016-09-12 20:32:16 +03:00
|
|
|
|
2017-07-20 10:37:19 +03:00
|
|
|
return file
|
2016-09-12 20:32:16 +03:00
|
|
|
|
2016-09-11 17:24:03 +03:00
|
|
|
# endregion
|
2016-09-10 19:05:20 +03:00
|
|
|
|
2016-09-07 12:36:34 +03:00
|
|
|
# endregion
|
|
|
|
|
|
|
|
# region Updates handling
|
|
|
|
|
2016-09-11 12:50:38 +03:00
|
|
|
def add_update_handler(self, handler):
|
|
|
|
"""Adds an update handler (a function which takes a TLObject,
|
|
|
|
an update, as its parameter) and listens for updates"""
|
2017-06-22 12:43:42 +03:00
|
|
|
if not self._sender:
|
2017-06-07 21:08:16 +03:00
|
|
|
raise RuntimeError("You can't add update handlers until you've "
|
2017-06-08 14:12:57 +03:00
|
|
|
"successfully connected to the server.")
|
2016-10-02 14:42:17 +03:00
|
|
|
|
2017-06-07 21:08:16 +03:00
|
|
|
first_handler = not self._update_handlers
|
|
|
|
self._update_handlers.append(handler)
|
|
|
|
if first_handler:
|
|
|
|
self._set_updates_thread(running=True)
|
2016-09-09 12:47:37 +03:00
|
|
|
|
2016-09-11 12:50:38 +03:00
|
|
|
def remove_update_handler(self, handler):
|
2017-06-07 21:08:16 +03:00
|
|
|
self._update_handlers.remove(handler)
|
|
|
|
if not self._update_handlers:
|
|
|
|
self._set_updates_thread(running=False)
|
2016-09-07 12:36:34 +03:00
|
|
|
|
2017-03-28 19:46:07 +03:00
|
|
|
def list_update_handlers(self):
|
2017-06-07 21:08:16 +03:00
|
|
|
return self._update_handlers[:]
|
2017-05-29 22:24:47 +03:00
|
|
|
|
|
|
|
def _set_updates_thread(self, running):
|
|
|
|
"""Sets the updates thread status (running or not)"""
|
2017-06-07 21:08:16 +03:00
|
|
|
if running == self._updates_thread_running.is_set():
|
2017-05-29 22:24:47 +03:00
|
|
|
return
|
|
|
|
|
|
|
|
# Different state, update the saved value and behave as required
|
2017-07-10 16:21:20 +03:00
|
|
|
self._logger.debug('Changing updates thread running status to %s', running)
|
2017-05-29 22:24:47 +03:00
|
|
|
if running:
|
|
|
|
self._updates_thread_running.set()
|
2017-06-07 21:08:16 +03:00
|
|
|
if not self._updates_thread:
|
|
|
|
self._updates_thread = Thread(
|
|
|
|
name='UpdatesThread', daemon=True,
|
|
|
|
target=self._updates_thread_method)
|
|
|
|
|
2017-05-29 22:24:47 +03:00
|
|
|
self._updates_thread.start()
|
|
|
|
else:
|
|
|
|
self._updates_thread_running.clear()
|
|
|
|
if self._updates_thread_receiving.is_set():
|
2017-06-22 12:43:42 +03:00
|
|
|
self._sender.cancel_receive()
|
2017-05-29 22:24:47 +03:00
|
|
|
|
|
|
|
def _updates_thread_method(self):
|
|
|
|
"""This method will run until specified and listen for incoming updates"""
|
|
|
|
|
|
|
|
# Set a reasonable timeout when checking for updates
|
|
|
|
timeout = timedelta(minutes=1)
|
|
|
|
|
|
|
|
while self._updates_thread_running.is_set():
|
|
|
|
# Always sleep a bit before each iteration to relax the CPU,
|
|
|
|
# since it's possible to early 'continue' the loop to reach
|
|
|
|
# the next iteration, but we still should to sleep.
|
2017-06-07 21:08:16 +03:00
|
|
|
sleep(0.1)
|
2017-05-29 22:24:47 +03:00
|
|
|
|
|
|
|
with self._lock:
|
|
|
|
self._logger.debug('Updates thread acquired the lock')
|
|
|
|
try:
|
|
|
|
self._updates_thread_receiving.set()
|
2017-06-16 16:36:47 +03:00
|
|
|
self._logger.debug(
|
|
|
|
'Trying to receive updates from the updates thread'
|
|
|
|
)
|
2017-06-10 14:16:37 +03:00
|
|
|
|
2017-06-20 10:46:20 +03:00
|
|
|
if time() > self._next_ping_at:
|
|
|
|
self._next_ping_at = time() + self.ping_interval
|
2017-07-02 12:56:40 +03:00
|
|
|
self(PingRequest(utils.generate_random_long()))
|
2017-06-20 10:46:20 +03:00
|
|
|
|
2017-06-22 12:43:42 +03:00
|
|
|
updates = self._sender.receive_updates(timeout=timeout)
|
2017-06-10 14:16:37 +03:00
|
|
|
|
|
|
|
self._updates_thread_receiving.clear()
|
2017-07-10 16:21:20 +03:00
|
|
|
self._logger.debug(
|
2017-06-16 16:36:47 +03:00
|
|
|
'Received {} update(s) from the updates thread'
|
|
|
|
.format(len(updates))
|
|
|
|
)
|
|
|
|
for update in updates:
|
|
|
|
for handler in self._update_handlers:
|
|
|
|
handler(update)
|
2017-05-29 22:24:47 +03:00
|
|
|
|
2017-05-30 11:11:18 +03:00
|
|
|
except ConnectionResetError:
|
2017-07-10 16:21:20 +03:00
|
|
|
self._logger.debug('Server disconnected us. Reconnecting...')
|
2017-05-30 11:11:18 +03:00
|
|
|
self.reconnect()
|
|
|
|
|
2017-05-29 22:24:47 +03:00
|
|
|
except TimeoutError:
|
|
|
|
self._logger.debug('Receiving updates timed out')
|
|
|
|
|
|
|
|
except ReadCancelledError:
|
2017-07-10 16:21:20 +03:00
|
|
|
self._logger.debug('Receiving updates cancelled')
|
2017-05-29 22:24:47 +03:00
|
|
|
|
2017-06-16 15:59:10 +03:00
|
|
|
except BrokenPipeError:
|
2017-07-10 16:21:20 +03:00
|
|
|
self._logger.debug('Tcp session is broken. Reconnecting...')
|
2017-06-16 15:59:10 +03:00
|
|
|
self.reconnect()
|
|
|
|
|
|
|
|
except InvalidChecksumError:
|
2017-07-10 16:21:20 +03:00
|
|
|
self._logger.debug('MTProto session is broken. Reconnecting...')
|
2017-06-16 15:59:10 +03:00
|
|
|
self.reconnect()
|
|
|
|
|
2017-05-29 22:24:47 +03:00
|
|
|
except OSError:
|
2017-07-10 16:21:20 +03:00
|
|
|
self._logger.debug('OSError on updates thread, %s logging out',
|
2017-06-22 12:43:42 +03:00
|
|
|
'was' if self._sender.logging_out else 'was not')
|
2017-05-29 22:24:47 +03:00
|
|
|
|
2017-06-22 12:43:42 +03:00
|
|
|
if self._sender.logging_out:
|
2017-05-29 22:24:47 +03:00
|
|
|
# This error is okay when logging out, means we got disconnected
|
2017-06-10 14:39:37 +03:00
|
|
|
# TODO Not sure why this happens because we call disconnect()...
|
2017-05-29 22:24:47 +03:00
|
|
|
self._set_updates_thread(running=False)
|
|
|
|
else:
|
|
|
|
raise
|
|
|
|
|
|
|
|
self._logger.debug('Updates thread released the lock')
|
2017-03-28 19:46:07 +03:00
|
|
|
|
2017-06-07 21:08:16 +03:00
|
|
|
# Thread is over, so clean unset its variable
|
|
|
|
self._updates_thread = None
|
|
|
|
|
2016-09-07 12:36:34 +03:00
|
|
|
# endregion
|