Telethon

Language: Python

Web

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.

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.

Installation

pip: pip install telethon
conda: conda install -c conda-forge telethon

Usage

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.

Connecting to Telegram

from telethon import TelegramClient

api_id = 123456
api_hash = 'your_api_hash'
client = TelegramClient('session_name', api_id, api_hash)
client.start()

Initializes a Telethon client and starts a session. You will be prompted to enter your phone number and verification code.

Sending a message

client.send_message('username_or_chat_id', 'Hello from Telethon!')

Sends a text message to a specified user or chat.

Getting chat participants

participants = client.get_participants('chat_name')
for user in participants:
    print(user.id, user.username)

Retrieves a list of participants from a chat and prints their IDs and usernames.

Asynchronous client example

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())

Demonstrates sending a message using Telethon’s asynchronous client.

Handling new messages with events

from telethon import events

@client.on(events.NewMessage(pattern='hello'))
async def handler(event):
    await event.reply('Hi!')

client.run_until_disconnected()

Replies 'Hi!' automatically whenever a new message containing 'hello' is received.

Downloading media

from telethon.tl.types import InputMessagesFilterPhotos
messages = client.get_messages('chat_name', limit=10, filter=InputMessagesFilterPhotos)
for msg in messages:
    client.download_media(msg)

Downloads the last 10 photo messages from a chat.

Iterating through dialogs

for dialog in client.iter_dialogs():
    print(dialog.name, dialog.id)

Lists all dialogs (chats, groups, channels) accessible to the user.

Forwarding messages

client.forward_messages('target_chat', messages=12345, from_peer='source_chat')

Forwards a message with ID 12345 from a source chat to a target chat.

Error Handling

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.