{"id":3291,"library":"telethon","title":"Telethon - Telegram Client Library","description":"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.","status":"active","version":"1.43.0","language":"en","source_language":"en","source_url":"https://github.com/LonamiWebs/Telethon","tags":["telegram","client","async","mtproto","bot","api"],"install":[{"cmd":"pip install telethon","lang":"bash","label":"Install stable version"}],"dependencies":[{"reason":"Optional: Provides significantly faster encryption/decryption (C implementation) for improved performance, especially during file transfers.","package":"cryptg","optional":true},{"reason":"Optional: Automatically resizes large images when sending photos to avoid Telegram API failures.","package":"pillow","optional":true},{"reason":"Optional: Enables downloading of WebDocument media files.","package":"aiohttp","optional":true},{"reason":"Optional: Extracts metadata (e.g., artist, title, duration) from files when sending documents.","package":"hachoir","optional":true}],"imports":[{"symbol":"TelegramClient","correct":"from telethon import TelegramClient"},{"symbol":"events","correct":"from telethon import events"},{"symbol":"errors","correct":"from telethon import errors"},{"note":"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.","wrong":"from telethon import sync","symbol":"sync","correct":"import telethon.sync"}],"quickstart":{"code":"import os\nimport asyncio\nfrom telethon import TelegramClient\n\n# Get API ID and API Hash from environment variables for security\n# You can obtain these from https://my.telegram.org\napi_id = int(os.environ.get('TG_API_ID', 0))\napi_hash = os.environ.get('TG_API_HASH', '')\n\n# 'session_name' will create 'session_name.session' file\n# This file stores your login information and should be kept private.\nclient = TelegramClient('session_name', api_id, api_hash)\n\nasync def main():\n    if not api_id or not api_hash:\n        print(\"Please set TG_API_ID and TG_API_HASH environment variables.\")\n        return\n\n    print(\"Connecting to Telegram...\")\n    await client.start()\n    print(\"Client Connected!\")\n\n    # Get information about yourself\n    me = await client.get_me()\n    print(f\"Logged in as: {me.first_name} (@{me.username})\")\n\n    # Example: Send a message to yourself\n    # await client.send_message('me', 'Hello from Telethon!')\n    # print(\"Message sent to self!\")\n\n    # Keep the client running until disconnected (e.g., by Ctrl+C)\n    await client.run_until_disconnected()\n\nif __name__ == '__main__':\n    asyncio.run(main())\n","lang":"python","description":"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."},"warnings":[{"fix":"Review the official 'Migrating from v1 to v2' documentation for detailed instructions on adapting your codebase to the new API and structure.","message":"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.","severity":"breaking","affected_versions":"<2.0.0"},{"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.","message":"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.","severity":"gotcha","affected_versions":"All versions"},{"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.","message":"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.","severity":"gotcha","affected_versions":"All versions"},{"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.","message":"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.","severity":"gotcha","affected_versions":"All versions"},{"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.","message":"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.","severity":"gotcha","affected_versions":"All versions"},{"fix":"Install `cryptg` using `pip install cryptg`. Verify its usage by enabling logging at INFO level before importing Telethon.","message":"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.","severity":"gotcha","affected_versions":"All versions"}],"env_vars":null,"last_verified":"2026-04-11T00:00:00.000Z","next_check":"2026-07-10T00:00:00.000Z"}