2018-06-10 13:57:36 +03:00
|
|
|
import getpass
|
2018-07-08 01:04:50 +03:00
|
|
|
import inspect
|
2018-06-10 13:57:36 +03:00
|
|
|
import os
|
2018-06-26 12:26:01 +03:00
|
|
|
import sys
|
2019-05-03 22:37:27 +03:00
|
|
|
import typing
|
2018-06-10 13:57:36 +03:00
|
|
|
|
2018-12-24 16:10:15 +03:00
|
|
|
from .. import utils, helpers, errors, password as pwd_mod
|
2018-06-10 13:57:36 +03:00
|
|
|
from ..tl import types, functions
|
|
|
|
|
2019-05-03 22:37:27 +03:00
|
|
|
if typing.TYPE_CHECKING:
|
|
|
|
from .telegramclient import TelegramClient
|
|
|
|
|
2018-06-10 13:57:36 +03:00
|
|
|
|
2019-06-24 18:48:46 +03:00
|
|
|
class AuthMethods:
|
2018-06-10 13:57:36 +03:00
|
|
|
|
|
|
|
# region Public methods
|
|
|
|
|
2018-06-25 14:42:29 +03:00
|
|
|
def start(
|
2019-05-03 22:37:27 +03:00
|
|
|
self: 'TelegramClient',
|
|
|
|
phone: typing.Callable[[], str] = lambda: input('Please enter your phone (or bot token): '),
|
|
|
|
password: typing.Callable[[], str] = lambda: getpass.getpass('Please enter your password: '),
|
2018-06-27 14:05:19 +03:00
|
|
|
*,
|
2019-05-03 22:37:27 +03:00
|
|
|
bot_token: str = None,
|
|
|
|
force_sms: bool = False,
|
|
|
|
code_callback: typing.Callable[[], typing.Union[str, int]] = None,
|
|
|
|
first_name: str = 'New User',
|
|
|
|
last_name: str = '',
|
|
|
|
max_attempts: int = 3) -> 'TelegramClient':
|
2018-06-10 13:57:36 +03:00
|
|
|
"""
|
2019-05-06 12:38:26 +03:00
|
|
|
Starts the client (connects and logs in if necessary).
|
|
|
|
|
|
|
|
By default, this method will be interactive (asking for
|
|
|
|
user input if needed), and will handle 2FA if enabled too.
|
2018-06-10 13:57:36 +03:00
|
|
|
|
|
|
|
If the phone doesn't belong to an existing account (and will hence
|
|
|
|
`sign_up` for a new one), **you are agreeing to Telegram's
|
|
|
|
Terms of Service. This is required and your account
|
|
|
|
will be banned otherwise.** See https://telegram.org/tos
|
|
|
|
and https://core.telegram.org/api/terms.
|
|
|
|
|
2018-06-25 14:42:29 +03:00
|
|
|
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.
|
|
|
|
|
2019-05-20 12:38:26 +03:00
|
|
|
Arguments
|
2018-06-10 13:57:36 +03:00
|
|
|
phone (`str` | `int` | `callable`):
|
|
|
|
The phone (or callable without arguments to get it)
|
2018-07-10 11:21:15 +03:00
|
|
|
to which the code will be sent. If a bot-token-like
|
|
|
|
string is given, it will be used as such instead.
|
2018-09-09 17:17:20 +03:00
|
|
|
The argument may be a coroutine.
|
2018-06-10 13:57:36 +03:00
|
|
|
|
2018-09-09 17:17:20 +03:00
|
|
|
password (`str`, `callable`, optional):
|
2018-06-10 13:57:36 +03:00
|
|
|
The password for 2 Factor Authentication (2FA).
|
|
|
|
This is only required if it is enabled in your account.
|
2018-09-09 17:17:20 +03:00
|
|
|
The argument may be a coroutine.
|
2018-06-10 13:57:36 +03:00
|
|
|
|
|
|
|
bot_token (`str`):
|
|
|
|
Bot Token obtained by `@BotFather <https://t.me/BotFather>`_
|
|
|
|
to log in as a bot. Cannot be specified with ``phone`` (only
|
|
|
|
one of either allowed).
|
|
|
|
|
|
|
|
force_sms (`bool`, optional):
|
|
|
|
Whether to force sending the code request as SMS.
|
|
|
|
This only makes sense when signing in with a `phone`.
|
|
|
|
|
|
|
|
code_callback (`callable`, optional):
|
|
|
|
A callable that will be used to retrieve the Telegram
|
|
|
|
login code. Defaults to `input()`.
|
2018-09-09 17:17:20 +03:00
|
|
|
The argument may be a coroutine.
|
2018-06-10 13:57:36 +03:00
|
|
|
|
|
|
|
first_name (`str`, optional):
|
|
|
|
The first name to be used if signing up. This has no
|
|
|
|
effect if the account already exists and you sign in.
|
|
|
|
|
|
|
|
last_name (`str`, optional):
|
|
|
|
Similar to the first name, but for the last. Optional.
|
|
|
|
|
2018-06-17 15:07:45 +03:00
|
|
|
max_attempts (`int`, optional):
|
|
|
|
How many times the code/password callback should be
|
|
|
|
retried or switching between signing in and signing up.
|
|
|
|
|
2019-05-20 12:38:26 +03:00
|
|
|
Returns
|
2018-06-10 13:57:36 +03:00
|
|
|
This `TelegramClient`, so initialization
|
|
|
|
can be chained with ``.start()``.
|
2019-05-09 13:24:37 +03:00
|
|
|
|
2019-05-20 12:38:26 +03:00
|
|
|
Example
|
2019-05-09 13:24:37 +03:00
|
|
|
.. code-block:: python
|
|
|
|
|
|
|
|
client = TelegramClient('anon', api_id, api_hash)
|
|
|
|
|
|
|
|
# Starting as a bot account
|
2019-08-14 00:33:39 +03:00
|
|
|
await client.start(bot_token=bot_token)
|
2019-05-09 13:24:37 +03:00
|
|
|
|
|
|
|
# Starting as an user account
|
2019-08-14 00:33:39 +03:00
|
|
|
await client.start(phone)
|
2019-05-09 13:24:37 +03:00
|
|
|
# Please enter the code you received: 12345
|
|
|
|
# Please enter your password: *******
|
|
|
|
# (You are now logged in)
|
|
|
|
|
|
|
|
# Starting using a context manager (this calls start()):
|
|
|
|
with client:
|
|
|
|
pass
|
2018-06-10 13:57:36 +03:00
|
|
|
"""
|
|
|
|
if code_callback is None:
|
|
|
|
def code_callback():
|
|
|
|
return input('Please enter the code you received: ')
|
|
|
|
elif not callable(code_callback):
|
|
|
|
raise ValueError(
|
|
|
|
'The code_callback parameter needs to be a callable '
|
|
|
|
'function that returns the code you received by Telegram.'
|
|
|
|
)
|
|
|
|
|
|
|
|
if not phone and not bot_token:
|
|
|
|
raise ValueError('No phone number or bot token provided.')
|
|
|
|
|
|
|
|
if phone and bot_token and not callable(phone):
|
|
|
|
raise ValueError('Both a phone and a bot token provided, '
|
|
|
|
'must only provide one of either')
|
|
|
|
|
2018-06-25 14:42:29 +03:00
|
|
|
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(
|
2019-08-16 20:19:42 +03:00
|
|
|
self: 'TelegramClient', phone, password, bot_token, force_sms,
|
2018-06-25 14:42:29 +03:00
|
|
|
code_callback, first_name, last_name, max_attempts):
|
2018-06-10 13:57:36 +03:00
|
|
|
if not self.is_connected():
|
|
|
|
await self.connect()
|
|
|
|
|
|
|
|
if await self.is_user_authorized():
|
|
|
|
return self
|
|
|
|
|
2018-07-10 11:21:15 +03:00
|
|
|
if not bot_token:
|
|
|
|
# Turn the callable into a valid phone number (or bot token)
|
|
|
|
while callable(phone):
|
|
|
|
value = phone()
|
2018-09-09 17:17:20 +03:00
|
|
|
if inspect.isawaitable(value):
|
|
|
|
value = await value
|
|
|
|
|
2018-07-10 11:21:15 +03:00
|
|
|
if ':' in value:
|
|
|
|
# Bot tokens have 'user_id:access_hash' format
|
|
|
|
bot_token = value
|
|
|
|
break
|
|
|
|
|
|
|
|
phone = utils.parse_phone(value) or phone
|
|
|
|
|
2018-06-10 13:57:36 +03:00
|
|
|
if bot_token:
|
|
|
|
await self.sign_in(bot_token=bot_token)
|
|
|
|
return self
|
|
|
|
|
|
|
|
me = None
|
|
|
|
attempts = 0
|
|
|
|
two_step_detected = False
|
|
|
|
|
2019-08-16 20:19:42 +03:00
|
|
|
await self.send_code_request(phone, force_sms=force_sms)
|
|
|
|
sign_up = False # assume login
|
2018-06-10 13:57:36 +03:00
|
|
|
while attempts < max_attempts:
|
|
|
|
try:
|
2018-09-09 17:17:20 +03:00
|
|
|
value = code_callback()
|
|
|
|
if inspect.isawaitable(value):
|
|
|
|
value = await value
|
|
|
|
|
2018-10-21 17:05:31 +03:00
|
|
|
# Since sign-in with no code works (it sends the code)
|
|
|
|
# we must double-check that here. Else we'll assume we
|
|
|
|
# logged in, and it will return None as the User.
|
|
|
|
if not value:
|
|
|
|
raise errors.PhoneCodeEmptyError(request=None)
|
|
|
|
|
2018-06-10 13:57:36 +03:00
|
|
|
if sign_up:
|
2018-09-09 17:17:20 +03:00
|
|
|
me = await self.sign_up(value, first_name, last_name)
|
2018-06-10 13:57:36 +03:00
|
|
|
else:
|
|
|
|
# Raises SessionPasswordNeededError if 2FA enabled
|
2018-09-09 17:17:20 +03:00
|
|
|
me = await self.sign_in(phone, code=value)
|
2018-06-10 13:57:36 +03:00
|
|
|
break
|
|
|
|
except errors.SessionPasswordNeededError:
|
|
|
|
two_step_detected = True
|
|
|
|
break
|
|
|
|
except errors.PhoneNumberOccupiedError:
|
|
|
|
sign_up = False
|
|
|
|
except errors.PhoneNumberUnoccupiedError:
|
|
|
|
sign_up = True
|
|
|
|
except (errors.PhoneCodeEmptyError,
|
|
|
|
errors.PhoneCodeExpiredError,
|
|
|
|
errors.PhoneCodeHashEmptyError,
|
|
|
|
errors.PhoneCodeInvalidError):
|
|
|
|
print('Invalid code. Please try again.', file=sys.stderr)
|
|
|
|
|
|
|
|
attempts += 1
|
|
|
|
else:
|
|
|
|
raise RuntimeError(
|
|
|
|
'{} consecutive sign-in attempts failed. Aborting'
|
|
|
|
.format(max_attempts)
|
|
|
|
)
|
|
|
|
|
|
|
|
if two_step_detected:
|
|
|
|
if not password:
|
|
|
|
raise ValueError(
|
|
|
|
"Two-step verification is enabled for this account. "
|
|
|
|
"Please provide the 'password' argument to 'start()'."
|
|
|
|
)
|
2018-06-17 15:07:45 +03:00
|
|
|
|
2018-06-10 13:57:36 +03:00
|
|
|
if callable(password):
|
2018-06-17 15:07:45 +03:00
|
|
|
for _ in range(max_attempts):
|
|
|
|
try:
|
2018-09-09 17:17:20 +03:00
|
|
|
value = password()
|
|
|
|
if inspect.isawaitable(value):
|
|
|
|
value = await value
|
|
|
|
|
|
|
|
me = await self.sign_in(phone=phone, password=value)
|
2018-06-17 15:07:45 +03:00
|
|
|
break
|
|
|
|
except errors.PasswordHashInvalidError:
|
|
|
|
print('Invalid password. Please try again',
|
|
|
|
file=sys.stderr)
|
|
|
|
else:
|
2019-05-27 19:18:38 +03:00
|
|
|
raise errors.PasswordHashInvalidError(request=None)
|
2018-06-17 15:07:45 +03:00
|
|
|
else:
|
|
|
|
me = await self.sign_in(phone=phone, password=password)
|
2018-06-10 13:57:36 +03:00
|
|
|
|
|
|
|
# We won't reach here if any step failed (exit by exception)
|
|
|
|
signed, name = 'Signed in successfully as', utils.get_display_name(me)
|
|
|
|
try:
|
|
|
|
print(signed, name)
|
|
|
|
except UnicodeEncodeError:
|
|
|
|
# Some terminals don't support certain characters
|
|
|
|
print(signed, name.encode('utf-8', errors='ignore')
|
|
|
|
.decode('ascii', errors='ignore'))
|
|
|
|
|
|
|
|
return self
|
|
|
|
|
2019-02-12 13:44:36 +03:00
|
|
|
def _parse_phone_and_hash(self, phone, phone_hash):
|
|
|
|
"""
|
|
|
|
Helper method to both parse and validate phone and its hash.
|
|
|
|
"""
|
|
|
|
phone = utils.parse_phone(phone) or self._phone
|
|
|
|
if not phone:
|
|
|
|
raise ValueError(
|
|
|
|
'Please make sure to call send_code_request first.'
|
|
|
|
)
|
|
|
|
|
2019-02-14 09:46:57 +03:00
|
|
|
phone_hash = phone_hash or self._phone_code_hash.get(phone, None)
|
|
|
|
if not phone_hash:
|
2019-02-14 12:58:48 +03:00
|
|
|
raise ValueError('You also need to provide a phone_code_hash.')
|
2019-02-12 13:44:36 +03:00
|
|
|
|
|
|
|
return phone, phone_hash
|
|
|
|
|
2018-06-10 13:57:36 +03:00
|
|
|
async def sign_in(
|
2019-05-03 22:37:27 +03:00
|
|
|
self: 'TelegramClient',
|
|
|
|
phone: str = None,
|
|
|
|
code: typing.Union[str, int] = None,
|
|
|
|
*,
|
|
|
|
password: str = None,
|
|
|
|
bot_token: str = None,
|
2019-08-16 20:19:42 +03:00
|
|
|
phone_code_hash: str = None) -> 'typing.Union[types.User, types.auth.SentCode]':
|
2018-06-10 13:57:36 +03:00
|
|
|
"""
|
2019-05-06 12:38:26 +03:00
|
|
|
Logs in to Telegram to an existing user or bot account.
|
|
|
|
|
|
|
|
You should only use this if you are not authorized yet.
|
|
|
|
|
|
|
|
This method will send the code if it's not provided.
|
2018-06-10 13:57:36 +03:00
|
|
|
|
2019-05-26 22:11:24 +03:00
|
|
|
.. note::
|
|
|
|
|
|
|
|
In most cases, you should simply use `start()` and not this method.
|
|
|
|
|
2019-05-20 12:38:26 +03:00
|
|
|
Arguments
|
2018-06-10 13:57:36 +03:00
|
|
|
phone (`str` | `int`):
|
|
|
|
The phone to send the code to if no code was provided,
|
|
|
|
or to override the phone that was previously used with
|
|
|
|
these requests.
|
|
|
|
|
|
|
|
code (`str` | `int`):
|
|
|
|
The code that Telegram sent. Note that if you have sent this
|
|
|
|
code through the application itself it will immediately
|
|
|
|
expire. If you want to send the code, obfuscate it somehow.
|
|
|
|
If you're not doing any of this you can ignore this note.
|
|
|
|
|
|
|
|
password (`str`):
|
|
|
|
2FA password, should be used if a previous call raised
|
2019-06-11 12:09:22 +03:00
|
|
|
``SessionPasswordNeededError``.
|
2018-06-10 13:57:36 +03:00
|
|
|
|
|
|
|
bot_token (`str`):
|
|
|
|
Used to sign in as a bot. Not all requests will be available.
|
2019-06-11 12:09:22 +03:00
|
|
|
This should be the hash the `@BotFather <https://t.me/BotFather>`_
|
|
|
|
gave you.
|
2018-06-10 13:57:36 +03:00
|
|
|
|
2019-02-12 13:44:36 +03:00
|
|
|
phone_code_hash (`str`, optional):
|
|
|
|
The hash returned by `send_code_request`. This can be left as
|
2019-07-06 13:10:25 +03:00
|
|
|
`None` to use the last hash known for the phone to be used.
|
2018-06-10 13:57:36 +03:00
|
|
|
|
2019-05-20 12:38:26 +03:00
|
|
|
Returns
|
2018-06-10 13:57:36 +03:00
|
|
|
The signed in user, or the information about
|
|
|
|
:meth:`send_code_request`.
|
2019-05-20 12:38:26 +03:00
|
|
|
|
|
|
|
Example
|
|
|
|
.. code-block:: python
|
|
|
|
|
|
|
|
phone = '+34 123 123 123'
|
2019-08-14 00:33:39 +03:00
|
|
|
await client.sign_in(phone) # send code
|
2019-05-20 12:38:26 +03:00
|
|
|
|
|
|
|
code = input('enter code: ')
|
2019-08-14 00:33:39 +03:00
|
|
|
await client.sign_in(phone, code)
|
2018-06-10 13:57:36 +03:00
|
|
|
"""
|
|
|
|
me = await self.get_me()
|
|
|
|
if me:
|
|
|
|
return me
|
|
|
|
|
|
|
|
if phone and not code and not password:
|
|
|
|
return await self.send_code_request(phone)
|
|
|
|
elif code:
|
2019-02-12 13:44:36 +03:00
|
|
|
phone, phone_code_hash = \
|
|
|
|
self._parse_phone_and_hash(phone, phone_code_hash)
|
2018-06-10 13:57:36 +03:00
|
|
|
|
|
|
|
# May raise PhoneCodeEmptyError, PhoneCodeExpiredError,
|
|
|
|
# PhoneCodeHashEmptyError or PhoneCodeInvalidError.
|
2019-08-16 20:19:42 +03:00
|
|
|
request = functions.auth.SignInRequest(
|
|
|
|
phone, phone_code_hash, str(code)
|
|
|
|
)
|
2018-06-10 13:57:36 +03:00
|
|
|
elif password:
|
2018-12-24 16:10:15 +03:00
|
|
|
pwd = await self(functions.account.GetPasswordRequest())
|
2019-08-16 20:19:42 +03:00
|
|
|
request = functions.auth.CheckPasswordRequest(
|
2018-12-24 16:10:15 +03:00
|
|
|
pwd_mod.compute_check(pwd, password)
|
2019-08-16 20:19:42 +03:00
|
|
|
)
|
2018-06-10 13:57:36 +03:00
|
|
|
elif bot_token:
|
2019-08-16 20:19:42 +03:00
|
|
|
request = functions.auth.ImportBotAuthorizationRequest(
|
2018-06-10 13:57:36 +03:00
|
|
|
flags=0, bot_auth_token=bot_token,
|
|
|
|
api_id=self.api_id, api_hash=self.api_hash
|
2019-08-16 20:19:42 +03:00
|
|
|
)
|
2018-06-10 13:57:36 +03:00
|
|
|
else:
|
|
|
|
raise ValueError(
|
|
|
|
'You must provide a phone and a code the first time, '
|
|
|
|
'and a password only if an RPCError was raised before.'
|
|
|
|
)
|
|
|
|
|
2019-08-16 20:19:42 +03:00
|
|
|
result = await self(request)
|
|
|
|
if isinstance(result, types.auth.AuthorizationSignUpRequired):
|
|
|
|
# Emulate pre-layer 104 behaviour
|
|
|
|
self._tos = result.terms_of_service
|
|
|
|
raise errors.PhoneNumberUnoccupiedError(request=request)
|
|
|
|
|
2018-12-06 18:07:11 +03:00
|
|
|
return self._on_login(result.user)
|
2018-06-10 13:57:36 +03:00
|
|
|
|
2019-05-03 22:37:27 +03:00
|
|
|
async def sign_up(
|
|
|
|
self: 'TelegramClient',
|
|
|
|
code: typing.Union[str, int],
|
|
|
|
first_name: str,
|
|
|
|
last_name: str = '',
|
|
|
|
*,
|
|
|
|
phone: str = None,
|
2019-05-08 18:16:09 +03:00
|
|
|
phone_code_hash: str = None) -> 'types.User':
|
2018-06-10 13:57:36 +03:00
|
|
|
"""
|
2019-05-06 12:38:26 +03:00
|
|
|
Signs up to Telegram as a new user account.
|
|
|
|
|
|
|
|
Use this if you don't have an account yet.
|
|
|
|
|
|
|
|
You must call `send_code_request` first.
|
2018-06-10 13:57:36 +03:00
|
|
|
|
|
|
|
**By using this method you're agreeing to Telegram's
|
|
|
|
Terms of Service. This is required and your account
|
|
|
|
will be banned otherwise.** See https://telegram.org/tos
|
|
|
|
and https://core.telegram.org/api/terms.
|
|
|
|
|
2019-05-20 12:38:26 +03:00
|
|
|
Arguments
|
2018-06-10 13:57:36 +03:00
|
|
|
code (`str` | `int`):
|
|
|
|
The code sent by Telegram
|
|
|
|
|
|
|
|
first_name (`str`):
|
|
|
|
The first name to be used by the new account.
|
|
|
|
|
|
|
|
last_name (`str`, optional)
|
|
|
|
Optional last name.
|
|
|
|
|
2019-02-12 13:44:36 +03:00
|
|
|
phone (`str` | `int`, optional):
|
|
|
|
The phone to sign up. This will be the last phone used by
|
|
|
|
default (you normally don't need to set this).
|
|
|
|
|
|
|
|
phone_code_hash (`str`, optional):
|
|
|
|
The hash returned by `send_code_request`. This can be left as
|
2019-07-06 13:10:25 +03:00
|
|
|
`None` to use the last hash known for the phone to be used.
|
2019-02-12 13:44:36 +03:00
|
|
|
|
2019-05-20 12:38:26 +03:00
|
|
|
Returns
|
2018-06-10 13:57:36 +03:00
|
|
|
The new created :tl:`User`.
|
2019-05-20 12:38:26 +03:00
|
|
|
|
|
|
|
Example
|
|
|
|
.. code-block:: python
|
|
|
|
|
|
|
|
phone = '+34 123 123 123'
|
2019-08-14 00:33:39 +03:00
|
|
|
await client.send_code_request(phone)
|
2019-05-20 12:38:26 +03:00
|
|
|
|
|
|
|
code = input('enter code: ')
|
2019-08-14 00:33:39 +03:00
|
|
|
await client.sign_up(code, first_name='Anna', last_name='Banana')
|
2018-06-10 13:57:36 +03:00
|
|
|
"""
|
|
|
|
me = await self.get_me()
|
|
|
|
if me:
|
|
|
|
return me
|
|
|
|
|
|
|
|
if self._tos and self._tos.text:
|
|
|
|
if self.parse_mode:
|
|
|
|
t = self.parse_mode.unparse(self._tos.text, self._tos.entities)
|
|
|
|
else:
|
|
|
|
t = self._tos.text
|
|
|
|
sys.stderr.write("{}\n".format(t))
|
|
|
|
sys.stderr.flush()
|
|
|
|
|
2019-02-12 13:44:36 +03:00
|
|
|
phone, phone_code_hash = \
|
|
|
|
self._parse_phone_and_hash(phone, phone_code_hash)
|
|
|
|
|
2018-06-10 13:57:36 +03:00
|
|
|
result = await self(functions.auth.SignUpRequest(
|
2019-02-12 13:44:36 +03:00
|
|
|
phone_number=phone,
|
|
|
|
phone_code_hash=phone_code_hash,
|
2018-06-10 13:57:36 +03:00
|
|
|
first_name=first_name,
|
|
|
|
last_name=last_name
|
|
|
|
))
|
|
|
|
|
|
|
|
if self._tos:
|
|
|
|
await self(
|
|
|
|
functions.help.AcceptTermsOfServiceRequest(self._tos.id))
|
|
|
|
|
2018-12-06 18:07:11 +03:00
|
|
|
return self._on_login(result.user)
|
|
|
|
|
|
|
|
def _on_login(self, user):
|
|
|
|
"""
|
|
|
|
Callback called whenever the login or sign up process completes.
|
|
|
|
|
|
|
|
Returns the input user parameter.
|
|
|
|
"""
|
2018-12-24 19:32:34 +03:00
|
|
|
self._bot = bool(user.bot)
|
2018-12-06 18:07:11 +03:00
|
|
|
self._self_input_peer = utils.get_input_peer(user, allow_self=False)
|
|
|
|
self._authorized = True
|
|
|
|
|
|
|
|
return user
|
2018-06-10 13:57:36 +03:00
|
|
|
|
2019-05-03 22:37:27 +03:00
|
|
|
async def send_code_request(
|
|
|
|
self: 'TelegramClient',
|
|
|
|
phone: str,
|
|
|
|
*,
|
2019-05-08 18:16:09 +03:00
|
|
|
force_sms: bool = False) -> 'types.auth.SentCode':
|
2018-06-10 13:57:36 +03:00
|
|
|
"""
|
2019-05-06 12:38:26 +03:00
|
|
|
Sends the Telegram code needed to login to the given phone number.
|
2018-06-10 13:57:36 +03:00
|
|
|
|
2019-05-20 12:38:26 +03:00
|
|
|
Arguments
|
2018-06-10 13:57:36 +03:00
|
|
|
phone (`str` | `int`):
|
|
|
|
The phone to which the code will be sent.
|
|
|
|
|
|
|
|
force_sms (`bool`, optional):
|
|
|
|
Whether to force sending as SMS.
|
|
|
|
|
2019-05-20 12:38:26 +03:00
|
|
|
Returns
|
2018-06-10 13:57:36 +03:00
|
|
|
An instance of :tl:`SentCode`.
|
2019-05-20 12:38:26 +03:00
|
|
|
|
|
|
|
Example
|
|
|
|
.. code-block:: python
|
|
|
|
|
|
|
|
phone = '+34 123 123 123'
|
2019-08-14 00:33:39 +03:00
|
|
|
sent = await client.send_code_request(phone)
|
2019-05-20 12:38:26 +03:00
|
|
|
print(sent)
|
|
|
|
|
|
|
|
if sent.phone_registered:
|
|
|
|
print('This phone has an existing account registered')
|
|
|
|
else:
|
|
|
|
print('This phone does not have an account registered')
|
2018-06-10 13:57:36 +03:00
|
|
|
"""
|
2019-05-03 17:49:02 +03:00
|
|
|
result = None
|
2018-06-10 13:57:36 +03:00
|
|
|
phone = utils.parse_phone(phone) or self._phone
|
|
|
|
phone_hash = self._phone_code_hash.get(phone)
|
|
|
|
|
|
|
|
if not phone_hash:
|
2018-06-13 11:55:37 +03:00
|
|
|
try:
|
|
|
|
result = await self(functions.auth.SendCodeRequest(
|
2019-02-21 14:40:47 +03:00
|
|
|
phone, self.api_id, self.api_hash, types.CodeSettings()))
|
2018-06-13 11:55:37 +03:00
|
|
|
except errors.AuthRestartError:
|
2019-05-03 17:49:02 +03:00
|
|
|
return await self.send_code_request(phone, force_sms=force_sms)
|
2018-06-13 11:55:37 +03:00
|
|
|
|
2018-06-10 13:57:36 +03:00
|
|
|
self._phone_code_hash[phone] = phone_hash = result.phone_code_hash
|
|
|
|
else:
|
|
|
|
force_sms = True
|
|
|
|
|
|
|
|
self._phone = phone
|
|
|
|
|
|
|
|
if force_sms:
|
|
|
|
result = await self(
|
|
|
|
functions.auth.ResendCodeRequest(phone, phone_hash))
|
|
|
|
|
|
|
|
self._phone_code_hash[phone] = result.phone_code_hash
|
|
|
|
|
|
|
|
return result
|
|
|
|
|
2019-05-03 22:37:27 +03:00
|
|
|
async def log_out(self: 'TelegramClient') -> bool:
|
2018-06-10 13:57:36 +03:00
|
|
|
"""
|
|
|
|
Logs out Telegram and deletes the current ``*.session`` file.
|
|
|
|
|
2019-05-20 12:38:26 +03:00
|
|
|
Returns
|
2019-07-06 13:10:25 +03:00
|
|
|
`True` if the operation was successful.
|
2019-05-09 13:24:37 +03:00
|
|
|
|
2019-05-20 12:38:26 +03:00
|
|
|
Example
|
2019-05-09 13:24:37 +03:00
|
|
|
.. code-block:: python
|
|
|
|
|
|
|
|
# Note: you will need to login again!
|
2019-08-14 00:33:39 +03:00
|
|
|
await client.log_out()
|
2018-06-10 13:57:36 +03:00
|
|
|
"""
|
|
|
|
try:
|
|
|
|
await self(functions.auth.LogOutRequest())
|
|
|
|
except errors.RPCError:
|
|
|
|
return False
|
|
|
|
|
2018-12-24 19:32:34 +03:00
|
|
|
self._bot = None
|
2018-10-12 20:57:16 +03:00
|
|
|
self._self_input_peer = None
|
2018-12-06 18:07:11 +03:00
|
|
|
self._authorized = False
|
2019-04-21 14:56:14 +03:00
|
|
|
self._state_cache.reset()
|
2019-01-24 13:16:40 +03:00
|
|
|
|
2019-03-21 14:21:00 +03:00
|
|
|
await self.disconnect()
|
2018-10-12 23:00:02 +03:00
|
|
|
self.session.delete()
|
2018-06-10 13:57:36 +03:00
|
|
|
return True
|
|
|
|
|
|
|
|
async def edit_2fa(
|
2019-05-03 22:37:27 +03:00
|
|
|
self: 'TelegramClient',
|
|
|
|
current_password: str = None,
|
|
|
|
new_password: str = None,
|
|
|
|
*,
|
|
|
|
hint: str = '',
|
|
|
|
email: str = None,
|
|
|
|
email_code_callback: typing.Callable[[int], str] = None) -> bool:
|
2018-06-10 13:57:36 +03:00
|
|
|
"""
|
2019-05-06 12:38:26 +03:00
|
|
|
Changes the 2FA settings of the logged in user.
|
|
|
|
|
|
|
|
Review carefully the parameter explanations before using this method.
|
2018-06-10 13:57:36 +03:00
|
|
|
|
2018-12-24 18:02:44 +03:00
|
|
|
Note that this method may be *incredibly* slow depending on the
|
|
|
|
prime numbers that must be used during the process to make sure
|
|
|
|
that everything is safe.
|
|
|
|
|
2018-06-10 13:57:36 +03:00
|
|
|
Has no effect if both current and new password are omitted.
|
|
|
|
|
2019-05-20 12:38:26 +03:00
|
|
|
Arguments
|
|
|
|
current_password (`str`, optional):
|
|
|
|
The current password, to authorize changing to ``new_password``.
|
|
|
|
Must be set if changing existing 2FA settings.
|
|
|
|
Must **not** be set if 2FA is currently disabled.
|
|
|
|
Passing this by itself will remove 2FA (if correct).
|
|
|
|
|
|
|
|
new_password (`str`, optional):
|
|
|
|
The password to set as 2FA.
|
|
|
|
If 2FA was already enabled, ``current_password`` **must** be set.
|
2019-07-06 13:10:25 +03:00
|
|
|
Leaving this blank or `None` will remove the password.
|
2019-05-20 12:38:26 +03:00
|
|
|
|
|
|
|
hint (`str`, optional):
|
|
|
|
Hint to be displayed by Telegram when it asks for 2FA.
|
|
|
|
Leaving unspecified is highly discouraged.
|
|
|
|
Has no effect if ``new_password`` is not set.
|
|
|
|
|
|
|
|
email (`str`, optional):
|
|
|
|
Recovery and verification email. If present, you must also
|
|
|
|
set `email_code_callback`, else it raises ``ValueError``.
|
|
|
|
|
|
|
|
email_code_callback (`callable`, optional):
|
|
|
|
If an email is provided, a callback that returns the code sent
|
|
|
|
to it must also be set. This callback may be asynchronous.
|
|
|
|
It should return a string with the code. The length of the
|
|
|
|
code will be passed to the callback as an input parameter.
|
|
|
|
|
|
|
|
If the callback returns an invalid code, it will raise
|
|
|
|
``CodeInvalidError``.
|
|
|
|
|
|
|
|
Returns
|
2019-07-06 13:10:25 +03:00
|
|
|
`True` if successful, `False` otherwise.
|
2018-06-10 13:57:36 +03:00
|
|
|
|
2019-05-20 12:38:26 +03:00
|
|
|
Example
|
|
|
|
.. code-block:: python
|
2019-01-14 15:56:41 +03:00
|
|
|
|
2019-05-20 12:38:26 +03:00
|
|
|
# Setting a password for your account which didn't have
|
2019-08-14 00:33:39 +03:00
|
|
|
await client.edit_2fa(new_password='I_<3_Telethon')
|
2018-12-24 18:02:44 +03:00
|
|
|
|
2019-05-20 12:38:26 +03:00
|
|
|
# Removing the password
|
2019-08-14 00:33:39 +03:00
|
|
|
await client.edit_2fa(current_password='I_<3_Telethon')
|
2018-06-10 13:57:36 +03:00
|
|
|
"""
|
|
|
|
if new_password is None and current_password is None:
|
|
|
|
return False
|
|
|
|
|
2019-01-14 15:56:41 +03:00
|
|
|
if email and not callable(email_code_callback):
|
|
|
|
raise ValueError('email present without email_code_callback')
|
|
|
|
|
2018-12-24 18:02:44 +03:00
|
|
|
pwd = await self(functions.account.GetPasswordRequest())
|
2018-12-24 23:16:09 +03:00
|
|
|
pwd.new_algo.salt1 += os.urandom(32)
|
2018-12-24 18:02:44 +03:00
|
|
|
assert isinstance(pwd, types.account.Password)
|
|
|
|
if not pwd.has_password and current_password:
|
2018-06-10 13:57:36 +03:00
|
|
|
current_password = None
|
|
|
|
|
2018-12-24 18:02:44 +03:00
|
|
|
if current_password:
|
|
|
|
password = pwd_mod.compute_check(pwd, current_password)
|
2018-06-10 13:57:36 +03:00
|
|
|
else:
|
2018-12-24 18:02:44 +03:00
|
|
|
password = types.InputCheckPasswordEmpty()
|
|
|
|
|
|
|
|
if new_password:
|
|
|
|
new_password_hash = pwd_mod.compute_digest(
|
|
|
|
pwd.new_algo, new_password)
|
|
|
|
else:
|
|
|
|
new_password_hash = b''
|
2018-06-10 13:57:36 +03:00
|
|
|
|
2019-01-14 15:56:41 +03:00
|
|
|
try:
|
|
|
|
await self(functions.account.UpdatePasswordSettingsRequest(
|
|
|
|
password=password,
|
|
|
|
new_settings=types.account.PasswordInputSettings(
|
|
|
|
new_algo=pwd.new_algo,
|
|
|
|
new_password_hash=new_password_hash,
|
|
|
|
hint=hint,
|
|
|
|
email=email,
|
|
|
|
new_secure_settings=None
|
|
|
|
)
|
|
|
|
))
|
|
|
|
except errors.EmailUnconfirmedError as e:
|
|
|
|
code = email_code_callback(e.code_length)
|
|
|
|
if inspect.isawaitable(code):
|
|
|
|
code = await code
|
|
|
|
|
|
|
|
code = str(code)
|
|
|
|
await self(functions.account.ConfirmPasswordEmailRequest(code))
|
|
|
|
|
|
|
|
return True
|
2018-06-10 13:57:36 +03:00
|
|
|
|
|
|
|
# endregion
|
2018-06-26 12:26:01 +03:00
|
|
|
|
|
|
|
# region with blocks
|
|
|
|
|
|
|
|
async def __aenter__(self):
|
|
|
|
return await self.start()
|
|
|
|
|
|
|
|
async def __aexit__(self, *args):
|
2019-03-21 14:21:00 +03:00
|
|
|
await self.disconnect()
|
2018-06-26 12:26:01 +03:00
|
|
|
|
2019-04-13 11:53:33 +03:00
|
|
|
__enter__ = helpers._sync_enter
|
|
|
|
__exit__ = helpers._sync_exit
|
|
|
|
|
2018-06-26 12:26:01 +03:00
|
|
|
# endregion
|