Full-featured Telegram client library for Python 3
—
Quality
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
User and bot authentication, session management, two-factor authentication, and QR code login functionality for Telethon clients.
Sign in existing users with phone number and verification code, including support for two-factor authentication.
async def sign_in(
self,
phone: str = None,
code: Union[str, int] = None,
*,
password: str = None,
bot_token: str = None,
phone_code_hash: str = None
) -> Union[types.User, types.auth.SentCode]:
"""
Sign in to Telegram with phone/code or bot token.
Parameters:
- phone: Phone number in international format
- code: Verification code received via SMS/app
- password: Password for two-factor authentication
- bot_token: Bot token for bot authentication
- phone_code_hash: Hash from send_code_request (auto-managed)
Returns:
User object if successful, SentCode if more steps needed
Raises:
- SessionPasswordNeededError: If 2FA password required
- PhoneCodeInvalidError: If verification code is invalid
- FloodWaitError: If rate limited
"""Register new users with verification code, first name, and optional last name.
async def sign_up(
self,
code: Union[str, int],
first_name: str,
last_name: str = '',
*,
phone: str = None,
phone_code_hash: str = None
) -> types.User:
"""
Register a new user account.
Parameters:
- code: Verification code received via SMS/app
- first_name: User's first name (required)
- last_name: User's last name (optional)
- phone: Phone number (auto-managed if not provided)
- phone_code_hash: Hash from send_code_request (auto-managed)
Returns:
User object of the newly created account
Raises:
- PhoneCodeInvalidError: If verification code is invalid
- FirstnameInvalidError: If first name is invalid
"""Request verification codes for phone number authentication.
async def send_code_request(
self,
phone: str,
*,
force_sms: bool = False
) -> types.auth.SentCode:
"""
Request verification code for phone number.
Parameters:
- phone: Phone number in international format (e.g., '+1234567890')
- force_sms: Force SMS delivery instead of Telegram app
Returns:
SentCode object with code delivery information
Raises:
- PhoneNumberInvalidError: If phone number format is invalid
- FloodWaitError: If too many requests made recently
"""Modern QR code-based login for user accounts without phone number entry.
async def qr_login(self, ignored_ids: List[int] = None) -> custom.QRLogin:
"""
Initialize QR code login process.
Parameters:
- ignored_ids: List of authorization IDs to ignore
Returns:
QRLogin object for managing the QR login process
Usage:
async with client.qr_login() as qr_login:
print(qr_login.url) # Display QR code for this URL
await qr_login.wait() # Wait for user to scan
"""Log out and terminate the current session.
async def log_out(self) -> bool:
"""
Log out the current user and terminate the session.
Returns:
bool: True if logout successful, False otherwise
Note:
This invalidates the current session and requires re-authentication
"""Manage two-factor authentication settings for enhanced account security.
async def edit_2fa(
self,
current_password: str = None,
new_password: str = None,
*,
hint: str = '',
email: str = None,
email_code_callback: Callable[[int], str] = None
) -> bool:
"""
Enable, disable, or modify two-factor authentication.
Parameters:
- current_password: Current 2FA password (if enabled)
- new_password: New password to set (None to disable)
- hint: Password hint for users
- email: Recovery email address
- email_code_callback: Callback to get email verification code
Returns:
bool: True if 2FA settings updated successfully
Raises:
- PasswordHashInvalidError: If current password is wrong
- EmailUnconfirmedError: If email verification required
"""Different session storage backends for client state persistence.
class StringSession:
"""
Session stored as a base64-encoded string.
Useful for serverless environments or when persistence is handled elsewhere.
"""
def __init__(self, session: str = None):
"""
Initialize string session.
Parameters:
- session: Previously saved session string (None for new session)
"""
def save(self) -> str:
"""
Get the session as a string for storage.
Returns:
str: Base64-encoded session data
"""
class SQLiteSession:
"""
Session stored in SQLite database (default).
Provides persistent storage with caching for entities and files.
"""
def __init__(self, session_id: str):
"""
Initialize SQLite session.
Parameters:
- session_id: Session identifier (creates session_id.session file)
"""
class MemorySession:
"""
Session stored in memory only.
Lost when process ends, useful for temporary operations.
"""
def __init__(self):
"""Initialize memory-only session."""Control session behavior and state.
def clone(self, to_instance=None) -> Session:
"""
Clone the current session.
Parameters:
- to_instance: Target session instance to clone to
Returns:
Session: Cloned session instance
"""
def save(self) -> None:
"""Save current session state to storage."""
def close(self) -> None:
"""Close and clean up session resources."""
def set_dc(self, dc_id: int, server_address: str, port: int) -> None:
"""
Set datacenter information.
Parameters:
- dc_id: Datacenter ID (1-5)
- server_address: Server IP address
- port: Server port number
"""import asyncio
from telethon import TelegramClient
async def authenticate_user():
client = TelegramClient('user_session', api_id, api_hash)
await client.connect()
if not await client.is_user_authorized():
# Request verification code
phone = input('Enter your phone number: ')
await client.send_code_request(phone)
# Enter the code
code = input('Enter the verification code: ')
try:
await client.sign_in(phone, code)
except SessionPasswordNeededError:
# 2FA is enabled
password = input('Enter your 2FA password: ')
await client.sign_in(password=password)
print("Authentication successful!")
await client.disconnect()
asyncio.run(authenticate_user())async def authenticate_bot():
client = TelegramClient('bot_session', api_id, api_hash)
await client.connect()
# Bot authentication is simpler
bot_token = 'your_bot_token_here'
await client.sign_in(bot_token=bot_token)
print("Bot authenticated successfully!")
# Verify it's a bot
if await client.is_bot():
me = await client.get_me()
print(f"Bot username: @{me.username}")
await client.disconnect()import qrcode
from io import BytesIO
async def qr_login():
client = TelegramClient('qr_session', api_id, api_hash)
await client.connect()
# Start QR login process
async with client.qr_login() as qr_login:
# Generate QR code
qr = qrcode.QRCode()
qr.add_data(qr_login.url)
qr.make()
# Display QR code (this is a simple text version)
qr.print_ascii(invert=True)
print(f"QR URL: {qr_login.url}")
print("Scan this QR code with your Telegram app")
# Wait for user to scan and authorize
try:
await qr_login.wait()
print("QR login successful!")
except TimeoutError:
print("QR login timed out")
await client.disconnect()from telethon.sessions import StringSession
async def use_string_session():
# Load from existing session string
session_string = "your_saved_session_string_here"
client = TelegramClient(
StringSession(session_string),
api_id,
api_hash
)
await client.connect()
# Use client normally
me = await client.get_me()
print(f"Connected as {me.first_name}")
# Save session string for next time
saved_session = client.session.save()
print(f"Save this for next time: {saved_session}")
await client.disconnect()async def setup_2fa():
client = TelegramClient('session', api_id, api_hash)
await client.start()
# Enable 2FA
password = "my_secure_password"
hint = "My favorite password"
email = "recovery@example.com"
def email_code_callback(length):
return input(f'Enter the {length}-digit code sent to your email: ')
success = await client.edit_2fa(
new_password=password,
hint=hint,
email=email,
email_code_callback=email_code_callback
)
if success:
print("2FA enabled successfully!")
await client.disconnect()from typing import Union, List, Optional, Callable, Any
from telethon.tl import types
from telethon import custom
PhoneNumber = str # International format, e.g., '+1234567890'
VerificationCode = Union[str, int]
Password = str
BotToken = str
EmailCallback = Callable[[int], str]Install with Tessl CLI
npx tessl i tessl/pypi-telethon