What it is
Telethon is a Python library to interact with Telegram’s API as a user or bot. It allows you to send messages, manage groups, channels, and perform a wide range of Telegram actions programmatically.
Telethon allows you to log in using API ID and hash, send and receive messages, manage chats, retrieve users and groups, and handle media. It provides both synchronous and asynchronous clients, supports event handlers, and works with Telegram’s full API.
Installation
pip install telethonGetting started
The smallest useful thing you can do with it, and what each part means.
from telethon import TelegramClient
api_id = 123456
api_hash = 'your_api_hash'
client = TelegramClient('session_name', api_id, api_hash)
client.start()client.send_message('username_or_chat_id', 'Hello from Telethon!')participants = client.get_participants('chat_name')
for user in participants:
print(user.id, user.username)Advanced usage
Where the library earns its place over a simpler alternative.
from telethon import TelegramClient, events
async def main():
async with TelegramClient('session_name', api_id, api_hash) as client:
await client.send_message('username_or_chat_id', 'Hello async world!')
import asyncio
asyncio.run(main())from telethon import events
@client.on(events.NewMessage(pattern='hello'))
async def handler(event):
await event.reply('Hi!')
client.run_until_disconnected()from telethon.tl.types import InputMessagesFilterPhotos
messages = client.get_messages('chat_name', limit=10, filter=InputMessagesFilterPhotos)
for msg in messages:
client.download_media(msg)for dialog in client.iter_dialogs():
print(dialog.name, dialog.id)client.forward_messages('target_chat', messages=12345, from_peer='source_chat')Errors and fixes
The failures you are most likely to hit, and what actually resolves them.
- telethon.errors.SessionPasswordNeededError
- Occurs when two-factor authentication is enabled. Provide your 2FA password to continue.
- telethon.errors.FloodWaitError
- Occurs when performing too many requests. Wait for the specified duration before retrying.
- telethon.errors.RPCError
- Handle specific RPC errors like PeerIdInvalid or UserIsBlocked based on the error code.
Best practices
- Store your API ID and hash securely using environment variables.
- Use Telethon’s asynchronous client for IO-heavy tasks to improve performance.
- Handle session files carefully to avoid repeated login prompts.
- Respect Telegram's terms of service and avoid sending spam messages.
- Use event handlers for reactive automation instead of polling.
Background
Why it exists, and what it was reacting to.
Telethon was created by Lonami to provide a pure Python interface to the Telegram API. Unlike bot-only libraries, Telethon can log in as a real user, enabling access to features that bots cannot use. It supports both synchronous and asynchronous operations and is widely used for automation, scraping, and advanced bot functionalities.
