### Send 'Hello World' Message with Rubpy Client Source: https://rubpy.shayan-heidari.ir/account_examples This example demonstrates how to send a simple 'Hello World' message using the rubpy.Client. It initializes a client, starts the session, sends a message to 'me' with Markdown enabled, and then disconnects. This is suitable for user account interactions. ```python from rubpy import Client # Create a new Client instance app = Client("session-name") async def main(): # Start client await app.start() # Send a message, Markdown is enabled by default await app.send_message("me", "Hi there! I'm using **Rubpy**") # Close client await app.disconnect() import asyncio asyncio.run(main()) ``` -------------------------------- ### Synchronous Rubpy Client Usage (with and without Context Manager) Source: https://rubpy.shayan-heidari.ir/account_examples This example illustrates two ways to use the rubpy.Client synchronously. The first method uses a context manager (`with Client(...)`) for automatic session handling. The second method manually starts the client (`app.start()`), sends a message, and then disconnects (`app.disconnect()`). ```python # استفاده از کانتکست منیجر به صورت همزمان with Client('my_session') as app: print(app.get_me()) # بدون کانتکست منیجر app = Client('my_session') app.start() app.send_message("me", "Hello from rubpy!") app.disconnect() ``` -------------------------------- ### Get chat and user IDs with Rubpy Bot Source: https://rubpy.shayan-heidari.ir/bot_examples This example demonstrates how to retrieve and display the user ID and chat ID to the user when they send the '/start' command. Requires a bot token. ```python from rubpy.bot import BotClient, filters from rubpy.bot.models import Update bot = BotClient('your-bot-token') @bot.on_update(filters.commands('start')) async def handle_start(c: BotClient, update: Update): if update.new_message: text = ( "🆔 شناسه کاربری شما:\n{user_id}\n\n" "💬 شناسه چت شما:\n{chat_id}\n\n" ).format( user_id=update.new_message.sender_id, chat_id=update.chat_id ) await update.reply(text) bot.run() ``` -------------------------------- ### Run the Python Bot Application Source: https://rubpy.shayan-heidari.ir/bot_examples This line of code initiates the execution of the Rubpy bot application. It starts the bot's event loop, allowing it to listen for and process incoming updates according to its configured middlewares and handlers. ```python bot.run() ``` -------------------------------- ### Echo Incoming Messages with Rubpy Source: https://rubpy.shayan-heidari.ir/account_examples This example shows how to create a simple echo bot using rubpy. It listens for text messages in private chats and replies with the same text. The `filters.text` and `filters.private` ensure it only responds to text messages in private chats. The client is run using `app.run()`, which automatically handles starting and stopping. ```python from rubpy import Client, filters app = Client("session-name") @app.on_message_updates(filters.text, filters.private) async def echo(client, update): await update.reply(update.text) app.run() # Automatically start() ``` -------------------------------- ### Install Rubpy Development Version from GitHub Source: https://rubpy.shayan-heidari.ir/index This command installs the bleeding-edge development version of Rubpy directly from its GitHub repository. This is useful for accessing the latest features and bug fixes before they are released in a stable version. ```bash pip3 install -U https://github.com/shayanheidari/rubika/archive/master.zip ``` -------------------------------- ### Rubpy Bot Middleware Example Source: https://rubpy.shayan-heidari.ir/bot_examples This example outlines the structure for implementing middleware in a Rubpy bot. It details the execution order of middleware components like logging, authentication, and rate limiting before reaching the main handler. Requires a bot token. ```python from rubpy.bot import BotClient, filters from rubpy.bot.models import Update, InlineMessage from collections import defaultdict import time user_timestamps = defaultdict(float) bot = BotClient("your-bot-token") ``` -------------------------------- ### Install Rubpy using pip Source: https://rubpy.shayan-heidari.ir/index This command installs or updates the Rubpy library to the latest stable version using pip, Python's package installer. Ensure you have Python 3 and pip installed. ```bash pip3 install -U rubpy ``` -------------------------------- ### Verify Rubpy Installation Source: https://rubpy.shayan-heidari.ir/index This Python code snippet checks if the Rubpy library has been successfully installed by importing it and printing its version. If no errors occur, the installation was successful. ```python import rubpy print(rubpy.__version__) ``` -------------------------------- ### Start Rubpy Client Connection Source: https://rubpy.shayan-heidari.ir/client_methods Initiates the connection to the Rubika server using the `start` method of the rubpy.Client. This method handles session loading, authentication, and device registration if necessary. It can optionally take a phone number for the initial login process. ```python await app.start(phone_number="+1234567890") ``` -------------------------------- ### Use Rubpy Client with Context Manager (Async and Sync) Source: https://rubpy.shayan-heidari.ir/account_examples This example demonstrates using the rubpy.Client with context managers for both asynchronous and synchronous operations. The `async with` statement is used for async operations like `get_me()`, while the standard `with` statement is used for synchronous operations. This ensures proper session management and cleanup. ```python # Use async async with Client('my_session') as app: print(await app.get_me()) # Use sync with Client('my_session') as app: print(app.get_me()) ``` -------------------------------- ### Send a basic message with Rubpy Bot Source: https://rubpy.shayan-heidari.ir/bot_examples This example demonstrates how to create a simple Rubpy bot client, send a message to a chat, and then close the client. It requires a bot token and a chat ID. ```python from rubpy import BotClient # Create a new Client instance app = BotClient("bot-token") async def main(): # Start client await app.start() # Send a message, Markdown is enabled by default await app.send_message("chat_id", "Hi there! I\'m using **Rubpy**") # Close client await app.stop() import asyncio asyncio.run(main()) ``` -------------------------------- ### Retrieve All Members of a Group/Channel with Rubpy Source: https://rubpy.shayan-heidari.ir/account_examples This script retrieves all members from a specified group or channel using the rubpy.Client. It iteratively fetches members using `app.get_members` until all members are collected. The `OBJECT_GUID` needs to be set to the target group or channel's GUID. It prints the total number of members found. ```python from rubpy import Client OBJECT_GUID = '' # GUID گروه یا کانال موردنظر with Client('get_all_members') as app: has_continue = True next_start_id = None total_members = 0 while has_continue: response = app.get_members(OBJECT_GUID, start_id=next_start_id) if not response: break # اگر پاسخ خالی بود، حلقه متوقف شود next_start_id = response.next_start_id has_continue = response.has_continue members = response.in_chat_members or [] for member in members: # print(member) total_members += 1 print("Total members:", total_members) ``` -------------------------------- ### Create link buttons with Rubpy Bot Source: https://rubpy.shayan-heidari.ir/bot_examples This example shows how to create interactive buttons within a Rubpy bot's message. It includes buttons for joining a channel and opening a URL. Requires a bot token. ```python """ This source code is just a sample for rubpy.BotClient You can edit the source code whenever you want. """ from rubpy import BotClient from rubpy.bot import filters from rubpy.bot.models import ( ButtonLink, JoinChannelData, Update, Keypad, KeypadRow, Button, ) from rubpy.bot.enums import ButtonLinkTypeEnum, ButtonTypeEnum bot = BotClient(token="your-bot-token") @bot.on_update(filters.commands("start")) async def handle_start(bot, update: Update): keypad = Keypad( rows=[ KeypadRow( buttons=[ Button( id="1", type=ButtonTypeEnum.LINK, button_text="عضویت اجباری", button_link=ButtonLink( type=ButtonLinkTypeEnum.JoinChannel, joinchannel_data=JoinChannelData( username="rubikapy", ask_join=True ), # اگر ask_join برابر False باشد کاربر مستقیما بدون پرسش عضو کانال میشود. ), ) ] ), KeypadRow( buttons=[ Button( id="2", type=ButtonTypeEnum.LINK, button_text="باز کردن لینک", button_link=ButtonLink( type=ButtonLinkTypeEnum.URL, link_url="https://shayan-heidari.ir/", ), ), ] ), ], resize_keyboard=True, on_time_keyboard=False, ) await update.reply( "سلام! خوش اومدی. از دکمه‌های زیر برای کار با ربات استفاده کن:", inline_keypad=keypad, ) bot.run() ``` -------------------------------- ### Manage states with Rubpy Bot Source: https://rubpy.shayan-heidari.ir/bot_examples This example illustrates how to use states in a Rubpy bot to manage conversational flows, such as awaiting user input like an email address. It shows setting, clearing, and filtering by states. Requires a bot token. ```python from rubpy.bot import BotClient, filters from rubpy.bot.models import Update app = BotClient("bot-token") # 1) یک نمونهٔ فیلتر بساز (می‌تونی پارامترها رو تغییر بدی) state_filter = filters.states("awaiting_email", match_mode="exact", scope="user", auto_clear=True) @app.on_update(filters.commands("start")) async def start(c, update: Update): # ست کردن state (با TTL 5 دقیقه) await state_filter.set_state_for(update, "awaiting_email", expire=300) await update.reply("لطفاً ایمیل خود را ارسال کنید.") # 2) دستی پاک کردن (مثال) @app.on_update(filters.commands("cancel")) async def cancel(c, update: Update): await state_filter.clear_state_for(update) await update.reply("جریان لغو شد.") # 3) handler ای که با state کار می‌کنه (فقط با فیلتر) @app.on_update(state_filter) async def got_email(c, update: Update): text = update.find_key("text") # process, validate email... await update.reply(f"ایمیل دریافت شد: {text}") app.run() ``` -------------------------------- ### On Start Event Source: https://rubpy.shayan-heidari.ir/bot_client_methods Decorator to register a function that runs once when the bot starts. ```APIDOC ## POST /events/on_start ### Description Registers an asynchronous function to be executed immediately after the bot client starts. ### Method POST ### Endpoint /events/on_start ### Parameters #### Request Body - **callback** (Callable) - Required - The asynchronous function to execute on bot start. It receives the bot client instance as an argument. ### Request Example ```json { "callback": "async def greet(bot):\n print(\"Bot started...\")\n print(await bot.get_me())" } ``` ### Response #### Success Response (200) - **status** (str) - Indicates successful registration. #### Response Example ```json { "status": "registered" } ``` ``` -------------------------------- ### Echo messages with Rubpy Bot Source: https://rubpy.shayan-heidari.ir/bot_examples This example creates a Rubpy bot that echoes back any text message it receives in a private chat. It uses a text filter and a private scope filter. Requires a bot token. ```python from rubpy import BotClient from rubpy.bot import filters from rubpy.bot.models import Update app = BotClient("bot-token") @app.on_update(filters.text, filters.private) async def echo(client, update: Update): await update.reply(update.new_message.text) app.run() # Automatically start() ``` -------------------------------- ### OpenChatData Source: https://rubpy.shayan-heidari.ir/bot_models Data structure for opening a chat, including object GUID and type. ```APIDOC ## OpenChatData ### Description Data structure for opening a chat, including object GUID and type. ### Fields - **object_guid** (Optional[str]) - The globally unique identifier (GUID) of the object. - **object_type** (Optional[ChatTypeEnum]) - The type of the object, specified by `ChatTypeEnum`. ``` -------------------------------- ### Run Webhook API Source: https://rubpy.shayan-heidari.ir/bot_client_methods Starts the bot client with a webhook server to receive updates. ```APIDOC ## POST /run/webhook ### Description Starts the bot client configured to receive updates via a webhook server. ### Method POST ### Endpoint /run/webhook ### Parameters #### Request Body - **webhook_url** (str) - Required - The public URL where the bot should listen for incoming webhooks. - **path** (str) - Optional - The specific path on the webhook URL for receiving updates (defaults to `/rubika/webhook`). - **host** (str) - Optional - The host address for the webhook server (defaults to `0.0.0.0`). - **port** (int) - Optional - The port for the webhook server (defaults to `8080`). ### Request Example ```json { "webhook_url": "https://example.com", "path": "/rubika/webhook", "host": "0.0.0.0", "port": 8080 } ``` ### Response #### Success Response (200) - **status** (str) - Indicates that the bot is running with a webhook server. #### Response Example ```json { "status": "running with webhook" } ``` ``` -------------------------------- ### Run Bot with Webhook Source: https://rubpy.shayan-heidari.ir/bot_client_methods Starts the bot client using a webhook. Requires specifying the public URL of your service, the path for the webhook, and the host and port to listen on for incoming requests. ```python # فرض: سرویس شما در https://example.com است await client.run(webhook_url="https://example.com", path="/rubika/webhook", host="0.0.0.0", port=8080) ``` -------------------------------- ### Get Message Reactions Source: https://rubpy.shayan-heidari.ir/client_methods Retrieves a list of reactions for a specific message. Supports pagination using `start_id`. ```APIDOC ## GET /get_message_reactions ### Description Retrieves a list of reactions for a specific message. Supports pagination using `start_id`. ### Method GET ### Endpoint /get_message_reactions ### Parameters #### Path Parameters - **object_guid** (str) - Required - The unique identifier of the chat. - **message_id** (str) - Required - The unique identifier of the message. #### Query Parameters - **start_id** (Optional[str]) - Optional - A unique identifier to continue fetching reactions from. Defaults to None. #### Request Body None ### Request Example ```python reactions = await client.get_message_reactions("object_guid", "message_id") # OR with start_id reactions = await client.get_message_reactions("object_guid", "message_id", start_id="your-next-start-id") ``` ### Response #### Success Response (200) - **Dict** - An asynchronous dictionary containing the reactions. Includes `next_start_id` and `has_continue` (bool) for pagination. **Note:** The `start_id` parameter is used for fetching subsequent batches of reactions. The response provides `next_start_id` and `has_continue` for managing this pagination. ``` -------------------------------- ### Simple Rubpy Bot Example (Echo Bot) Source: https://rubpy.shayan-heidari.ir/index This Python code demonstrates a basic Rubpy bot that echoes back any text message received in a private chat. It uses the BotClient and filters to process incoming updates and reply with the received message. Requires a bot token from Rubika's BotFather. ```python from rubpy.bot import BotClient, filters from rubpy.bot.models import Update app = BotClient("your-bot-token") @app.on_update(filters.text, filters.private) async def echo(client, update: Update): await update.reply(update.new_message.text) app.run() # Automatically start() ``` -------------------------------- ### Define Bot Startup Event Source: https://rubpy.shayan-heidari.ir/bot_client_methods Decorator to define an asynchronous function that runs once when the bot client starts. It receives the bot client instance as an argument and can be used for initialization tasks. ```python @app.on_start() async def greet(bot): print("Bot started...") print(await bot.get_me()) ``` -------------------------------- ### Get Updates Source: https://rubpy.shayan-heidari.ir/client_methods Low-level API for receiving raw updates from the WebSocket/LongPoll connection. ```APIDOC ## GET /get_updates ### Description This is a low-level layer for receiving raw updates from the WebSocket/LongPoll connection. It employs an infinite loop with retry attempts until `self.connection.get_updates()` yields a result. ### Method GET ### Endpoint /get_updates ### Parameters *None* ### Request Example *No request body needed for this GET request.* ### Response #### Success Response (200) - **update** (rubpy.types.Update) - The received update object. #### Response Example ```json { "update": { "update_id": 12345, "message": { "message_id": 67890, "text": "Hello, world!" } } } ``` ``` -------------------------------- ### Rubpy Bot Enums Usage Example (Python) Source: https://rubpy.shayan-heidari.ir/bot_enums Demonstrates how to use Enum values from the rubpy.bot.enums module for comparisons and payload construction. It shows checking chat types, constructing API payloads with keypad types, and handling update types. ```Python from rubpy.bot.enums import ChatTypeEnum, UpdateTypeEnum, ChatKeypadTypeEnum # Assuming 'chat' and 'update' are objects with relevant properties # Example usage: # if chat.chat_type == ChatTypeEnum.USER: # print("This is a user chat") # payload = {"chat_keypad_type": ChatKeypadTypeEnum.NEW} # if update.type == UpdateTypeEnum.NewMessage: # # handle new message # pass ``` -------------------------------- ### Run Coroutine with Rubpy Client Source: https://rubpy.shayan-heidari.ir/client_methods Executes an asynchronous coroutine after starting the client using the `run` method. This method is versatile, supporting both synchronous and asynchronous handlers. It manages the event loop for receiving updates. ```python async def my_handler(): # Your async logic here pass await app.run(coroutine=my_handler()) ``` -------------------------------- ### Authenticate Users with Python Middleware Source: https://rubpy.shayan-heidari.ir/bot_examples This middleware checks if the incoming update's user ID is in a predefined allowed list. If the user is not allowed, it prints a message and stops further processing. Otherwise, it allows the update to proceed to the next middleware or handler. ```python @bot.middleware() async def auth_checker(bot, update, call_next): """ Blocks users that are not in allowed list. """ allowed_users = {"b0IYdTF0EWT0d3c486d5205d051e86c5"} # فقط این کاربرا مجازن user_id = getattr(update, "chat_id", None) if user_id not in allowed_users: print(f"🚫 [Auth] کاربر {user_id} اجازه دسترسی نداره") return # نذار به هندلر برسه await call_next() ``` -------------------------------- ### Get User Information in Rubpy Source: https://rubpy.shayan-heidari.ir/client_methods Retrieves information about the currently authenticated user account. This is an asynchronous method and returns a dictionary containing user details. ```python me = await client.get_me() ``` -------------------------------- ### Log Bot Updates with Python Middleware Source: https://rubpy.shayan-heidari.ir/bot_examples This middleware logs incoming updates before they are processed by handlers. It identifies the update type and user ID, printing this information to the console. It then passes the update to the next middleware or handler. ```python @bot.middleware() async def logger(bot, update, call_next): """ Logs every update before it reaches the handlers. """ update_type = "InlineMessage" if isinstance(update, InlineMessage) else update.type user_id = getattr(update, "chat_id", None) print(f"📥 [Logger] type={update_type}, user={user_id}") await call_next() # ادامه بده به middleware بعدی یا handler ``` -------------------------------- ### Implement Rate Limiting with Python Middleware Source: https://rubpy.shayan-heidari.ir/bot_examples This middleware limits users to one message every 3 seconds. It tracks the last timestamp of a user's message and prevents new messages if the time difference is less than 3 seconds. If the limit is not exceeded, it updates the timestamp and allows the update to proceed. ```python @bot.middleware() async def rate_limiter(bot, update, call_next): """ Prevents users from spamming (1 message per 3 seconds). """ user_id = getattr(update, "chat_id", None) now = time.time() if user_id and now - user_timestamps[user_id] < 3: print(f"⚠️ [RateLimit] کاربر {user_id} داره اسپم می‌کنه") return user_timestamps[user_id] = now await call_next() ``` -------------------------------- ### Get Message Reactions using Rubpy Source: https://rubpy.shayan-heidari.ir/client_methods Retrieves a list of reactions for a specific message in a given chat. It supports pagination using `start_id` for fetching subsequent reactions. ```python reactions = await client.get_message_reactions("object_guid", "message_id") # OR reactions = await client.get_message_reactions("object_guid", "message_id", start_id="your-next-start-id") ``` -------------------------------- ### Handle Text Updates with Python Bot Handler Source: https://rubpy.shayan-heidari.ir/bot_examples This is the main handler for text-based updates. It is triggered by the `filters.text` condition. Upon receiving a text message, it prints a confirmation and replies to the user indicating that their message has been received. ```python # 🔹 Handler @bot.on_update(filters.text) async def main_handler(bot, update: Update): print(f"✅ Handler: پیام دریافت شد → {update.chat_id}") await update.reply("پیام شما دریافت شد ✅") ``` -------------------------------- ### Get Message Updates Source: https://rubpy.shayan-heidari.ir/client_methods Retrieves updates for messages in a conversation. Requires the conversation's object GUID and a state timestamp. ```APIDOC ## GET /get_messages_updates ### Description Retrieves updates for messages in a conversation. ### Method GET ### Endpoint /get_messages_updates ### Parameters #### Query Parameters - **object_guid** (str) - Required - The unique identifier for the conversation. - **state** (int) - Required - The timestamp to fetch updates from. ### Response #### Success Response (200) - **messages** (list) - A list of message update objects. - **next_state** (int) - The timestamp for the next set of updates. ``` -------------------------------- ### Instantiate Rubpy Client Source: https://rubpy.shayan-heidari.ir/client_methods Demonstrates how to create an instance of the rubpy.Client class. This client is used for direct user account interaction with the Rubika API. It requires a session name for storing login information. ```python from rubpy import Client app = Client("your-session-name") ``` -------------------------------- ### Get Poll Option Voters Source: https://rubpy.shayan-heidari.ir/client_methods Fetches the list of voters for a specific poll option. Requires the poll ID, the selected option index, and a starting ID for pagination. ```APIDOC ## GET /get_poll_option_voters ### Description Retrieves the list of voters for a specific poll option. ### Method GET ### Endpoint /get_poll_option_voters ### Parameters #### Query Parameters - **poll_id** (str) - Required - The unique identifier for the poll. - **selection_index** (int) - Required - The index of the selected poll option. - **start_id** (str) - Optional - The ID to start fetching voters from (for pagination). ### Response #### Success Response (200) - **voters** (list) - A list of voter objects. - **next_start_id** (str) - The ID for the next page of voters. ``` -------------------------------- ### Rubpy Client as Synchronous Context Manager Source: https://rubpy.shayan-heidari.ir/client_methods Utilizes the `__enter__` and `__exit__` methods to manage the rubpy.Client within a synchronous context. This ensures that the client connection is properly established upon entering the block and disconnected upon exiting. ```python with Client("my-sync-session") as app: # Use the client synchronously here pass ``` -------------------------------- ### GET /api/get_me Source: https://rubpy.shayan-heidari.ir/bot_client_methods Retrieves information about the bot. This endpoint is used to get details related to the bot's identity and status. ```APIDOC ## GET /api/get_me ### Description Retrieves information about the bot. ### Method GET ### Endpoint /api/get_me ### Parameters #### Query Parameters - **—** (—) - Required - Retrieves bot information ### Request Example ```python # No request body or specific parameters needed for this endpoint ``` ### Response #### Success Response (200) - **Bot** (async) - Information about the bot #### Response Example ```json { "result": { "id": 123456789, "is_bot": true, "first_name": "MyBot", "username": "my_bot" } } ``` ``` -------------------------------- ### Rubpy Client as Asynchronous Context Manager Source: https://rubpy.shayan-heidari.ir/client_methods Employs the `__aenter__` and `__aexit__` methods for managing the rubpy.Client within an asynchronous context, suitable for frameworks like FastAPI. It guarantees proper connection management in async environments. ```python async with Client("my-async-session") as app: # Use the client asynchronously here pass ``` -------------------------------- ### Use Plugins and Middleware Source: https://rubpy.shayan-heidari.ir/bot_client_methods Initializes the BotClient with automatic plugin enabling and specifies a plugin named 'echo'. It also defines a middleware function to log incoming update types before processing. ```python client = BotClient("TOKEN", auto_enable_plugins=True, plugins=["echo"]) @client.middleware() async def logger(bot, update, call_next): print("Update arrived", update.type) await call_next() await client.run() ``` -------------------------------- ### General Usage of Rubpy Bot Filters Source: https://rubpy.shayan-heidari.ir/bot_filters Demonstrates the general usage of the `rubpy.bot.filters` module to set up a bot and define an update handler that responds to specific text messages. It requires the `rubpy` library and imports the `BotClient` and `filters` modules. ```python from rubpy import BotClient from rubpy.bot import filters bot = BotClient("your_bot_token") @bot.on_update(filters.text("hello")) async def handle_hello(c, update): await c.send_message(update.chat_id, "Hello!") ``` -------------------------------- ### JoinChannelData Source: https://rubpy.shayan-heidari.ir/bot_models Data structure for handling channel join requests, including username and an option to ask for confirmation. ```APIDOC ## JoinChannelData ### Description Data structure for handling channel join requests, including username and an option to ask for confirmation. ### Fields - **username** (Optional[str]) - The username of the channel or group. The '@' symbol is normalized during `__post_init__`. - **ask_join** (Optional[bool]) - A boolean indicating whether to prompt the user for confirmation to join. Defaults to `False`. ``` -------------------------------- ### Get Poll Status Source: https://rubpy.shayan-heidari.ir/client_methods Retrieves the current status of a poll. ```APIDOC ## GET /get_poll_status ### Description Retrieves the current status of a poll. ### Method GET ### Endpoint /get_poll_status ### Parameters #### Path Parameters - **poll_id** (str) - Required - The unique identifier of the poll. #### Query Parameters None #### Request Body None ### Response #### Success Response (200) - **Dict** - An asynchronous dictionary containing the poll's status. ``` -------------------------------- ### Get Messages By ID Source: https://rubpy.shayan-heidari.ir/client_methods Retrieves specific messages from a chat using their unique identifiers. ```APIDOC ## GET /get_messages_by_id ### Description Retrieves specific messages from a chat using their unique identifiers. ### Method GET ### Endpoint /get_messages_by_id ### Parameters #### Path Parameters - **object_guid** (str) - Required - The unique identifier of the chat. - **message_ids** (str) - Required - A comma-separated string of message identifiers. #### Query Parameters None #### Request Body None ### Response #### Success Response (200) - **Dict** - An asynchronous dictionary containing the requested messages. ``` -------------------------------- ### Get Message URL Source: https://rubpy.shayan-heidari.ir/client_methods Retrieves the public sharing URL for a message from a public channel. ```APIDOC ## GET /get_message_url ### Description Retrieves the public sharing URL for a message from a public channel. ### Method GET ### Endpoint /get_message_url ### Parameters #### Path Parameters - **object_guid** (str) - Required - The unique identifier of the channel. - **message_id** (str) - Required - The unique identifier of the message. #### Query Parameters None #### Request Body None ### Response #### Success Response (200) - **Dict** - An asynchronous dictionary containing the public URL of the message. ``` -------------------------------- ### BotClient Initialization Source: https://rubpy.shayan-heidari.ir/bot_client_methods Instantiate the BotClient with your bot token and configure various settings like rate limiting, webhook usage, timeouts, and retry mechanisms. ```APIDOC ## BotClient Initialization ### Description Instantiate the BotClient with your bot token and configure various settings like rate limiting, webhook usage, timeouts, and retry mechanisms. ### Method Constructor ### Endpoint N/A ### Parameters #### Constructor Parameters - **token** (str) - Required - The token issued by Rubika. - **rate_limit** (float) - Optional - Default: 0.5 - Minimum delay between requests to prevent rate limiting. - **use_webhook** (bool) - Optional - Default: False - Determines the execution mode (webhook or polling). - **timeout** (float) - Optional - Default: 10.0 - Overall timeout for each HTTP request. - **connector** (aiohttp.TCPConnector) - Optional - Default: None - Share connections with other applications. - **max_retries** (int) - Optional - Default: 3 - Number of retries for recoverable errors. - **backoff_factor** (float) - Optional - Default: 0.5 - Exponential backoff factor for retries. - **retry_statuses** (Tuple[int,...]) - Optional - Default: (408,425,429,500,502,503,504) - HTTP status codes that trigger a retry. - **long_poll_timeout** (float) - Optional - Default: 30.0 - Timeout for the `getUpdates` request in long polling. - **parse_mode** (ParseMode | str) - Optional - Default: ParseMode.MARKDOWN - Default text formatting mode. - **fallback_urls** (Sequence[str]) - Optional - Default: ("https://botapi.rubika.ir/v3/{}/",) - Fallback URLs if the primary address is down. - **ignore_timeout** (bool) - Optional - Default: False - Continue retrying on Timeout errors. - **plugins** (Sequence[str]) - Optional - Default: None - List of plugins to auto-enable. - **auto_enable_plugins** (bool) - Optional - Default: False - Automatically enable plugins on `start`. - **plugin_entry_point_group** (str) - Optional - Default: "rubpy.plugins" - Entry point group for plugin discovery. - **plugin_manager_class** (Type[PluginManager]) - Optional - Default: PluginManager - Plugin manager class. ### Request Example ```python from rubpy import BotClient client = BotClient( token="YOUR_BOT_TOKEN", rate_limit=0.5, use_webhook=False ) ``` ### Response N/A (Constructor does not return a value directly) ``` -------------------------------- ### GET /api/get_file Source: https://rubpy.shayan-heidari.ir/bot_client_methods Retrieves the download URL for a file using its file ID. ```APIDOC ## GET /api/get_file ### Description Retrieves the download URL (`download_url`) for a file using its `file_id`. ### Method GET ### Endpoint /api/get_file ### Parameters #### Query Parameters - **file_id** (str) - Required - The ID of the file. ### Request Example ```python # Assuming 'client' is an initialized client object # download_url = await client.get_file("file_id_from_upload") ``` ### Response #### Success Response (200) - **str** - The download URL (`download_url`). #### Response Example ```json { "result": "https://rubika.ir/download/file_xyz789" } ``` ``` -------------------------------- ### Run Polling API Source: https://rubpy.shayan-heidari.ir/bot_client_methods Starts the bot's polling mechanism to receive updates. ```APIDOC ## POST /run/polling ### Description Starts the bot client in polling mode to continuously fetch updates from the server. ### Method POST ### Endpoint /run/polling ### Parameters None ### Response #### Success Response (200) - **status** (str) - Indicates that the bot is running in polling mode. #### Response Example ```json { "status": "running in polling mode" } ``` ``` -------------------------------- ### Send Video Source: https://rubpy.shayan-heidari.ir/client_methods Method for sending videos. ```APIDOC ## POST /send_video ### Description Method for sending videos. ### Method POST ### Endpoint /send_video ### Parameters #### Request Body - **object_guid** (str) - Required - Destination identifier. - **video** (Union[Path, bytes]) - Required - Path to the file or file bytes. - **caption** (Optional[str]) - Caption for the video. - **...** - Other parameters are similar to `send_message`. ### Request Example ```json { "object_guid": "me", "video": "path/to/your/video.mp4", "caption": "my video file" } ``` ### Response #### Success Response (200) - **message_info** (Dict) - Information about the sent message. #### Response Example ```json { "message_info": { "message_id": "11228", "sent_at": "2023-10-27T10:10:00Z" } } ``` ``` -------------------------------- ### Get Messages Interval Source: https://rubpy.shayan-heidari.ir/client_methods Retrieves the last 25 messages from a chat based on a middle message ID. ```APIDOC ## GET /get_messages_interval ### Description Retrieves the last 25 messages from a chat based on a middle message ID. ### Method GET ### Endpoint /get_messages_interval ### Parameters #### Path Parameters - **object_guid** (str) - Required - The unique identifier of the chat. - **middle_message_id** (str) - Required - The identifier of the middle message to fetch messages around. #### Query Parameters None #### Request Body None ### Response #### Success Response (200) - **Dict** - An asynchronous dictionary containing the last 25 messages. ``` -------------------------------- ### Bot Lifecycle Management Source: https://rubpy.shayan-heidari.ir/bot_client_methods Manage the lifecycle of your bot client, including starting, stopping, and handling plugin management. ```APIDOC ## Bot Lifecycle Management ### Description Manage the lifecycle of your bot client, including starting, stopping, and handling plugin management. ### Methods #### Start Bot - **Method**: `start` - **Description**: Initializes the BotClient and prepares it for communication with the Rubika bot API by setting up the HTTP session. - **Parameters**: None - **Return**: None (async) #### Stop Bot - **Method**: `stop` - **Description**: Shuts down the BotClient, closes resources, and prepares for termination. - **Parameters**: None - **Return**: None (async) #### Plugin Management - **`enable_plugins(identifiers: Optional[Sequence[str]] = None)`**: Enables specified plugins or the default list from the constructor. Returns a list of enabled `Plugin` objects. - **`disable_plugins(identifiers: Optional[Sequence[str]] = None)`**: Disables specified plugins. If no identifiers are provided, all active plugins are disabled. - **`register_plugin(plugin_cls, name=None)`**: Registers a new plugin with the internal manager and returns its unique name. **Note**: The `auto_enable_plugins` constructor parameter automatically enables plugins during the `start` method if set to `True`. ### Context Manager - **`__aenter__` / `__aexit__`**: Automatically calls `start()` and `stop()` within an `async with` block for asynchronous context management. - **`__enter__` / `__exit__`**: Synchronous versions for use in simple scripts. ``` -------------------------------- ### ButtonLocation Source: https://rubpy.shayan-heidari.ir/bot_models Represents a button for selecting a location, with options for default pointer and map locations, and type. ```APIDOC ## ButtonLocation ### Description Represents a button for selecting a location, with options for default pointer and map locations, and type. ### Fields - **default_pointer_location** (Optional[Location]) - The default location of the pointer on the map. - **default_map_location** (Optional[Location]) - The default location displayed on the map. - **type** (Optional[ButtonLocationTypeEnum]) - The type of location input (enum). - **title** (Optional[str]) - The title for the location input. - **location_image_url** (Optional[str]) - URL for an associated image or map. ``` -------------------------------- ### Get Bot Information (Python) Source: https://rubpy.shayan-heidari.ir/bot_client_methods Retrieves information about the bot. This method does not require any parameters. The return type is a Bot object. ```python bot = await client.get_me() ``` -------------------------------- ### Handler Management Source: https://rubpy.shayan-heidari.ir/client_methods APIs for managing event handlers, including adding and removing them. ```APIDOC ## POST /handlers/add ### Description Registers a user function and a handler instance (from `rubpy.handlers`). If the function is synchronous, `self.is_sync` is activated to facilitate concurrent execution. ### Method POST ### Endpoint /handlers/add ### Parameters #### Request Body - **func** (function) - Required - The user function to register. - **handler** (rubpy.handlers.Handler) - Required - The handler instance. ### Request Example ```json { "func": "on_update", "handler": "handlers.ChatUpdates()" } ``` ### Response #### Success Response (200) - **status** (string) - Indicates success. #### Response Example ```json { "status": "Handler added successfully" } ``` ## DELETE /handlers/remove ### Description Removes a function from the handler dictionary. ### Method DELETE ### Endpoint /handlers/remove ### Parameters #### Request Body - **func** (function) - Required - The user function to remove. ### Request Example ```json { "func": "on_update" } ``` ### Response #### Success Response (200) - **status** (string) - Indicates success. #### Response Example ```json { "status": "Handler removed successfully" } ``` ``` -------------------------------- ### Get Updates API Source: https://rubpy.shayan-heidari.ir/bot_client_methods Retrieves updates and generates a list of Update/InlineMessage objects. Supports limiting the number of updates and using an offset for pagination. ```APIDOC ## GET /get_updates ### Description Fetches updates and returns a list of `Update` or `InlineMessage` objects. You can specify the number of updates to retrieve and an optional offset ID. ### Method GET ### Endpoint /get_updates ### Parameters #### Query Parameters - **limit** (int) - Optional - The number of updates to request. Defaults to 100. - **offset_id** (str) - Optional - The offset ID for fetching updates. ### Response #### Success Response (200) - **updates** (List[Union[Update, InlineMessage]]) - A list of update objects. #### Response Example ```json { "updates": [ { "update_id": 12345, "message": { "message_id": 1, "from": {"id": 123, "is_bot": false, "first_name": "John"}, "chat": {"id": 123, "first_name": "John", "type": "private"}, "date": 1678886400, "text": "Hello" } } ] } ``` ``` -------------------------------- ### Get Messages by ID using Rubpy Source: https://rubpy.shayan-heidari.ir/client_methods Retrieves specific messages from a chat using their unique IDs. Requires the chat ID and a list of message IDs. ```python # Example usage: # messages = await client.get_messages_by_id("object_guid", ["message_id_1", "message_id_2"]) ``` -------------------------------- ### Send Music Source: https://rubpy.shayan-heidari.ir/client_methods Method for sending music files. ```APIDOC ## POST /send_music ### Description Method for sending music files. ### Method POST ### Endpoint /send_music ### Parameters #### Request Body - **object_guid** (str) - Required - Destination identifier. - **music** (Union[Path, bytes]) - Required - Path to the file or file bytes. - **caption** (Optional[str]) - Caption for the music file. - **...** - Other parameters are similar to `send_message`. ### Request Example ```json { "object_guid": "me", "music": "path/to/your/music.mp3", "caption": "my mp3 file" } ``` ### Response #### Success Response (200) - **message_info** (Dict) - Information about the sent message. #### Response Example ```json { "message_info": { "message_id": "11226", "sent_at": "2023-10-27T10:08:00Z" } } ``` ``` -------------------------------- ### Send Sticker Source: https://rubpy.shayan-heidari.ir/client_methods Method for sending stickers. ```APIDOC ## POST /send_sticker ### Description Method for sending stickers. ### Method POST ### Endpoint /send_sticker ### Parameters #### Request Body - **object_guid** (str) - Required - Destination identifier. - **sticker** (Dict) - Required - Sticker information. - **...** - Other parameters are similar to `send_message`. ### Request Example ```json { "object_guid": "me", "sticker": { "sticker_id": "some_sticker_id" } } ``` ### Response #### Success Response (200) - **message_info** (Dict) - Information about the sent message. #### Response Example ```json { "message_info": { "message_id": "11227", "sent_at": "2023-10-27T10:09:00Z" } } ``` ``` -------------------------------- ### Get Message Share URL using Rubpy Source: https://rubpy.shayan-heidari.ir/client_methods Generates a public shareable URL for a message in a public channel. Requires the channel ID and the message ID. ```python # Example usage: # url = await client.get_message_url("channel_guid", "message_id") ``` -------------------------------- ### Get File Download URL (Python) Source: https://rubpy.shayan-heidari.ir/bot_client_methods Retrieves the download URL for a file using its file ID. Returns the download URL as a string. ```python # Example for get_file (implementation details not provided in source) ``` -------------------------------- ### Keypad Source: https://rubpy.shayan-heidari.ir/bot_models Represents a custom keyboard (keypad) that can be attached to messages, with options for resizing and temporary display. ```APIDOC ## Keypad ### Description Represents a custom keyboard (keypad) that can be attached to messages, with options for resizing and temporary display. ### Fields - **rows** (Optional[List[KeypadRow]]) - A list of `KeypadRow` objects defining the layout of the keypad. - **resize_keyboard** (Optional[bool]) - A boolean indicating whether the keyboard should be resizable. - **on_time_keyboard** (Optional[bool]) - A boolean indicating whether the keyboard is temporary or time-based. ```