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.
pip install telethonconda install -c conda-forge telethonTelethon 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.
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.
client.send_message('username_or_chat_id', 'Hello from Telethon!')Sends a text message to a specified user or chat.
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.
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.
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.
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.
for dialog in client.iter_dialogs():
print(dialog.name, dialog.id)Lists all dialogs (chats, groups, channels) accessible to the user.
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.
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.