forked from pyrogram/pyrogram
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.py
More file actions
2151 lines (1695 loc) · 78 KB
/
client.py
File metadata and controls
2151 lines (1695 loc) · 78 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Pyrogram - Telegram MTProto API Client Library for Python
# Copyright (C) 2017-2020 Dan <https://github.com/delivrance>
#
# This file is part of Pyrogram.
#
# Pyrogram is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Pyrogram is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with Pyrogram. If not, see <http://www.gnu.org/licenses/>.
import asyncio
import io
import logging
import math
import os
import re
import shutil
import tempfile
from configparser import ConfigParser
from hashlib import sha256, md5
from importlib import import_module
from pathlib import Path, PurePath
from signal import signal, SIGINT, SIGTERM, SIGABRT
from typing import Union, List, BinaryIO
from pyrogram.api import functions, types
from pyrogram.api.core import TLObject
from pyrogram.client.handlers import DisconnectHandler
from pyrogram.client.handlers.handler import Handler
from pyrogram.client.methods.password.utils import compute_check
from pyrogram.crypto import AES
from pyrogram.errors import (
PhoneMigrate, NetworkMigrate, SessionPasswordNeeded,
PeerIdInvalid, VolumeLocNotFound, UserMigrate, ChannelPrivate,
AuthBytesInvalid, BadRequest
)
from pyrogram.session import Auth, Session
from .ext import utils, Syncer, BaseClient, Dispatcher
from .ext.utils import ainput
from .methods import Methods
from .storage import Storage, FileStorage, MemoryStorage
from .types import User, SentCode, TermsOfService
log = logging.getLogger(__name__)
class Client(Methods, BaseClient):
"""Pyrogram Client, the main means for interacting with Telegram.
Parameters:
session_name (``str``):
Pass a string of your choice to give a name to the client session, e.g.: "*my_account*". This name will be
used to save a file on disk that stores details needed to reconnect without asking again for credentials.
Alternatively, if you don't want a file to be saved on disk, pass the special name "**:memory:**" to start
an in-memory session that will be discarded as soon as you stop the Client. In order to reconnect again
using a memory storage without having to login again, you can use
:meth:`~pyrogram.Client.export_session_string` before stopping the client to get a session string you can
pass here as argument.
api_id (``int`` | ``str``, *optional*):
The *api_id* part of your Telegram API Key, as integer. E.g.: "12345".
This is an alternative way to pass it if you don't want to use the *config.ini* file.
api_hash (``str``, *optional*):
The *api_hash* part of your Telegram API Key, as string. E.g.: "0123456789abcdef0123456789abcdef".
This is an alternative way to set it if you don't want to use the *config.ini* file.
app_version (``str``, *optional*):
Application version. Defaults to "Pyrogram |version|".
This is an alternative way to set it if you don't want to use the *config.ini* file.
device_model (``str``, *optional*):
Device model. Defaults to *platform.python_implementation() + " " + platform.python_version()*.
This is an alternative way to set it if you don't want to use the *config.ini* file.
system_version (``str``, *optional*):
Operating System version. Defaults to *platform.system() + " " + platform.release()*.
This is an alternative way to set it if you don't want to use the *config.ini* file.
lang_code (``str``, *optional*):
Code of the language used on the client, in ISO 639-1 standard. Defaults to "en".
This is an alternative way to set it if you don't want to use the *config.ini* file.
ipv6 (``bool``, *optional*):
Pass True to connect to Telegram using IPv6.
Defaults to False (IPv4).
proxy (``dict``, *optional*):
Your SOCKS5 Proxy settings as dict,
e.g.: *dict(hostname="11.22.33.44", port=1080, username="user", password="pass")*.
The *username* and *password* can be omitted if your proxy doesn't require authorization.
This is an alternative way to setup a proxy if you don't want to use the *config.ini* file.
test_mode (``bool``, *optional*):
Enable or disable login to the test servers.
Only applicable for new sessions and will be ignored in case previously created sessions are loaded.
Defaults to False.
bot_token (``str``, *optional*):
Pass your Bot API token to create a bot session, e.g.: "123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11"
Only applicable for new sessions.
This is an alternative way to set it if you don't want to use the *config.ini* file.
phone_number (``str``, *optional*):
Pass your phone number as string (with your Country Code prefix included) to avoid entering it manually.
Only applicable for new sessions.
phone_code (``str``, *optional*):
Pass the phone code as string (for test numbers only) to avoid entering it manually.
Only applicable for new sessions.
password (``str``, *optional*):
Pass your Two-Step Verification password as string (if you have one) to avoid entering it manually.
Only applicable for new sessions.
force_sms (``bool``, *optional*):
Pass True to force Telegram sending the authorization code via SMS.
Only applicable for new sessions.
Defaults to False.
workers (``int``, *optional*):
Number of maximum concurrent workers for handling incoming updates.
Defaults to 4.
workdir (``str``, *optional*):
Define a custom working directory. The working directory is the location in your filesystem where Pyrogram
will store your session files.
Defaults to the parent directory of the main script.
config_file (``str``, *optional*):
Path of the configuration file.
Defaults to ./config.ini
plugins (``dict``, *optional*):
Your Smart Plugins settings as dict, e.g.: *dict(root="plugins")*.
This is an alternative way to setup plugins if you don't want to use the *config.ini* file.
parse_mode (``str``, *optional*):
The parse mode, can be any of: *"combined"*, for the default combined mode. *"markdown"* or *"md"*
to force Markdown-only styles. *"html"* to force HTML-only styles. *None* to disable the parser
completely.
no_updates (``bool``, *optional*):
Pass True to completely disable incoming updates for the current session.
When updates are disabled your client can't receive any new message.
Useful for batch programs that don't need to deal with updates.
Defaults to False (updates enabled and always received).
takeout (``bool``, *optional*):
Pass True to let the client use a takeout session instead of a normal one, implies *no_updates=True*.
Useful for exporting your Telegram data. Methods invoked inside a takeout session (such as get_history,
download_media, ...) are less prone to throw FloodWait exceptions.
Only available for users, bots will ignore this parameter.
Defaults to False (normal session).
sleep_threshold (``int``, *optional*):
Set a sleep threshold for flood wait exceptions happening globally in this client instance, below which any
request that raises a flood wait will be automatically invoked again after sleeping for the required amount
of time. Flood wait exceptions requiring higher waiting times will be raised.
Defaults to 60 (seconds).
"""
def __init__(
self,
session_name: Union[str, Storage],
api_id: Union[int, str] = None,
api_hash: str = None,
app_version: str = None,
device_model: str = None,
system_version: str = None,
lang_code: str = None,
ipv6: bool = False,
proxy: dict = None,
test_mode: bool = False,
bot_token: str = None,
phone_number: str = None,
phone_code: str = None,
password: str = None,
force_sms: bool = False,
workers: int = BaseClient.WORKERS,
workdir: str = BaseClient.WORKDIR,
config_file: str = BaseClient.CONFIG_FILE,
plugins: dict = None,
parse_mode: str = BaseClient.PARSE_MODES[0],
no_updates: bool = None,
takeout: bool = None,
sleep_threshold: int = Session.SLEEP_THRESHOLD
):
super().__init__()
self.session_name = session_name
self.api_id = int(api_id) if api_id else None
self.api_hash = api_hash
self.app_version = app_version
self.device_model = device_model
self.system_version = system_version
self.lang_code = lang_code
self.ipv6 = ipv6
# TODO: Make code consistent, use underscore for private/protected fields
self._proxy = proxy
self.test_mode = test_mode
self.bot_token = bot_token
self.phone_number = phone_number
self.phone_code = phone_code
self.password = password
self.force_sms = force_sms
self.workers = workers
self.workdir = Path(workdir)
self.config_file = Path(config_file)
self.plugins = plugins
self.parse_mode = parse_mode
self.no_updates = no_updates
self.takeout = takeout
self.sleep_threshold = sleep_threshold
if isinstance(session_name, str):
if session_name == ":memory:" or len(session_name) >= MemoryStorage.SESSION_STRING_SIZE:
session_name = re.sub(r"[\n\s]+", "", session_name)
self.storage = MemoryStorage(session_name)
else:
self.storage = FileStorage(session_name, self.workdir)
elif isinstance(session_name, Storage):
self.storage = session_name
else:
raise ValueError("Unknown storage engine")
self.dispatcher = Dispatcher(self, 0 if no_updates else workers)
def __enter__(self):
return self.start()
def __exit__(self, *args):
try:
self.stop()
except ConnectionError:
pass
async def __aenter__(self):
return await self.start()
async def __aexit__(self, *args):
await self.stop()
@property
def proxy(self):
return self._proxy
@proxy.setter
def proxy(self, value):
if value is None:
self._proxy = None
return
if self._proxy is None:
self._proxy = {}
self._proxy["enabled"] = bool(value.get("enabled", True))
self._proxy.update(value)
async def connect(self) -> bool:
"""
Connect the client to Telegram servers.
Returns:
``bool``: On success, in case the passed-in session is authorized, True is returned. Otherwise, in case
the session needs to be authorized, False is returned.
Raises:
ConnectionError: In case you try to connect an already connected client.
"""
if self.is_connected:
raise ConnectionError("Client is already connected")
self.load_config()
await self.load_session()
self.session = Session(self, self.storage.dc_id(), self.storage.auth_key())
await self.session.start()
self.is_connected = True
return bool(self.storage.user_id())
async def disconnect(self):
"""Disconnect the client from Telegram servers.
Raises:
ConnectionError: In case you try to disconnect an already disconnected client or in case you try to
disconnect a client that needs to be terminated first.
"""
if not self.is_connected:
raise ConnectionError("Client is already disconnected")
if self.is_initialized:
raise ConnectionError("Can't disconnect an initialized client")
await self.session.stop()
self.storage.close()
self.is_connected = False
async def initialize(self):
"""Initialize the client by starting up workers.
This method will start updates and download workers.
It will also load plugins and start the internal dispatcher.
Raises:
ConnectionError: In case you try to initialize a disconnected client or in case you try to initialize an
already initialized client.
"""
if not self.is_connected:
raise ConnectionError("Can't initialize a disconnected client")
if self.is_initialized:
raise ConnectionError("Client is already initialized")
self.load_plugins()
if not self.no_updates:
for _ in range(Client.UPDATES_WORKERS):
self.updates_worker_tasks.append(
asyncio.ensure_future(self.updates_worker())
)
logging.info("Started {} UpdatesWorkerTasks".format(Client.UPDATES_WORKERS))
for _ in range(Client.DOWNLOAD_WORKERS):
self.download_worker_tasks.append(
asyncio.ensure_future(self.download_worker())
)
logging.info("Started {} DownloadWorkerTasks".format(Client.DOWNLOAD_WORKERS))
await self.dispatcher.start()
await Syncer.add(self)
self.is_initialized = True
async def terminate(self):
"""Terminate the client by shutting down workers.
This method does the opposite of :meth:`~Client.initialize`.
It will stop the dispatcher and shut down updates and download workers.
Raises:
ConnectionError: In case you try to terminate a client that is already terminated.
"""
if not self.is_initialized:
raise ConnectionError("Client is already terminated")
if self.takeout_id:
await self.send(functions.account.FinishTakeoutSession())
log.warning("Takeout session {} finished".format(self.takeout_id))
await Syncer.remove(self)
await self.dispatcher.stop()
for _ in range(Client.DOWNLOAD_WORKERS):
self.download_queue.put_nowait(None)
for task in self.download_worker_tasks:
await task
self.download_worker_tasks.clear()
logging.info("Stopped {} DownloadWorkerTasks".format(Client.DOWNLOAD_WORKERS))
if not self.no_updates:
for _ in range(Client.UPDATES_WORKERS):
self.updates_queue.put_nowait(None)
for task in self.updates_worker_tasks:
await task
self.updates_worker_tasks.clear()
logging.info("Stopped {} UpdatesWorkerTasks".format(Client.UPDATES_WORKERS))
for media_session in self.media_sessions.values():
await media_session.stop()
self.media_sessions.clear()
self.is_initialized = False
async def send_code(self, phone_number: str) -> SentCode:
"""Send the confirmation code to the given phone number.
Parameters:
phone_number (``str``):
Phone number in international format (includes the country prefix).
Returns:
:obj:`SentCode`: On success, an object containing information on the sent confirmation code is returned.
Raises:
BadRequest: In case the phone number is invalid.
"""
phone_number = phone_number.strip(" +")
while True:
try:
r = await self.send(
functions.auth.SendCode(
phone_number=phone_number,
api_id=self.api_id,
api_hash=self.api_hash,
settings=types.CodeSettings()
)
)
except (PhoneMigrate, NetworkMigrate) as e:
await self.session.stop()
self.storage.dc_id(e.x)
self.storage.auth_key(await Auth(self, self.storage.dc_id()).create())
self.session = Session(self, self.storage.dc_id(), self.storage.auth_key())
await self.session.start()
else:
return SentCode._parse(r)
async def resend_code(self, phone_number: str, phone_code_hash: str) -> SentCode:
"""Re-send the confirmation code using a different type.
The type of the code to be re-sent is specified in the *next_type* attribute of the :obj:`SentCode` object
returned by :meth:`send_code`.
Parameters:
phone_number (``str``):
Phone number in international format (includes the country prefix).
phone_code_hash (``str``):
Confirmation code identifier.
Returns:
:obj:`SentCode`: On success, an object containing information on the re-sent confirmation code is returned.
Raises:
BadRequest: In case the arguments are invalid.
"""
phone_number = phone_number.strip(" +")
r = await self.send(
functions.auth.ResendCode(
phone_number=phone_number,
phone_code_hash=phone_code_hash
)
)
return SentCode._parse(r)
async def sign_in(self, phone_number: str, phone_code_hash: str, phone_code: str) -> Union[
User, TermsOfService, bool]:
"""Authorize a user in Telegram with a valid confirmation code.
Parameters:
phone_number (``str``):
Phone number in international format (includes the country prefix).
phone_code_hash (``str``):
Code identifier taken from the result of :meth:`~Client.send_code`.
phone_code (``str``):
The valid confirmation code you received (either as Telegram message or as SMS in your phone number).
Returns:
:obj:`User` | :obj:`TermsOfService` | bool: On success, in case the authorization completed, the user is
returned. In case the phone number needs to be registered first AND the terms of services accepted (with
:meth:`~Client.accept_terms_of_service`), an object containing them is returned. In case the phone number
needs to be registered, but the terms of services don't need to be accepted, False is returned instead.
Raises:
BadRequest: In case the arguments are invalid.
SessionPasswordNeeded: In case a password is needed to sign in.
"""
phone_number = phone_number.strip(" +")
r = await self.send(
functions.auth.SignIn(
phone_number=phone_number,
phone_code_hash=phone_code_hash,
phone_code=phone_code
)
)
if isinstance(r, types.auth.AuthorizationSignUpRequired):
if r.terms_of_service:
return TermsOfService._parse(terms_of_service=r.terms_of_service)
return False
else:
self.storage.user_id(r.user.id)
self.storage.is_bot(False)
return User._parse(self, r.user)
async def sign_up(self, phone_number: str, phone_code_hash: str, first_name: str, last_name: str = "") -> User:
"""Register a new user in Telegram.
Parameters:
phone_number (``str``):
Phone number in international format (includes the country prefix).
phone_code_hash (``str``):
Code identifier taken from the result of :meth:`~Client.send_code`.
first_name (``str``):
New user first name.
last_name (``str``, *optional*):
New user last name. Defaults to "" (empty string, no last name).
Returns:
:obj:`User`: On success, the new registered user is returned.
Raises:
BadRequest: In case the arguments are invalid.
"""
phone_number = phone_number.strip(" +")
r = await self.send(
functions.auth.SignUp(
phone_number=phone_number,
first_name=first_name,
last_name=last_name,
phone_code_hash=phone_code_hash
)
)
self.storage.user_id(r.user.id)
self.storage.is_bot(False)
return User._parse(self, r.user)
async def sign_in_bot(self, bot_token: str) -> User:
"""Authorize a bot using its bot token generated by BotFather.
Parameters:
bot_token (``str``):
The bot token generated by BotFather
Returns:
:obj:`User`: On success, the bot identity is return in form of a user object.
Raises:
BadRequest: In case the bot token is invalid.
"""
while True:
try:
r = await self.send(
functions.auth.ImportBotAuthorization(
flags=0,
api_id=self.api_id,
api_hash=self.api_hash,
bot_auth_token=bot_token
)
)
except UserMigrate as e:
await self.session.stop()
self.storage.dc_id(e.x)
self.storage.auth_key(await Auth(self, self.storage.dc_id()).create())
self.session = Session(self, self.storage.dc_id(), self.storage.auth_key())
await self.session.start()
else:
self.storage.user_id(r.user.id)
self.storage.is_bot(True)
return User._parse(self, r.user)
async def get_password_hint(self) -> str:
"""Get your Two-Step Verification password hint.
Returns:
``str``: On success, the password hint as string is returned.
"""
return (await self.send(functions.account.GetPassword())).hint
async def check_password(self, password: str) -> User:
"""Check your Two-Step Verification password and log in.
Parameters:
password (``str``):
Your Two-Step Verification password.
Returns:
:obj:`User`: On success, the authorized user is returned.
Raises:
BadRequest: In case the password is invalid.
"""
r = await self.send(
functions.auth.CheckPassword(
password=compute_check(
await self.send(functions.account.GetPassword()),
password
)
)
)
self.storage.user_id(r.user.id)
self.storage.is_bot(False)
return User._parse(self, r.user)
async def send_recovery_code(self) -> str:
"""Send a code to your email to recover your password.
Returns:
``str``: On success, the hidden email pattern is returned and a recovery code is sent to that email.
Raises:
BadRequest: In case no recovery email was set up.
"""
return (await self.send(
functions.auth.RequestPasswordRecovery()
)).email_pattern
async def recover_password(self, recovery_code: str) -> User:
"""Recover your password with a recovery code and log in.
Parameters:
recovery_code (``str``):
The recovery code sent via email.
Returns:
:obj:`User`: On success, the authorized user is returned and the Two-Step Verification password reset.
Raises:
BadRequest: In case the recovery code is invalid.
"""
r = await self.send(
functions.auth.RecoverPassword(
code=recovery_code
)
)
self.storage.user_id(r.user.id)
self.storage.is_bot(False)
return User._parse(self, r.user)
async def accept_terms_of_service(self, terms_of_service_id: str) -> bool:
"""Accept the given terms of service.
Parameters:
terms_of_service_id (``str``):
The terms of service identifier.
"""
r = await self.send(
functions.help.AcceptTermsOfService(
id=types.DataJSON(
data=terms_of_service_id
)
)
)
assert r
return True
async def authorize(self) -> User:
if self.bot_token:
return await self.sign_in_bot(self.bot_token)
while True:
try:
if not self.phone_number:
while True:
value = await ainput("Enter phone number or bot token: ")
if not value:
continue
confirm = input("Is \"{}\" correct? (y/N): ".format(value)).lower()
if confirm == "y":
break
if ":" in value:
self.bot_token = value
return await self.sign_in_bot(value)
else:
self.phone_number = value
sent_code = await self.send_code(self.phone_number)
except BadRequest as e:
print(e.MESSAGE)
self.phone_number = None
self.bot_token = None
else:
break
if self.force_sms:
sent_code = await self.resend_code(self.phone_number, sent_code.phone_code_hash)
print("The confirmation code has been sent via {}".format(
{
"app": "Telegram app",
"sms": "SMS",
"call": "phone call",
"flash_call": "phone flash call"
}[sent_code.type]
))
while True:
if not self.phone_code:
self.phone_code = await ainput("Enter confirmation code: ")
try:
signed_in = await self.sign_in(self.phone_number, sent_code.phone_code_hash, self.phone_code)
except BadRequest as e:
print(e.MESSAGE)
self.phone_code = None
except SessionPasswordNeeded as e:
print(e.MESSAGE)
while True:
print("Password hint: {}".format(await self.get_password_hint()))
if not self.password:
self.password = await ainput("Enter password (empty to recover): ")
try:
if not self.password:
confirm = await ainput("Confirm password recovery (y/n): ")
if confirm == "y":
email_pattern = await self.send_recovery_code()
print("The recovery code has been sent to {}".format(email_pattern))
while True:
recovery_code = await ainput("Enter recovery code: ")
try:
return await self.recover_password(recovery_code)
except BadRequest as e:
print(e.MESSAGE)
except Exception as e:
log.error(e, exc_info=True)
raise
else:
self.password = None
else:
return await self.check_password(self.password)
except BadRequest as e:
print(e.MESSAGE)
self.password = None
else:
break
if isinstance(signed_in, User):
return signed_in
while True:
first_name = await ainput("Enter first name: ")
last_name = await ainput("Enter last name (empty to skip): ")
try:
signed_up = await self.sign_up(
self.phone_number,
sent_code.phone_code_hash,
first_name,
last_name
)
except BadRequest as e:
print(e.MESSAGE)
else:
break
if isinstance(signed_in, TermsOfService):
print("\n" + signed_in.text + "\n")
await self.accept_terms_of_service(signed_in.id)
return signed_up
async def log_out(self):
"""Log out from Telegram and delete the *\\*.session* file.
When you log out, the current client is stopped and the storage session deleted.
No more API calls can be made until you start the client and re-authorize again.
Returns:
``bool``: On success, True is returned.
Example:
.. code-block:: python
# Log out.
app.log_out()
"""
await self.send(functions.auth.LogOut())
await self.stop()
self.storage.delete()
return True
async def start(self):
"""Start the client.
This method connects the client to Telegram and, in case of new sessions, automatically manages the full
authorization process using an interactive prompt.
Returns:
:obj:`Client`: The started client itself.
Raises:
ConnectionError: In case you try to start an already started client.
Example:
.. code-block:: python
:emphasize-lines: 4
from pyrogram import Client
app = Client("my_account")
app.start()
... # Call API methods
app.stop()
"""
is_authorized = await self.connect()
try:
if not is_authorized:
await self.authorize()
if not self.storage.is_bot() and self.takeout:
self.takeout_id = (await self.send(functions.account.InitTakeoutSession())).id
log.warning("Takeout session {} initiated".format(self.takeout_id))
await self.send(functions.updates.GetState())
except (Exception, KeyboardInterrupt):
await self.disconnect()
raise
else:
await self.initialize()
return self
async def stop(self, block: bool = True):
"""Stop the Client.
This method disconnects the client from Telegram and stops the underlying tasks.
Parameters:
block (``bool``, *optional*):
Blocks the code execution until the client has been restarted. It is useful with ``block=False`` in case
you want to stop the own client *within* an handler in order not to cause a deadlock.
Defaults to True.
Returns:
:obj:`Client`: The stopped client itself.
Raises:
ConnectionError: In case you try to stop an already stopped client.
Example:
.. code-block:: python
:emphasize-lines: 8
from pyrogram import Client
app = Client("my_account")
app.start()
... # Call API methods
app.stop()
"""
async def do_it():
await self.terminate()
await self.disconnect()
if block:
await do_it()
else:
asyncio.ensure_future(do_it())
return self
async def restart(self, block: bool = True):
"""Restart the Client.
This method will first call :meth:`~Client.stop` and then :meth:`~Client.start` in a row in order to restart
a client using a single method.
Parameters:
block (``bool``, *optional*):
Blocks the code execution until the client has been restarted. It is useful with ``block=False`` in case
you want to restart the own client *within* an handler in order not to cause a deadlock.
Defaults to True.
Returns:
:obj:`Client`: The restarted client itself.
Raises:
ConnectionError: In case you try to restart a stopped Client.
Example:
.. code-block:: python
:emphasize-lines: 8
from pyrogram import Client
app = Client("my_account")
app.start()
... # Call API methods
app.restart()
... # Call other API methods
app.stop()
"""
async def do_it():
await self.stop()
await self.start()
if block:
await do_it()
else:
asyncio.ensure_future(do_it())
return self
@staticmethod
async def idle(stop_signals: tuple = (SIGINT, SIGTERM, SIGABRT)):
"""Block the main script execution until a signal is received.
This static method will run an infinite loop in order to block the main script execution and prevent it from
exiting while having client(s) that are still running in the background.
It is useful for event-driven application only, that are, applications which react upon incoming Telegram
updates through handlers, rather than executing a set of methods sequentially.
The way Pyrogram works, it will keep your handlers in a pool of worker threads, which are executed concurrently
outside the main thread; calling idle() will ensure the client(s) will be kept alive by not letting the main
script to end, until you decide to quit.
Once a signal is received (e.g.: from CTRL+C) the inner infinite loop will break and your main script will
continue. Don't forget to call :meth:`~Client.stop` for each running client before the script ends.
Parameters:
stop_signals (``tuple``, *optional*):
Iterable containing signals the signal handler will listen to.
Defaults to *(SIGINT, SIGTERM, SIGABRT)*.
Example:
.. code-block:: python
:emphasize-lines: 13
from pyrogram import Client
app1 = Client("account1")
app2 = Client("account2")
app3 = Client("account3")
... # Set handlers up
app1.start()
app2.start()
app3.start()
Client.idle()
app1.stop()
app2.stop()
app3.stop()
"""
def signal_handler(_, __):
logging.info("Stop signal received ({}). Exiting...".format(_))
Client.is_idling = False
for s in stop_signals:
signal(s, signal_handler)
Client.is_idling = True
while Client.is_idling:
await asyncio.sleep(1)
def run(self, coroutine=None):
"""Start the client, idle the main script and finally stop the client.
This is a convenience method that calls :meth:`~Client.start`, :meth:`~Client.idle` and :meth:`~Client.stop` in