Full-featured Telegram client library for Python 3
npx @tessl/cli install tessl/pypi-telethon@1.41.0A comprehensive Python 3 asyncio-based MTProto library for interacting with Telegram's API as both user and bot accounts. Telethon provides full access to Telegram's features including message handling, file transfers, user authentication, real-time updates, and complete raw API access, making it ideal for building sophisticated Telegram applications, bots, and automation tools.
pip install Telethoncryptg for performance improvementsfrom telethon import TelegramClient, events, ButtonFor specific components:
from telethon import TelegramClient, events, Button, utils, errors
from telethon.tl import types, functions
from telethon.sessions import StringSession, SQLiteSessionimport asyncio
from telethon import TelegramClient
# Replace with your actual values from https://my.telegram.org
api_id = 'your_api_id'
api_hash = 'your_api_hash'
async def main():
# Create client
client = TelegramClient('session_name', api_id, api_hash)
# Connect and authenticate
await client.start()
# Get current user info
me = await client.get_me()
print(f"Logged in as {me.first_name}")
# Send a message
await client.send_message('username', 'Hello from Telethon!')
# Disconnect
await client.disconnect()
# Run the client
asyncio.run(main())from telethon import TelegramClient, events
bot = TelegramClient('bot_session', api_id, api_hash)
@bot.on(events.NewMessage(pattern='/start'))
async def start_handler(event):
await event.respond('Hello! I am a bot created with Telethon.')
@bot.on(events.NewMessage)
async def echo_handler(event):
if not event.text.startswith('/'):
await event.respond(f'You said: {event.text}')
async def main():
await bot.start(bot_token='your_bot_token')
print("Bot is running...")
await bot.run_until_disconnected()
asyncio.run(main())Telethon uses a layered architecture built around the MTProto protocol:
The client uses Python's asyncio for asynchronous operations and supports both high-level convenience methods and low-level raw API access for maximum flexibility.
Core client functionality including connection management, authentication, session handling, and basic client operations.
class TelegramClient:
def __init__(self, session, api_id: int, api_hash: str, **kwargs): ...
async def start(self, phone=None, password=None, *, bot_token=None, **kwargs): ...
async def connect(self) -> None: ...
async def disconnect(self) -> None: ...
def is_connected(self) -> bool: ...User and bot authentication, session management, two-factor authentication, and QR code login functionality.
async def sign_in(self, phone: str = None, code: Union[str, int] = None, **kwargs): ...
async def sign_up(self, code: Union[str, int], first_name: str, last_name: str = '', **kwargs): ...
async def send_code_request(self, phone: str, *, force_sms: bool = False): ...
async def log_out(self) -> bool: ...
async def qr_login(self, ignored_ids: List[int] = None): ...Comprehensive message handling including sending, receiving, editing, deleting, forwarding, and reading messages with support for formatting, media, and buttons.
async def send_message(self, entity, message='', *, reply_to=None, parse_mode=(), **kwargs): ...
async def get_messages(self, entity, *args, **kwargs): ...
def iter_messages(self, entity, limit: int = 1, **kwargs): ...
async def edit_message(self, entity, message=None, text: str = None, **kwargs): ...
async def delete_messages(self, entity, message_ids, *, revoke: bool = True): ...
async def forward_messages(self, entity, messages, from_peer=None, **kwargs): ...File upload and download operations with progress tracking, including sending media, documents, photos, and handling various file formats.
async def send_file(self, entity, file, *, caption: str = '', **kwargs): ...
async def upload_file(self, file, *, part_size_kb: int = None, **kwargs): ...
async def download_media(self, message, file=None, **kwargs) -> str: ...
async def download_file(self, input_location, file=None, **kwargs) -> bytes: ...
def iter_download(self, file, **kwargs): ...Chat and channel administration including member management, permissions, admin operations, and participant handling.
def iter_participants(self, entity, limit: int = None, **kwargs): ...
async def get_participants(self, *args, **kwargs): ...
async def edit_admin(self, entity, user, **kwargs): ...
async def edit_permissions(self, entity, user=None, until_date=None, **kwargs): ...
async def kick_participant(self, entity, user): ...
async def get_permissions(self, entity, user): ...Real-time update handling with event decorators, filters, and handlers for messages, edits, deletions, and other Telegram updates.
def on(self, event): ...
def add_event_handler(self, callback, event=None): ...
def remove_event_handler(self, callback, event=None) -> int: ...
def run_until_disconnected(self): ...
class NewMessage: ...
class MessageEdited: ...
class ChatAction: ...
class CallbackQuery: ...Utility functions for entity resolution, input conversion, media type detection, and common Telegram operations.
def get_display_name(entity) -> str: ...
def get_input_peer(entity, allow_self=True, check_hash=True): ...
def get_peer_id(peer) -> int: ...
def parse_phone(phone) -> str: ...
def parse_username(username) -> str: ...
def is_image(file) -> bool: ...
def is_video(file) -> bool: ...Comprehensive error handling system with specific exception types for different error conditions and RPC errors from Telegram.
class RPCError(Exception): ...
class FloodWaitError(RPCError): ...
class SessionPasswordNeededError(RPCError): ...
class PhoneCodeInvalidError(RPCError): ...
class UsernameNotOccupiedError(RPCError): ...
def rpc_message_to_error(rpc_error, request): ...class TelegramClient:
"""Main client class for all Telegram operations"""
class Session:
"""Abstract base class for session storage"""
class Connection:
"""Abstract base class for network connections"""from typing import Union, List, Optional, Any, Callable
from datetime import datetime
EntityLike = Union[int, str, 'types.User', 'types.Chat', 'types.Channel']
MessageLike = Union[int, 'types.Message', 'custom.Message']
FileLike = Union[str, bytes, 'types.Document', 'types.Photo', 'io.IOBase']