0
# Authentication & Sessions
1
2
User and bot authentication, session management, two-factor authentication, and QR code login functionality for Telethon clients.
3
4
## Capabilities
5
6
### User Authentication
7
8
Sign in existing users with phone number and verification code, including support for two-factor authentication.
9
10
```python { .api }
11
async def sign_in(
12
self,
13
phone: str = None,
14
code: Union[str, int] = None,
15
*,
16
password: str = None,
17
bot_token: str = None,
18
phone_code_hash: str = None
19
) -> Union[types.User, types.auth.SentCode]:
20
"""
21
Sign in to Telegram with phone/code or bot token.
22
23
Parameters:
24
- phone: Phone number in international format
25
- code: Verification code received via SMS/app
26
- password: Password for two-factor authentication
27
- bot_token: Bot token for bot authentication
28
- phone_code_hash: Hash from send_code_request (auto-managed)
29
30
Returns:
31
User object if successful, SentCode if more steps needed
32
33
Raises:
34
- SessionPasswordNeededError: If 2FA password required
35
- PhoneCodeInvalidError: If verification code is invalid
36
- FloodWaitError: If rate limited
37
"""
38
```
39
40
### User Registration
41
42
Register new users with verification code, first name, and optional last name.
43
44
```python { .api }
45
async def sign_up(
46
self,
47
code: Union[str, int],
48
first_name: str,
49
last_name: str = '',
50
*,
51
phone: str = None,
52
phone_code_hash: str = None
53
) -> types.User:
54
"""
55
Register a new user account.
56
57
Parameters:
58
- code: Verification code received via SMS/app
59
- first_name: User's first name (required)
60
- last_name: User's last name (optional)
61
- phone: Phone number (auto-managed if not provided)
62
- phone_code_hash: Hash from send_code_request (auto-managed)
63
64
Returns:
65
User object of the newly created account
66
67
Raises:
68
- PhoneCodeInvalidError: If verification code is invalid
69
- FirstnameInvalidError: If first name is invalid
70
"""
71
```
72
73
### Verification Code Request
74
75
Request verification codes for phone number authentication.
76
77
```python { .api }
78
async def send_code_request(
79
self,
80
phone: str,
81
*,
82
force_sms: bool = False
83
) -> types.auth.SentCode:
84
"""
85
Request verification code for phone number.
86
87
Parameters:
88
- phone: Phone number in international format (e.g., '+1234567890')
89
- force_sms: Force SMS delivery instead of Telegram app
90
91
Returns:
92
SentCode object with code delivery information
93
94
Raises:
95
- PhoneNumberInvalidError: If phone number format is invalid
96
- FloodWaitError: If too many requests made recently
97
"""
98
```
99
100
### QR Code Login
101
102
Modern QR code-based login for user accounts without phone number entry.
103
104
```python { .api }
105
async def qr_login(self, ignored_ids: List[int] = None) -> custom.QRLogin:
106
"""
107
Initialize QR code login process.
108
109
Parameters:
110
- ignored_ids: List of authorization IDs to ignore
111
112
Returns:
113
QRLogin object for managing the QR login process
114
115
Usage:
116
async with client.qr_login() as qr_login:
117
print(qr_login.url) # Display QR code for this URL
118
await qr_login.wait() # Wait for user to scan
119
"""
120
```
121
122
### Session Termination
123
124
Log out and terminate the current session.
125
126
```python { .api }
127
async def log_out(self) -> bool:
128
"""
129
Log out the current user and terminate the session.
130
131
Returns:
132
bool: True if logout successful, False otherwise
133
134
Note:
135
This invalidates the current session and requires re-authentication
136
"""
137
```
138
139
### Two-Factor Authentication
140
141
Manage two-factor authentication settings for enhanced account security.
142
143
```python { .api }
144
async def edit_2fa(
145
self,
146
current_password: str = None,
147
new_password: str = None,
148
*,
149
hint: str = '',
150
email: str = None,
151
email_code_callback: Callable[[int], str] = None
152
) -> bool:
153
"""
154
Enable, disable, or modify two-factor authentication.
155
156
Parameters:
157
- current_password: Current 2FA password (if enabled)
158
- new_password: New password to set (None to disable)
159
- hint: Password hint for users
160
- email: Recovery email address
161
- email_code_callback: Callback to get email verification code
162
163
Returns:
164
bool: True if 2FA settings updated successfully
165
166
Raises:
167
- PasswordHashInvalidError: If current password is wrong
168
- EmailUnconfirmedError: If email verification required
169
"""
170
```
171
172
### Session Types
173
174
Different session storage backends for client state persistence.
175
176
```python { .api }
177
class StringSession:
178
"""
179
Session stored as a base64-encoded string.
180
Useful for serverless environments or when persistence is handled elsewhere.
181
"""
182
def __init__(self, session: str = None):
183
"""
184
Initialize string session.
185
186
Parameters:
187
- session: Previously saved session string (None for new session)
188
"""
189
190
def save(self) -> str:
191
"""
192
Get the session as a string for storage.
193
194
Returns:
195
str: Base64-encoded session data
196
"""
197
198
class SQLiteSession:
199
"""
200
Session stored in SQLite database (default).
201
Provides persistent storage with caching for entities and files.
202
"""
203
def __init__(self, session_id: str):
204
"""
205
Initialize SQLite session.
206
207
Parameters:
208
- session_id: Session identifier (creates session_id.session file)
209
"""
210
211
class MemorySession:
212
"""
213
Session stored in memory only.
214
Lost when process ends, useful for temporary operations.
215
"""
216
def __init__(self):
217
"""Initialize memory-only session."""
218
```
219
220
### Session Management
221
222
Control session behavior and state.
223
224
```python { .api }
225
def clone(self, to_instance=None) -> Session:
226
"""
227
Clone the current session.
228
229
Parameters:
230
- to_instance: Target session instance to clone to
231
232
Returns:
233
Session: Cloned session instance
234
"""
235
236
def save(self) -> None:
237
"""Save current session state to storage."""
238
239
def close(self) -> None:
240
"""Close and clean up session resources."""
241
242
def set_dc(self, dc_id: int, server_address: str, port: int) -> None:
243
"""
244
Set datacenter information.
245
246
Parameters:
247
- dc_id: Datacenter ID (1-5)
248
- server_address: Server IP address
249
- port: Server port number
250
"""
251
```
252
253
## Usage Examples
254
255
### Basic User Authentication
256
257
```python
258
import asyncio
259
from telethon import TelegramClient
260
261
async def authenticate_user():
262
client = TelegramClient('user_session', api_id, api_hash)
263
await client.connect()
264
265
if not await client.is_user_authorized():
266
# Request verification code
267
phone = input('Enter your phone number: ')
268
await client.send_code_request(phone)
269
270
# Enter the code
271
code = input('Enter the verification code: ')
272
273
try:
274
await client.sign_in(phone, code)
275
except SessionPasswordNeededError:
276
# 2FA is enabled
277
password = input('Enter your 2FA password: ')
278
await client.sign_in(password=password)
279
280
print("Authentication successful!")
281
await client.disconnect()
282
283
asyncio.run(authenticate_user())
284
```
285
286
### Bot Authentication
287
288
```python
289
async def authenticate_bot():
290
client = TelegramClient('bot_session', api_id, api_hash)
291
await client.connect()
292
293
# Bot authentication is simpler
294
bot_token = 'your_bot_token_here'
295
await client.sign_in(bot_token=bot_token)
296
297
print("Bot authenticated successfully!")
298
299
# Verify it's a bot
300
if await client.is_bot():
301
me = await client.get_me()
302
print(f"Bot username: @{me.username}")
303
304
await client.disconnect()
305
```
306
307
### QR Code Login
308
309
```python
310
import qrcode
311
from io import BytesIO
312
313
async def qr_login():
314
client = TelegramClient('qr_session', api_id, api_hash)
315
await client.connect()
316
317
# Start QR login process
318
async with client.qr_login() as qr_login:
319
# Generate QR code
320
qr = qrcode.QRCode()
321
qr.add_data(qr_login.url)
322
qr.make()
323
324
# Display QR code (this is a simple text version)
325
qr.print_ascii(invert=True)
326
print(f"QR URL: {qr_login.url}")
327
print("Scan this QR code with your Telegram app")
328
329
# Wait for user to scan and authorize
330
try:
331
await qr_login.wait()
332
print("QR login successful!")
333
except TimeoutError:
334
print("QR login timed out")
335
336
await client.disconnect()
337
```
338
339
### String Session Usage
340
341
```python
342
from telethon.sessions import StringSession
343
344
async def use_string_session():
345
# Load from existing session string
346
session_string = "your_saved_session_string_here"
347
348
client = TelegramClient(
349
StringSession(session_string),
350
api_id,
351
api_hash
352
)
353
354
await client.connect()
355
356
# Use client normally
357
me = await client.get_me()
358
print(f"Connected as {me.first_name}")
359
360
# Save session string for next time
361
saved_session = client.session.save()
362
print(f"Save this for next time: {saved_session}")
363
364
await client.disconnect()
365
```
366
367
### Managing 2FA
368
369
```python
370
async def setup_2fa():
371
client = TelegramClient('session', api_id, api_hash)
372
await client.start()
373
374
# Enable 2FA
375
password = "my_secure_password"
376
hint = "My favorite password"
377
email = "recovery@example.com"
378
379
def email_code_callback(length):
380
return input(f'Enter the {length}-digit code sent to your email: ')
381
382
success = await client.edit_2fa(
383
new_password=password,
384
hint=hint,
385
email=email,
386
email_code_callback=email_code_callback
387
)
388
389
if success:
390
print("2FA enabled successfully!")
391
392
await client.disconnect()
393
```
394
395
## Types
396
397
```python { .api }
398
from typing import Union, List, Optional, Callable, Any
399
from telethon.tl import types
400
from telethon import custom
401
402
PhoneNumber = str # International format, e.g., '+1234567890'
403
VerificationCode = Union[str, int]
404
Password = str
405
BotToken = str
406
EmailCallback = Callable[[int], str]
407
```