Pyrogram

2.0.106 · abandoned · verified Wed Apr 15

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

Install

Imports

Quickstart

This quickstart initializes a Pyrogram client (which can act as a user account or bot). It requires `api_id` and `api_hash` from my.telegram.org/apps set as environment variables `TG_API_ID` and `TG_API_HASH`. For bots, `TG_BOT_TOKEN` should also be set. The client will create a `.session` file for persistent login. It includes a simple `start` command handler.

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())

view raw JSON →