### Pyrogram with uvloop Installation Source: https://github.com/telegramplayground/pyrogram/blob/master/source/topics/synchronous.rst Shows the required setup for using Pyrogram in synchronous mode with uvloop. Ensure uvloop.install() is called before importing Pyrogram. ```python import uvloop uvloop.install() from pyrogram import Client ... ``` -------------------------------- ### Install Pyrogram with TgCrypto Support Source: https://github.com/telegramplayground/pyrogram/blob/master/source/intro/install.rst Install Pyrogram with the 'fast' extra, which includes TgCrypto support for improved performance. This is the recommended installation method. ```text $ pip install pyrotgfork[fast] ``` -------------------------------- ### Define Plugin Loading Configuration Source: https://github.com/telegramplayground/pyrogram/blob/master/source/topics/smart-plugins.rst Examples of configuring the Client to load all plugins, specific modules, or exclude modules. ```python plugins = dict(root="plugins") Client("my_account", plugins=plugins).run() ``` ```python plugins = dict( root="plugins", include=[ "subfolder2.plugins2", "plugins0" ] ) Client("my_account", plugins=plugins).run() ``` ```python plugins = dict( root="plugins", exclude=["subfolder2.plugins2"] ) Client("my_account", plugins=plugins).run() ``` ```python plugins = dict( root="plugins", include=["subfolder1.plugins1 fn3 fn1 fn2"] ) Client("my_account", plugins=plugins).run() ``` -------------------------------- ### Install Pyrogram Development Version Source: https://github.com/telegramplayground/pyrogram/blob/master/source/intro/install.rst Install the development version of Pyrogram from its git repository. Use this command to get the latest unreleased features. ```text $ pip uninstall -y pyrogram && pip install pyrotgfork ``` -------------------------------- ### Initialize and Run a Pyrogram Client Source: https://github.com/telegramplayground/pyrogram/blob/master/source/index.rst Demonstrates the basic setup of a Pyrogram Client and a message handler for private messages. ```python from pyrogram import Client, filters app = Client("my_account") @app.on_message(filters.private) async def hello(client, message): await message.reply("Hello from Pyrogram!") app.run() ``` -------------------------------- ### Example Output of Handler Propagation Source: https://github.com/telegramplayground/pyrogram/blob/master/source/topics/more-on-updates.rst This text output demonstrates the sequential execution of handlers when propagation is continued. ```text 0 1 2 ``` -------------------------------- ### Basic API Call with Pyrogram Source: https://github.com/telegramplayground/pyrogram/blob/master/source/start/invoking.rst A complete example showing how to instantiate a client, define an async main function, and run it using the app.run() method. ```python from pyrogram import Client app = Client("my_account") async def main(): async with app: await app.send_message(chat_id="me", text="Hi!") app.run(main()) ``` -------------------------------- ### Smart Plugin Implementation Source: https://github.com/telegramplayground/pyrogram/blob/master/source/topics/smart-plugins.rst Example of using the Smart Plugin system to automatically register handlers using decorators. ```python from pyrogram import Client, filters @Client.on_message(filters.text & filters.private) async def echo(client, message): await message.reply(message.text) @Client.on_message(filters.text & filters.private, group=1) async def echo_reversed(client, message): await message.reply(message.text[::-1]) ``` ```python from pyrogram import Client plugins = dict(root="plugins") Client("my_account", plugins=plugins).run() ``` -------------------------------- ### Initialize and Send Message with Pyrogram Client Source: https://github.com/telegramplayground/pyrogram/blob/master/source/api/client.rst Instantiate the Client and use a context manager to send a message to 'me'. Ensure Pyrogram is installed. ```python from pyrogram import Client app = Client("my_account") with app: app.send_message(chat_id="me", text="Hi!") ``` -------------------------------- ### Install uvloop for Faster Asyncio Source: https://github.com/telegramplayground/pyrogram/blob/master/source/topics/speedups.rst Install uvloop, a drop-in replacement for the built-in asyncio event loop, to significantly speed up asyncio operations. This is recommended for performance-critical applications. ```bash pip3 install -U uvloop ``` -------------------------------- ### Manual Client Start and Stop Source: https://github.com/telegramplayground/pyrogram/blob/master/source/start/invoking.rst Performing API calls without a context manager by manually calling start and stop methods. ```python from pyrogram import Client app = Client("my_account") async def main(): await app.start() await app.send_message(chat_id="me", text="Hi!") await app.stop() app.run(main()) ``` -------------------------------- ### Verify Pyrogram Installation Source: https://github.com/telegramplayground/pyrogram/blob/master/source/intro/install.rst Verify that Pyrogram has been installed correctly by importing the library and checking its version in a Python shell. No errors indicate a successful installation. ```python from pyrogram import __version__ __version__ ``` -------------------------------- ### Install TgCrypto for Pyrogram Source: https://github.com/telegramplayground/pyrogram/blob/master/source/topics/speedups.rst Install the TgCrypto library to enable high-performance cryptography for Pyrogram. This is a prerequisite for Pyrogram to automatically use the faster cryptographic algorithms. ```bash pip3 install -U PyTgCrypto ``` -------------------------------- ### Interactive Authorization Output Source: https://github.com/telegramplayground/pyrogram/blob/master/source/start/auth.rst Example of the terminal prompts encountered during the user authorization flow. ```text Enter phone number: +1-123-456-7890 Is "+1-123-456-7890" correct? (y/n): y Enter phone code: 12345 Logged in successfully ``` -------------------------------- ### Use advanced filters with arguments Source: https://github.com/telegramplayground/pyrogram/blob/master/source/topics/use-filters.rst Examples of filters like command and regex that accept specific arguments for matching. ```python @app.on_message(filters.command(["start", "help"])) async def my_handler(client, message): print(message) ``` ```python @app.on_message(filters.regex("pyrogram")) async def my_handler(client, message): print(message) ``` -------------------------------- ### Manual Handler Registration Source: https://github.com/telegramplayground/pyrogram/blob/master/source/topics/smart-plugins.rst Example of modularizing handlers by manually importing and registering them in the main application script. ```python async def echo(client, message): await message.reply(message.text) async def echo_reversed(client, message): await message.reply(message.text[::-1]) ``` ```python from pyrogram import Client, filters from pyrogram.handlers import MessageHandler from handlers import echo, echo_reversed app = Client("my_account") app.add_handler( MessageHandler( echo, filters.text & filters.private)) app.add_handler( MessageHandler( echo_reversed, filters.text & filters.private), group=1) app.run() ``` -------------------------------- ### Create a Welcome Bot with Pyrogram Source: https://github.com/telegramplayground/pyrogram/blob/master/source/start/examples/welcome_bot.rst This bot listens for new chat members in a specified target chat and sends a personalized welcome message. Ensure you have the `pyrogram` library installed and replace `TARGET` with your chat's ID. ```python from pyrogram import Client, emoji, filters # Target chat. Can also be a list of multiple chat ids/usernames TARGET = -100123456789 # Welcome message template MESSAGE = "{} Welcome to [Pyrogram](https://telegramplayground.github.io/pyrogram/)'s group chat {}!" app = Client("my_account") # Filter in only new_chat_members updates generated in TARGET chat @app.on_chat_member_updated(filters.chat(TARGET)) async def welcome(client, chat_member_updated): if chat_member_updated.old_chat_member: return # it's not a new join # Build the new members list (with mentions) by using their first_name new_member = chat_member_updated.new_chat_member.user.mention added_by = message.from_user.id # is equal to new_member if user wasn't added # Build the welcome message by using an emoji and the list we built above text = MESSAGE.format(emoji.SPARKLES, new_member) # send a message to the chat await client.send_message( chat_id=chat_member_updated.chat.id, text=text ) app.run() # Automatically start() and idle() ``` -------------------------------- ### Using a bound method in Pyrogram Source: https://github.com/telegramplayground/pyrogram/blob/master/compiler/template/bound-methods.rst Example of using the reply bound method on a message object within a message handler. ```python from pyrogram import Client app = Client("my_account") @app.on_message() def hello(client, message) message.reply("hi") app.run() ``` -------------------------------- ### Synchronous and Asynchronous Handlers Source: https://github.com/telegramplayground/pyrogram/blob/master/source/topics/synchronous.rst Example showing how to define both synchronous (def) and asynchronous (async def) handlers for Pyrogram. Mixing handler types is supported. ```python @app.on_message() async def handler1(client, message): await message.forward("me") @app.on_edited_message() def handler2(client, message): message.forward("me") ``` -------------------------------- ### Get Full Chat History Source: https://github.com/telegramplayground/pyrogram/blob/master/source/start/examples/get_chat_history.rst Use `app.get_chat_history()` to iterate through all messages in a chat, starting from the latest. Ensure the Pyrogram client is properly initialized and run within an async context. ```python from pyrogram import Client app = Client("my_account") async def main(): async with app: # "me" refers to your own chat (Saved Messages) async for message in app.get_chat_history("me"): print(message) app.run(main()) ``` -------------------------------- ### Initialize Client and Send Message Source: https://github.com/telegramplayground/pyrogram/blob/master/compiler/template/methods.rst Demonstrates how to instantiate a Pyrogram Client and send a message using the context manager. ```python from pyrogram import Client app = Client("my_account") with app: app.send_message(chat_id="me", text="hi") ``` -------------------------------- ### Implement Custom Storage Engine Source: https://github.com/telegramplayground/pyrogram/blob/master/source/topics/storage-engines.rst Demonstrates using a custom storage engine class by passing it to the storage_engine parameter. ```python from pyrogram import Client from .aio_sqlite_storage import AioSQLiteStorage # assumes the file is available async with Client( "my_account", storage_engine=AioSQLiteStorage("/path/to/your/file.session") ) as app: await app.send_message(chat_id="me", text="Greetings from **Pyrogram**!") ``` -------------------------------- ### Implement Custom Storage Engine Source: https://github.com/telegramplayground/pyrogram/blob/master/source/api/storage/index.rst Demonstrates using a custom storage engine class, such as AioSQLiteStorage, via the storage_engine parameter. ```python import asyncio from pyrogram import Client from .aio_sqlite_storage import AioSQLiteStorage # assumes the file is available api_id = 12345 api_hash = "0123456789abcdef0123456789abcdef" async def main(): async with Client( "my_account", api_id, api_hash, storage_engine=AioSQLiteStorage("/path/to/your/file.session") ) as app: await app.send_message(chat_id="me", text="Greetings from **Pyrogram**!") asyncio.run(main()) ``` -------------------------------- ### Conflicting Handler Registration Source: https://github.com/telegramplayground/pyrogram/blob/master/source/topics/more-on-updates.rst Example of handlers with overlapping filters where only the first registered handler executes. ```python @app.on_message(filters.text | filters.sticker) async def text_or_sticker(client, message): print("Text or Sticker") @app.on_message(filters.text) async def just_text(client, message): print("Just Text") ``` -------------------------------- ### Client Instantiation Source: https://github.com/telegramplayground/pyrogram/blob/master/source/start/invoking.rst Creating a new Client object with a specified session name. ```python app = Client("my_account") ``` -------------------------------- ### Initialize Client After Authorization Source: https://github.com/telegramplayground/pyrogram/blob/master/source/start/auth.rst Once the session file is created, the client can be initialized using only the session name. ```python from pyrogram import Client app = Client("my_account") app.run() ``` -------------------------------- ### Using asyncio.run() Source: https://github.com/telegramplayground/pyrogram/blob/master/source/start/invoking.rst Executing the main function using standard asyncio.run(), requiring the client to be instantiated inside the main function. ```python import asyncio from pyrogram import Client async def main(): app = Client("my_account") async with app: await app.send_message(chat_id="me", text="Hi!") asyncio.run(main()) ``` -------------------------------- ### Pyrogram Client Initialization and Basic Usage Source: https://github.com/telegramplayground/pyrogram/blob/master/compiler/template/methods.rst Demonstrates how to initialize a Pyrogram Client and send a basic message. ```APIDOC ## Pyrogram Client Initialization and Basic Usage ### Description This example shows how to create a `pyrogram.Client` instance and use it within a `with` block to send a message. ### Method `send_message` ### Endpoint N/A (Client-side library) ### Request Example ```python from pyrogram import Client app = Client("my_account") with app: app.send_message(chat_id="me", text="hi") ``` ### Response Example (No direct response shown, but the message "hi" would be sent to the user's saved messages.) ``` -------------------------------- ### Handling FloodWait Errors Source: https://github.com/telegramplayground/pyrogram/blob/master/source/start/errors.rst Example of catching a FloodWait error and using its 'value' attribute to wait before retrying the request. ```python import asyncio from pyrogram.errors import FloodWait ... try: ... # Your code except FloodWait as e: await asyncio.sleep(e.value) # Wait N seconds before continuing ... ``` -------------------------------- ### Pyrogram Client Initialization and Usage Source: https://github.com/telegramplayground/pyrogram/blob/master/source/api/client.rst Demonstrates how to initialize and use the Pyrogram Client to send a message. ```APIDOC ## Pyrogram Client Initialization and Usage ### Description This snippet shows the basic setup for using the Pyrogram Client to connect to your Telegram account and send a message. ### Method N/A (Illustrative Example) ### Endpoint N/A ### Parameters N/A ### Request Example ```python from pyrogram import Client app = Client("my_account") with app: app.send_message(chat_id="me", text="Hi!") ``` ### Response N/A (Illustrative Example) #### Success Response (200) N/A #### Response Example N/A ``` -------------------------------- ### Initialize Client in Test Mode Source: https://github.com/telegramplayground/pyrogram/blob/master/source/topics/test-servers.rst Use the test_mode=True parameter when initializing the Client to connect to the Telegram test servers. ```python from pyrogram import Client async with Client("my_account_test", test_mode=True) as app: print(await app.get_me()) ``` -------------------------------- ### Schedule Periodic Task Non-Asynchronously Source: https://github.com/telegramplayground/pyrogram/blob/master/source/topics/scheduling.rst Utilize BackgroundScheduler for scheduling tasks in a non-asynchronous Pyrogram context. Make sure apscheduler is installed. ```python from apscheduler.schedulers.background import BackgroundScheduler from pyrogram import Client app = Client("my_account") def job(): app.send_message(chat_id="me", text="Hi!") scheduler = BackgroundScheduler() scheduler.add_job(job, "interval", seconds=3) scheduler.start() app.run() ``` -------------------------------- ### Schedule Periodic Task Asynchronously Source: https://github.com/telegramplayground/pyrogram/blob/master/source/topics/scheduling.rst Use AsyncIOScheduler for scheduling tasks within an asynchronous Pyrogram application. Ensure apscheduler is installed. ```python from apscheduler.schedulers.asyncio import AsyncIOScheduler from pyrogram import Client app = Client("my_account") async def job(): await app.send_message(chat_id="me", text="Hi!") scheduler = AsyncIOScheduler() scheduler.add_job(job, "interval", seconds=3) scheduler.start() app.run() ``` -------------------------------- ### Initialize File Storage Source: https://github.com/telegramplayground/pyrogram/blob/master/source/api/storage/index.rst Uses SQLite to persist session data to a local file, enabling reconnection without re-authorization. ```python from pyrogram import Client async with Client("my_account") as app: print(await app.get_me()) ``` -------------------------------- ### Registering a MessageHandler Source: https://github.com/telegramplayground/pyrogram/blob/master/source/api/handlers.rst Demonstrates how to instantiate a MessageHandler and add it to the Pyrogram Client to process incoming messages. ```APIDOC ## Registering a MessageHandler ### Description Registers a callback function to handle incoming messages using the MessageHandler class. ### Request Example ```python from pyrogram import Client from pyrogram.handlers import MessageHandler app = Client("my_account") def dump(client, message): print(message) app.add_handler(MessageHandler(dump)) app.run() ``` ``` -------------------------------- ### Serialize Pyrogram Object for Humans (JSON) Source: https://github.com/telegramplayground/pyrogram/blob/master/source/topics/serializing.rst Use `str(obj)` to get a human-readable JSON representation of a Pyrogram object. `print()` automatically calls `str()` on objects. ```python async with app: r = await app.get_chat("me") print(str(r)) ``` -------------------------------- ### Get Telegram Dialogs List Source: https://github.com/telegramplayground/pyrogram/blob/master/source/start/examples/get_dialogs.rst Use this snippet to retrieve and iterate over all dialogs in a user account. Requires an initialized Client instance and must be run within an async context. ```python from pyrogram import Client app = Client("my_account") async def main(): async with app: async for dialog in app.get_dialogs(): print(dialog.chat.title or dialog.chat.first_name) app.run(main()) ``` -------------------------------- ### Use uvloop with Pyrogram and app.run Source: https://github.com/telegramplayground/pyrogram/blob/master/source/topics/speedups.rst Configure Pyrogram to use uvloop by calling uvloop.install() before creating the Client instance and running the application with app.run(). This is an alternative method for integrating uvloop. ```python import uvloop from pyrogram import Client uvloop.install() app = Client("my_account") @app.on_message() async def hello(client, message): print(await client.get_me()) app.run() ``` -------------------------------- ### Get Chat Information with Raw API Source: https://github.com/telegramplayground/pyrogram/blob/master/source/topics/advanced-usage.rst Retrieve detailed chat information using `pyrogram.raw.functions.channels.GetFullChannel`. This method requires a `channel` object, which can be obtained using `app.resolve_peer` with a username or ID. The result is printed directly. ```python from pyrogram import Client from pyrogram.raw import functions, types async with Client("my_account") as app: r = await app.invoke( functions.channels.GetFullChannel( channel=app.resolve_peer("username") ) ) print(r) ``` -------------------------------- ### Authorize a User Account Source: https://github.com/telegramplayground/pyrogram/blob/master/source/start/auth.rst Initializes a Client instance with API credentials to trigger the interactive phone number and code verification process. ```python from pyrogram import Client api_id = 12345 api_hash = "0123456789abcdef0123456789abcdef" app = Client("my_account", api_id=api_id, api_hash=api_hash) app.run() ``` -------------------------------- ### Pyrogram Filters Overview Source: https://github.com/telegramplayground/pyrogram/blob/master/source/api/filters.rst Filters in Pyrogram are objects designed to selectively process incoming Telegram updates. They provide a powerful mechanism for routing and handling specific events within your bot or application. For a deeper understanding of filter mechanics, refer to the detailed guide on filter usage. ```APIDOC ## Pyrogram Filters ### Description Filters are objects that can be used to filter the content of incoming updates. ### Further Reading :doc:`Read more about how filters work <../topics/use-filters>` ### Module Details .. automodule:: pyrogram.filters :members: ``` -------------------------------- ### Set Custom Client Values Source: https://github.com/telegramplayground/pyrogram/blob/master/source/topics/client-settings.rst Pass arguments directly in the Client constructor to set custom values for app version, device model, and system version. ```python app = Client( "my_account", app_version="1.2.3", device_model="PC", system_version="Linux" ) ``` -------------------------------- ### Register a MessageHandler manually Source: https://github.com/telegramplayground/pyrogram/blob/master/source/api/handlers.rst Demonstrates how to define a callback function and register it with the client using the add_handler method. ```python from pyrogram import Client from pyrogram.handlers import MessageHandler app = Client("my_account") def dump(client, message): print(message) app.add_handler(MessageHandler(dump)) app.run() ``` -------------------------------- ### Initialize Pyrogram Client Source: https://github.com/telegramplayground/pyrogram/blob/master/source/start/setup.rst Use the Client class to initialize your application with your Telegram API credentials. ```python from pyrogram import Client api_id = 12345 api_hash = "0123456789abcdef0123456789abcdef" app = Client("my_account", api_id=api_id, api_hash=api_hash) ``` -------------------------------- ### Authorize a Bot Account Source: https://github.com/telegramplayground/pyrogram/blob/master/source/start/auth.rst Initializes a Client instance using a bot token provided by Bot Father. ```python from pyrogram import Client api_id = 12345 api_hash = "0123456789abcdef0123456789abcdef" bot_token = "123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11" app = Client( "my_bot", api_id=api_id, api_hash=api_hash, bot_token=bot_token ) app.run() ``` -------------------------------- ### Initialize and run a Pyrogram client Source: https://github.com/telegramplayground/pyrogram/blob/master/source/intro/quickstart.rst This script initializes a Pyrogram client using your Telegram API credentials and sends a test message to your own account. ```python import asyncio from pyrogram import Client api_id = 12345 api_hash = "0123456789abcdef0123456789abcdef" async def main(): async with Client("my_account", api_id, api_hash) as app: await app.send_message(chat_id="me", text="Greetings from **Pyrogram**!") asyncio.run(main()) ``` -------------------------------- ### Use uvloop with Pyrogram and asyncio.run Source: https://github.com/telegramplayground/pyrogram/blob/master/source/topics/speedups.rst Integrate uvloop into your Pyrogram application by calling uvloop.install() before asyncio.run(). This ensures that your application uses the faster uvloop event loop. ```python import asyncio import uvloop from pyrogram import Client async def main(): app = Client("my_account") async with app: print(await app.get_me()) uvloop.install() asyncio.run(main()) ``` -------------------------------- ### Initialize Pyrogram Client with TelethonStorage Source: https://github.com/telegramplayground/pyrogram/blob/master/source/topics/storage-engines.rst Use this snippet to create a Pyrogram client instance that leverages TelethonStorage. Ensure TelethonStorage is correctly imported and configured with necessary parameters like name, workdir, api_id, test_mode, and is_bot. ```python from pyrogram import Client from .tele_storage import TelethonStorage # assumes that the path downloaded is accurate workdir = Path(__file__).parent test_mode = False is_bot = False # Pass True if your session is bot session async with Client( "my_account", api_id=api_id, api_hash=api_hash, lang_code="ru", workdir=workdir, test_mode=test_mode, storage_engine=TelethonStorage( name="my_account", workdir=workdir, api_id=api_id, test_mode=test_mode, is_bot=is_bot ) ) as app: await app.send_message(chat_id="me", text="Greetings from **Pyrogram**!") ``` -------------------------------- ### Register multiple handlers with different filters Source: https://github.com/telegramplayground/pyrogram/blob/master/source/topics/use-filters.rst Shows how multiple handlers can coexist, each responding to different filter criteria. ```python @app.on_message(filters.command("start")) async def start_command(client, message): print("This is the /start command") @app.on_message(filters.command("help")) async def help_command(client, message): print("This is the /help command") @app.on_message(filters.chat("PyrogramChat")) async def from_pyrogramchat(client, message): print("New message in @PyrogramChat") ``` -------------------------------- ### Initialize Memory Storage Source: https://github.com/telegramplayground/pyrogram/blob/master/source/api/storage/index.rst Stores session data in RAM; data is discarded when the client stops. ```python from pyrogram import Client async with Client("my_account", in_memory=True) as app: print(await app.get_me()) ``` -------------------------------- ### Utilities Source: https://github.com/telegramplayground/pyrogram/blob/master/compiler/template/methods.rst Special functions available directly from the main package. ```APIDOC ## Utilities ### Description This section covers utility functions that are not bound to a `pyrogram.Client` instance. ### Methods - `idle()` - `compose()` ### Endpoint N/A (Client-side library) ### Parameters N/A ### Request Example ```python from pyrogram import idle, compose # Example usage for idle() # with app: # idle() # Example usage for compose() # apps = compose([ # Client("userbot1", bot_token="123:ABC"), # Client("userbot2", session_name="user2") # ]) ``` ### Response Example N/A ``` -------------------------------- ### Client Class Import Source: https://github.com/telegramplayground/pyrogram/blob/master/source/start/invoking.rst Importing the Client class required for Pyrogram operations. ```python from pyrogram import Client ``` -------------------------------- ### Invite Links Methods Source: https://github.com/telegramplayground/pyrogram/blob/master/compiler/template/methods.rst Methods for creating and managing invite links for chats. ```APIDOC ## Invite Links ### Description This section covers methods related to the creation and management of invite links for Telegram chats. ### Endpoint N/A (Client-side library) ### Parameters (Specific parameters depend on individual methods within this category) ### Request Example (Specific examples depend on individual methods within this category) ### Response Example (Specific examples depend on individual methods within this category) ``` -------------------------------- ### Configure Pyrogram Client with Proxy Source: https://github.com/telegramplayground/pyrogram/blob/master/source/topics/proxy.rst Use the 'proxy' parameter in the Client constructor to specify proxy details. Omit 'username' and 'password' if your proxy does not require authentication. Supported schemes include 'socks4', 'socks5', and 'http'. ```python from pyrogram import Client proxy = { "scheme": "socks5", # "socks4", "socks5" and "http" are supported "hostname": "11.22.33.44", "port": 1234, "username": "username", "password": "password" } app = Client("my_account", proxy=proxy) app.run() ``` -------------------------------- ### Handle sticker messages with filters Source: https://github.com/telegramplayground/pyrogram/blob/master/source/topics/use-filters.rst Demonstrates filtering for sticker messages using decorators or manual handler registration. ```python from pyrogram import filters @app.on_message(filters.sticker) async def my_handler(client, message): print(message) ``` ```python from pyrogram import filters from pyrogram.handlers import MessageHandler async def my_handler(client, message): print(message) app.add_handler(MessageHandler(my_handler, filters.sticker)) ``` -------------------------------- ### Send a Basic Message with Pyrogram Source: https://github.com/telegramplayground/pyrogram/blob/master/source/start/examples/hello_world.rst This snippet demonstrates how to initialize a Pyrogram client and send a simple text message to the 'me' chat. Markdown is enabled by default for message formatting. ```python from pyrogram import Client # Create a new Client instance app = Client("my_account") async def main(): async with app: # Send a message, Markdown is enabled by default await app.send_message(chat_id="me", text="Hi there! I'm using **Pyrogram**") app.run(main()) ``` -------------------------------- ### Filter Callback with Client Access Source: https://github.com/telegramplayground/pyrogram/blob/master/source/topics/create-filters.rst Demonstrates the structure of a filter callback function that includes the `client` argument. This allows making API calls within the filter logic to decide whether to pass the update. ```python async def func(_, client, query): # r = await client.some_api_method() # check response "r" and decide to return True or False ... ``` -------------------------------- ### Handle Callback Queries with Pyrogram Source: https://github.com/telegramplayground/pyrogram/blob/master/source/start/examples/callback_queries.rst Registers a callback query handler to respond to inline button presses. Requires a valid bot token and an active Client instance. ```python from pyrogram import Client app = Client("my_bot", bot_token="123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11") @app.on_callback_query() async def answer(client, callback_query): await callback_query.answer( f"Button contains: '{callback_query.data}'", show_alert=True) app.run() # Automatically start() and idle() ``` -------------------------------- ### Sequential Update Propagation Source: https://github.com/telegramplayground/pyrogram/blob/master/source/topics/more-on-updates.rst Demonstrates how updates propagate through groups even if an unhandled exception occurs in a previous handler. ```python @app.on_message(filters.private) async def _(client, message): print(0) @app.on_message(filters.private, group=1) async def _(client, message): raise Exception("Unhandled exception!") # Simulate an unhandled exception @app.on_message(filters.private, group=2) async def _(client, message): print(2) ``` ```text 0 Exception: Unhandled exception! 2 ``` -------------------------------- ### Combine filters with bitwise operators Source: https://github.com/telegramplayground/pyrogram/blob/master/source/topics/use-filters.rst Shows how to use bitwise operators to combine or invert filters for complex logic. ```python @app.on_message(filters.text | filters.photo) async def my_handler(client, message): print(message) ``` ```python @app.on_message(filters.sticker & (filters.channel | filters.private)) async def my_handler(client, message): print(message) ``` -------------------------------- ### Export and Use Session Strings Source: https://github.com/telegramplayground/pyrogram/blob/master/source/api/storage/index.rst Allows persisting in-memory sessions by exporting them to a string and re-importing later. ```python from pyrogram import Client async with Client("my_account", in_memory=True) as app: print(await app.export_session_string()) ``` ```python from pyrogram import Client session_string = "...ZnUIFD8jsjXTb8g_vpxx48k1zkov9sapD-tzjz-S4WZv70M..." async with Client("my_account", session_string=session_string) as app: print(await app.get_me()) ``` -------------------------------- ### Create a Basic Static Data Filter Source: https://github.com/telegramplayground/pyrogram/blob/master/source/topics/create-filters.rst Create a custom filter that matches the callback query data to a specific string ('pyrogram'). The filter callback function receives unused client and update arguments, indicated by underscores. ```python from pyrogram import filters async def func(_, __, query): return query.data == "pyrogram" static_data_filter = filters.create(func) ``` -------------------------------- ### Send ReplyKeyboardMarkup and InlineKeyboardMarkup Source: https://github.com/telegramplayground/pyrogram/blob/master/source/start/examples/bot_keyboards.rst Use this snippet to send both reply and inline keyboards to a chat. Ensure you are logged in as a bot. The reply markup can be configured with options like resize_keyboard. ```python from pyrogram import Client from pyrogram.types import ( ReplyKeyboardMarkup, InlineKeyboardMarkup, InlineKeyboardButton ) # Create a client using your bot token app = Client("my_bot", bot_token="123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11") async def main(): async with app: await app.send_message( chat_id="@PyrogramChat", # Edit this text="This is a ReplyKeyboardMarkup example", reply_markup=ReplyKeyboardMarkup( [ ["A", "B", "C", "D"], # First row ["E", "F", "G"], # Second row ["H", "I"], # Third row ["J"] ], # Fourth row resize_keyboard=True # Make the keyboard smaller ) ) await app.send_message( chat_id="@PyrogramChat", # Edit this text="This is a InlineKeyboardMarkup example", reply_markup=InlineKeyboardMarkup( [ [ InlineKeyboardButton( "Button", callback_data="data" ), InlineKeyboardButton( "URL", url="https://telegramplayground.github.io/pyrogram/" ), ], [ InlineKeyboardButton( "Choose chat", switch_inline_query="pyrogram" ), InlineKeyboardButton( "Inline here", switch_inline_query_current_chat="pyrogram" ) ] ] ) ) app.run(main()) ``` -------------------------------- ### Running the Async Function Source: https://github.com/telegramplayground/pyrogram/blob/master/source/start/invoking.rst Scheduling the main async function using the Pyrogram run method. ```python app.run(main()) ``` -------------------------------- ### Send message with mixed styles Source: https://github.com/telegramplayground/pyrogram/blob/master/source/topics/text-formatting.rst Shows how to combine Markdown and HTML syntax in a single message when parse_mode is not specified. ```python await app.send_message(chat_id="me", text="**bold**, italic") ``` -------------------------------- ### Handle Raw Updates with Pyrogram Source: https://github.com/telegramplayground/pyrogram/blob/master/source/start/examples/raw_updates.rst Use the @app.on_raw_update() decorator to create a handler for all raw updates. This is useful for debugging or processing specific update types not yet supported by higher-level abstractions. Ensure you have initialized the Client correctly. ```python from pyrogram import Client app = Client("my_account") @app.on_raw_update() def raw(client, update, users, chats): print(update) app.run() # Automatically start() and idle() ```