Registry / communication / telethon

telethon

JSON →
library1.44.0pypypi✓ verified 23d ago

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.

pip install telethon
INSTALL
IMPORT
SIG · TELETHON
T
telethon
communicationpythonv1.44.0
Install
3.5s avg
Import
1192ms
Disk
30MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v1.44.0 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.95 runs
installs and imports cleanly · install 0.0s · import 1.264s · 30.5MB
glibc
py 3.103.95 runs
installs and imports cleanly · install 3.5s · import 1.120s · 31MB
30MB installed
● package 30MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

TelegramClient
from telethon import TelegramClient
events
from telethon import events
errors
from telethon import errors
sync
import telethon.sync
from telethon import sync
While 'import telethon.sync' was a common pattern in v1.x to run async code synchronously, it is removed in v2.x and generally discouraged in favor of proper asyncio usage.

This quickstart demonstrates how to initialize and connect a Telethon client. It logs in the user (or registers if it's the first run) using the `api_id` and `api_hash` provided via environment variables. The session is saved to a `.session` file for persistence. The client runs asynchronously until manually disconnected.

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())
Debug
Known issues
breakingTelethon 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.
fix
Review the official 'Migrating from v1 to v2' documentation for detailed instructions on adapting your codebase to the new API and structure.
affects: <2.0.0
gotchaTelethon 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.
fix
Ensure all Telethon API calls within an `async` function are `await`ed. If integrating with synchronous code, use `asyncio.run()` for your main async function and avoid blocking the event loop.
affects: All versions
gotchaThe `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.
fix
Always retrieve your unique `api_id` and `api_hash` from https://my.telegram.org. Store them securely, preferably in environment variables, and never hardcode them directly into public repositories.
affects: All versions
gotchaSession 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.
fix
Treat session files as highly sensitive. Use a unique session name for each client instance, especially if running multiple scripts. If an error occurs, ensure no other process is holding the session file lock.
affects: All versions
gotchaTelegram 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.
fix
Implement proper delays and back-off strategies in your code, especially when performing bulk operations. Use the `FloodWaitError.seconds` attribute to dynamically adjust wait times. Monitor Telegram's official API guidelines for rate limits.
affects: All versions
gotchaFor 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.
fix
Install `cryptg` using `pip install cryptg`. Verify its usage by enabling logging at INFO level before importing Telethon.
affects: All versions
Errors
Common errors & fixes
ModuleNotFoundError: No module named 'telethon'
The Telethon library is not installed in the Python environment.
fix
Install Telethon using pip: `pip install telethon`.
ImportError: cannot import name 'InputPeerChannel' from 'telethon.utils'
Attempting to import 'InputPeerChannel' from the incorrect module.
fix
Import 'InputPeerChannel' from the correct module: `from telethon.tl.types import InputPeerChannel`.
telethon.errors.rpcerrorlist.FloodWaitError: A wait of X seconds is required (caused by SendMessageRequest)
Too many requests were sent in a short period, triggering Telegram's rate limiting.
fix
Implement error handling to catch 'FloodWaitError' and pause execution for the specified duration before retrying.
telethon.errors.rpcerrorlist.PhoneNumberInvalidError: The phone number is invalid (caused by SendCodeRequest)
An invalid phone number was provided during the authentication process.
fix
Verify that the phone number is correctly formatted and valid before attempting to authenticate.
telethon.errors.rpcerrorlist.ChatAdminRequiredError: Chat admin privileges are required to do that (caused by GetParticipantsRequest)
The operation requires administrative privileges in the chat, which the user lacks.
fix
Ensure the user has the necessary admin rights in the chat before performing the operation.
Upgrade
Version history
1.44.0latest on PyPI · released Jun 15, 2026
Audit
Dependencies
cryptgoptionalOptional: Provides significantly faster encryption/decryption (C implementation) for improved performance, especially during file transfers.
pillowoptionalOptional: Automatically resizes large images when sending photos to avoid Telegram API failures.
aiohttpoptionalOptional: Enables downloading of WebDocument media files.
hachoiroptionalOptional: Extracts metadata (e.g., artist, title, duration) from files when sending documents.
Agent activity
102 hits · last 30 days
node
95
OpenAI (training)
1
Resources
telethon — pip install telethon · libregistry