Telethon - Telegram Client Library
Telethon is a full-featured, asynchronous Python 3 client library for the Telegram API. It allows interaction with Telegram's MTProto API as a user or through a bot account. Currently at version 1.43.0, the library receives regular updates, including new API layers and bug fixes.
Warnings
- breaking Telethon v2.x is a complete rewrite and introduces significant breaking changes from v1.x (including API changes, renamed classes like TelegramClient to Client, and removal of telethon.sync). Code written for v1.x will likely not run on v2.x without substantial modification. Always consult the migration guide when upgrading to v2.x.
- gotcha Telethon is an asynchronous library. Incorrectly mixing asynchronous operations (like network requests) with synchronous code without proper `await` calls or an active `asyncio` event loop is a common mistake that can lead to unresponsive handlers, runtime errors, or unexpected behavior.
- gotcha The `api_id` and `api_hash` are critical for client creation and must be obtained from your Telegram API development tools page (my.telegram.org). Using incorrect, placeholder, or expired values will prevent the client from connecting to Telegram.
- gotcha Session files (`.session`) contain your encrypted authentication keys and sensitive login information. They are essential for persistent logins and should be protected, excluded from version control (e.g., via `.gitignore`), and never shared. Using the same session file for multiple concurrently running Telethon clients will result in `sqlite3.OperationalError: database is locked` or similar connection issues.
- gotcha Telegram API has rate limits. Sending too many requests in a short period can trigger `FloodWaitError`, requiring the client to wait for a specified duration before making further requests. While Telethon can automatically handle some `FloodWaitError` conditions, excessive flooding can lead to account bans.
- gotcha For optimal performance, particularly concerning file downloads/uploads and update handling, it is highly recommended to install the `cryptg` package. Without it, Telethon defaults to a slower pure Python implementation for encryption/decryption, leading to reduced speed.
Install
-
pip install telethon
Imports
- TelegramClient
from telethon import TelegramClient
- events
from telethon import events
- errors
from telethon import errors
- sync
import telethon.sync
Quickstart
import os
import asyncio
from telethon import TelegramClient
# Get API ID and API Hash from environment variables for security
# You can obtain these from https://my.telegram.org
api_id = int(os.environ.get('TG_API_ID', 0))
api_hash = os.environ.get('TG_API_HASH', '')
# 'session_name' will create 'session_name.session' file
# This file stores your login information and should be kept private.
client = TelegramClient('session_name', api_id, api_hash)
async def main():
if not api_id or not api_hash:
print("Please set TG_API_ID and TG_API_HASH environment variables.")
return
print("Connecting to Telegram...")
await client.start()
print("Client Connected!")
# Get information about yourself
me = await client.get_me()
print(f"Logged in as: {me.first_name} (@{me.username})")
# Example: Send a message to yourself
# await client.send_message('me', 'Hello from Telethon!')
# print("Message sent to self!")
# Keep the client running until disconnected (e.g., by Ctrl+C)
await client.run_until_disconnected()
if __name__ == '__main__':
asyncio.run(main())