Pyrogram
Pyrogram is an elegant, modern, and asynchronous Telegram MTProto API framework in Python, primarily used for building custom user clients and bots. While it offers extensive features for interacting with the Telegram API and is boosted by the high-performance TgCrypto library, the project is officially no longer maintained or supported as of December 2024.
Warnings
- breaking Project is no longer maintained or supported. Users should be aware that new features, bug fixes, or security updates are unlikely.
- breaking Authorization flow changed: Callback functions for `Client` arguments (e.g., `phone_number`, `password`) were removed in favor of a simpler, sequential authorization.
- breaking The `idle()` method no longer automatically stops the client. It only idles.
- gotcha Session persistence is managed via session files (SQLite by default). For ephemeral environments or explicit in-memory use, `in_memory=True` must be passed to `Client`.
- gotcha All Pyrogram operations are asynchronous. Blocking operations (e.g., `time.sleep()`, synchronous network requests) in handlers will freeze the event loop and prevent other updates from being processed.
Install
-
pip install pyrogram -
pip install pyrogram[tgcrypto]
Imports
- Client
from pyrogram import Client
- filters
from pyrogram import filters
- RPCError
from pyrogram import Error
from pyrogram import errors; errors.RPCError
- idle
Client.idle()
from pyrogram import idle
Quickstart
import os
from pyrogram import Client, filters
import asyncio
API_ID = os.environ.get('TG_API_ID', '')
API_HASH = os.environ.get('TG_API_HASH', '')
BOT_TOKEN = os.environ.get('TG_BOT_TOKEN', '') # Optional, for bot accounts
async def main():
if not API_ID or not API_HASH:
print("Please set TG_API_ID and TG_API_HASH environment variables.")
return
# For a user account, use Client("my_account", api_id, api_hash)
# For a bot account, use Client("my_bot", api_id, api_hash, bot_token)
async with Client(
"my_session", # Session name, creates my_session.session file
api_id=int(API_ID),
api_hash=API_HASH,
bot_token=BOT_TOKEN if BOT_TOKEN else None # Pass bot_token only for bots
) as app:
me = await app.get_me()
print(f"Client started as {me.first_name} (@{me.username})")
@app.on_message(filters.command("start") & filters.private)
async def start_command(client, message):
await message.reply_text("Hello! I'm a Pyrogram client/bot.")
# Keep the client running indefinitely. In a real app, you might use app.run()
# or integrate with other async loops.
print("Listening for messages...")
await asyncio.Event().wait() # Keeps the client running indefinitely
if __name__ == "__main__":
asyncio.run(main())