### Basic Bot Class Setup with Laraquest Traits Source: https://context7.com/laraxgram/laraquest/llms.txt Create a PHP class that utilizes the `Methode` and `Updates` traits from Laraquest to send messages and access incoming update data. This example demonstrates initializing the bot, retrieving chat information, and sending a response. ```php message->chat->id; $text = $bot->message->text; $userId = $bot->message->from->id; $username = $bot->message->from->username; // Send a message back to the user $response = $bot->sendMessage($chatId, 'Hello! You said: ' . $text); // Check response if ($response['ok']) { $messageId = $response['result']['message_id']; echo "Message sent successfully! ID: {$messageId}"; } else { echo "Error: " . $response['description']; } ``` -------------------------------- ### Basic Bot Class Setup Source: https://context7.com/laraxgram/laraquest/llms.txt Demonstrates how to set up a basic bot class using the `Methode` and `Updates` traits to send messages and process incoming update data. ```APIDOC ## Basic Bot Class Setup Create a bot class that utilizes the `Methode` and `Updates` traits to send messages and access incoming update data. ### Usage ```php message) { $chatId = $bot->message->chat->id; $text = $bot->message->text; $userId = $bot->message->from->id; $username = $bot->message->from->username; // Send a message back to the user $response = $bot->sendMessage($chatId, 'Hello! You said: ' . $text); // Check response if ($response['ok']) { $messageId = $response['result']['message_id']; echo "Message sent successfully! ID: {$messageId}"; } else { echo "Error: " . $response['description']; } } ``` ### Description This example shows how to instantiate a bot class that uses the `Methode` and `Updates` traits. It then accesses properties from the incoming message object (like `chat->id`, `message->text`, `from->id`, `from->username`) and uses the `sendMessage` method from the `Methode` trait to reply to the user. The response from `sendMessage` is checked for success or failure. ``` -------------------------------- ### Install Laraquest using Composer Source: https://github.com/laraxgram/laraquest/blob/1.x.x/README.md This command installs the Laraquest library using Composer, the dependency manager for PHP. Ensure Composer is installed globally on your system. ```bash composer require laraxgram/laraquest ``` -------------------------------- ### Laravel/LaraGram Integration with Singleton and Connections (PHP) Source: https://context7.com/laraxgram/laraquest/llms.txt This example demonstrates how to integrate Laraquest into Laravel applications by registering it as a singleton service. It includes configuration for multiple bot connections (e.g., 'main', 'secondary') and shows how to retrieve and use the singleton instance, including switching between different connections. ```php // In config/bot.php return [ 'default' => 'main', 'connections' => [ 'main' => [ 'token' => env('TELEGRAM_BOT_TOKEN'), ], 'secondary' => [ 'token' => env('TELEGRAM_SECONDARY_TOKEN'), ], ], 'api_server' => [ 'endpoint' => 'https://api.telegram.org/', ], ]; // In config/laraquest.php return [ 'update_type' => 'sync', 'polling' => [ 'sleep_interval' => 0.5, 'timeout' => 100, 'limit' => 100, 'allow_updates' => ['*'], ], ]; // Usage in a controller or command use LaraGram\Laraquest\Laraquest; class TelegramController { public function webhook() { $bot = app('laraquest'); // Get singleton instance if (isset($bot->message)) { $bot->sendMessage( $bot->message->chat->id, 'Received: ' . $bot->message->text ); } return response('OK'); } } // Using different connections $mainBot = app('laraquest')->connection('main'); $secondaryBot = app('laraquest')->connection('secondary'); $mainBot->sendMessage($chatId, 'From main bot'); $secondaryBot->sendMessage($chatId, 'From secondary bot'); ``` -------------------------------- ### Implement Long Polling with Laraquest Source: https://github.com/laraxgram/laraquest/blob/1.x.x/README.md This example demonstrates setting up long polling with Laraquest. The `Laraquest::polling` method accepts a callback function that receives a `Laraquest` instance, allowing you to process incoming updates and send responses. ```php Laraquest::polling(function(Laraquest $request){ $request->sendMessage($request->message->chat->id, "Hello, Laraquest!") }); ``` -------------------------------- ### Combine Methode and Updates Traits in Laraquest Source: https://github.com/laraxgram/laraquest/blob/1.x.x/README.md This example illustrates using both the `Methode` and `Updates` traits within the same class to send messages and process incoming updates. This allows for interactive bot functionalities. ```php use LaraGram\Laraquest\Methode; use LaraGram\Laraquest\Updates; class MyBotClass { use Methode, Updates; } $bot = new MyBotClass(); $bot->sendMessage($bot->message->chat->id, 'hello!'); ``` -------------------------------- ### Managing Multiple Telegram Bot Connections (PHP) Source: https://context7.com/laraxgram/laraquest/llms.txt This example shows how to configure and manage multiple Telegram bot tokens within a single application. It allows you to instantiate and interact with different bots independently, sending messages and performing actions using their respective tokens. ```php connection('main_bot'); $notificationBot = $bot->connection('notification_bot'); $adminBot = $bot->connection('admin_bot'); // Send messages from different bots $mainBot->sendMessage(123456789, 'Message from main bot'); $notificationBot->sendMessage(123456789, 'Alert: New notification!'); $adminBot->sendMessage(987654321, 'Admin panel notification'); // Check current connection name echo $mainBot->getConnection(); // Output: main_bot echo $notificationBot->getConnection(); // Output: notification_bot // Delete a message using specific bot $mainBot->deleteMessage(123456789, 42); // Forward message between chats $mainBot->forwardMessage( 987654321, // destination chat 123456789, // source chat 42 // message_id ); ``` -------------------------------- ### Manage Multiple Telegram Bot Connections in Laraquest Source: https://github.com/laraxgram/laraquest/blob/1.x.x/README.md This example shows how to configure and manage multiple Telegram bot connections within Laraquest. By defining connections in the `CONNECTIONS` array, you can easily switch between bots using the `connection` method. ```php $_ENV['CONNECTIONS']['first_bot']['BOT_TOKEN'] = 'XXX'; $_ENV['CONNECTIONS']['second_bot']['BOT_TOKEN'] = 'YYY'; $first_bot = $bot->connection('first_bot'); $second_bot = $bot->connection('second_bot'); $first_bot->sendMessage(...); $second_bot->deleteMessage(...); $first_bot->getConnection(); // first_bot ``` -------------------------------- ### Send Telegram Messages using Laraquest's Methode Trait Source: https://github.com/laraxgram/laraquest/blob/1.x.x/README.md This example demonstrates how to send a Telegram message using the `Methode` trait provided by Laraquest. Include the trait in your class and call the `sendMessage` method with the chat ID and message text. ```php use LaraGram\Laraquest\Methode; class MyBotClass { use Methode; } $bot = new MyBotClass(); $bot->sendMessage(123456789, 'hello!'); ``` -------------------------------- ### Receive Telegram Updates using Laraquest's Updates Trait Source: https://github.com/laraxgram/laraquest/blob/1.x.x/README.md This example shows how to access incoming Telegram updates using the `Updates` trait from Laraquest. After including the trait, you can access message details like the chat ID via the `$bot->message` property. ```php use LaraGram\Laraquest\Updates; class MyBotClass { use Updates; } $bot = new MyBotClass(); $chatID = $bot->message->chat->id; ``` -------------------------------- ### Common Telegram Bot API Methods (PHP) Source: https://context7.com/laraxgram/laraquest/llms.txt This snippet provides examples of frequently used Telegram Bot API methods available through the Laraquest library. It covers sending various media types (photo, document), location, contact, editing and deleting messages, answering callback queries, retrieving bot and chat information, managing webhooks, and handling chat members. ```php sendPhoto($chatId, 'https://example.com/image.jpg', 'Photo caption'); // Send a document $bot->sendDocument($chatId, 'https://example.com/file.pdf', null, 'Document caption'); // Send location $bot->sendLocation($chatId, 40.7128, -74.0060); // latitude, longitude // Send contact $bot->sendContact($chatId, '+1234567890', 'John Doe'); // Edit message text $bot->editMessageText('Updated text!', $chatId, $messageId); // Delete message $bot->deleteMessage($chatId, $messageId); // Answer callback query (inline button response) $bot->answerCallbackQuery($callbackQueryId, 'Button clicked!', true); // show_alert = true // Get bot info $me = $bot->getMe(); echo "Bot username: @" . $me['result']['username']; // Get updates (for manual polling) $updates = $bot->getUpdates(0, 100, 30); // offset, limit, timeout foreach ($updates['result'] as $update) { // Process each update } // Set webhook $bot->setWebhook('https://yourdomain.com/webhook'); // Delete webhook $bot->deleteWebhook(); // Get chat information $chat = $bot->getChat($chatId); echo "Chat title: " . $chat['result']['title']; // Get chat member count $count = $bot->getChatMemberCount($chatId); echo "Members: " . $count['result']; // Ban/unban chat member $bot->banChatMember($chatId, $userId); $bot->unbanChatMember($chatId, $userId); // Pin/unpin message $bot->pinChatMessage($chatId, $messageId); $bot->unpinChatMessage($chatId, $messageId); ``` -------------------------------- ### Configuration Source: https://context7.com/laraxgram/laraquest/llms.txt Configure your Telegram bot connection, API server, and polling parameters using environment variables. ```APIDOC ## Configuration Set environment variables to configure your Telegram bot connection, API server, and polling parameters. ### Environment Variables - **BOT_TOKEN** (string) - Required - Your bot token obtained from @BotFather. - **BOT_API_SERVER** (string) - Optional - Custom Bot API server URL. Defaults to `https://api.telegram.org/`. - **UPDATE_TYPE** (string) - Optional - Specifies the update retrieval method. Options: `sync`, `global`, `openswoole`, `swoole`, `polling`. Defaults to `sync`. #### Polling Configuration (for `polling` UPDATE_TYPE) - **sleep_interval** (float) - Optional - Time in seconds to sleep between polling cycles. Defaults to `0.5`. - **timeout** (integer) - Optional - Long polling timeout in seconds. Defaults to `100`. - **limit** (integer) - Optional - Maximum number of updates to retrieve per request. Defaults to `100`. - **allow_updates** (array) - Optional - An array of update types to receive. Use `["*"]` to receive all types. Defaults to `["*"]`. ``` -------------------------------- ### Configure Laraquest Environment Variables Source: https://context7.com/laraxgram/laraquest/llms.txt Set up environment variables for your Telegram bot token, API server URL, and update retrieval type. Optional parameters for long polling, such as sleep interval, timeout, and update limits, can also be configured. ```php sendMessage(123456789, 'Hello, World!'); // Message with HTML formatting $bot->sendMessage( 123456789, 'Bold, italic, code', null, // message_thread_id 'HTML' // parse_mode ); // Message with Markdown formatting $bot->sendMessage( 123456789, '*Bold* and _italic_ text', null, 'Markdown' ); // Reply to a specific message $bot->sendMessage( 123456789, 'This is a reply!', null, // message_thread_id null, // parse_mode null, // entities null, // link_preview_options null, // disable_notification null, // protect_content null, // message_effect_id (object)[ 'message_id' => 42 ] ); // Message with inline keyboard $bot->sendMessage( 123456789, 'Choose an option:', null, null, null, null, null, null, null, null, (object)[ 'inline_keyboard' => [ [ ['text' => 'Option 1', 'callback_data' => 'opt1'], ['text' => 'Option 2', 'callback_data' => 'opt2'] ], [ ['text' => 'Visit Website', 'url' => 'https://example.com'] ] ] ] ); ``` -------------------------------- ### POST /sendMessage Source: https://context7.com/laraxgram/laraquest/llms.txt Send text messages to users or groups. Supports various formatting options, reply markup, and replying to specific messages. ```APIDOC ## POST /sendMessage Send text messages to users or groups with optional formatting, reply markup, and reply functionality. ### Method `POST` ### Endpoint `/sendMessage` ### Parameters #### Query Parameters - **chat_id** (integer|string) - Required - Unique identifier for the target chat or username of the target channel (in the format `@channelusername`). - **text** (string) - Required - Text of the message to be sent. - **message_thread_id** (integer) - Optional - Unique identifier for the target message thread (topic) of the target chat. - **parse_mode** (string) - Optional - Mode for parsing entities in the text. Can be `MarkdownV2`, `HTML`, or `Markdown` (deprecated). - **entities** (array) - Optional - A JSON-serialized list of special entities that appear in the message text, which can be ordered and must be in JSON format. - **link_preview_options** (object) - Optional - Options for link preview. - **disable_notification** (boolean) - Optional - Sends the message silently. Users will not receive a notification, unless they are mentioned in the text or their chat is pinned. - **protect_content** (boolean) - Optional - If set to `True`, the content of the sent message will be protected under the terms of the Telegram Bot API policy. - **message_effect_id** (string) - Optional - Unique identifier of the message effect to be sent. Must be used only if the message is sent in a private chat and the user's chat with the bot is at least `10` seconds old. - **reply_to_message_id** (integer) - Optional - If the message is a reply, ID of the original message. - **allow_sending_without_reply** (boolean) - Optional - Pass `True`, if the message should be sent even if the specified replied-to message is not found. - **reply_markup** (object) - Optional - Additional interface options. A JSON-serialized object for an `inline keyboard`, `custom reply keyboard`, `force reply` to reply from the keyboard, or `remove reply keyboard`. ### Request Example (PHP using Laraquest) ```php sendMessage(123456789, 'Hello, World!'); // Message with HTML formatting $bot->sendMessage( 123456789, 'Bold, italic, code', null, // message_thread_id 'HTML' // parse_mode ); // Message with Markdown formatting $bot->sendMessage( 123456789, '*Bold* and _italic_ text', null, // message_thread_id 'Markdown' ); // Reply to a specific message $bot->sendMessage( 123456789, 'This is a reply!', null, // message_thread_id null, // parse_mode null, // entities null, // link_preview_options null, // disable_notification null, // protect_content null, // message_effect_id (object)[ 'message_id' => 42 ] // reply_parameters ); // Message with inline keyboard $bot->sendMessage( 123456789, 'Choose an option:', null, // message_thread_id null, // parse_mode null, // entities null, // link_preview_options null, // disable_notification null, // protect_content null, // message_effect_id null, // reply_parameters (object)[ 'inline_keyboard' => [ [ ['text' => 'Option 1', 'callback_data' => 'opt1'], ['text' => 'Option 2', 'callback_data' => 'opt2'] ], [ ['text' => 'Visit Website', 'url' => 'https://example.com'] ] ] ] // reply_markup ); ``` ### Response #### Success Response (200) - **ok** (boolean) - True if the request was successful. - **result** (object) - The sent `Message` object. #### Error Response - **ok** (boolean) - False if the request failed. - **error_code** (integer) - Error code. - **description** (string) - Description of the error. #### Response Example (Success) ```json { "ok": true, "result": { "message_id": 123, "chat": { "id": 123456789, "first_name": "John", "last_name": "Doe", "type": "private" }, "date": 1678886400, "text": "Hello, World!" } } ``` ``` -------------------------------- ### Configure Laraquest Bot Token and API Server Source: https://github.com/laraxgram/laraquest/blob/1.x.x/README.md Configuration for Laraquest involves setting environment variables for the bot token and optionally the Telegram API server URL. Default values are provided for optional settings like polling intervals and update limits. ```php $_ENV["BOT_TOKEN"] = "123456789:ABcdEfGHigKLMnopQrStuvWXYZ"; // required $_ENV["BOT_API_SERVER"] = "https://api.telegram.org/"; // default-optional // Polling $_ENV["sleep_interval"] = 0.5; // default-optional $_ENV["timeout"] = 100; // default-optional $_ENV["limit"] = 100; // default-optional $_ENV["allow_updates"] = ["*"]; // default-optional ``` -------------------------------- ### Configure Laraquest Request Modes (PHP) Source: https://context7.com/laraxgram/laraquest/llms.txt This snippet shows how to configure Laraquest's HTTP request modes. Mode::CURL is for standard synchronous requests that wait for a response, while Mode::NO_RESPONSE_CURL is for high-performance fire-and-forget requests that run in the background. The default mode can also be set via environment variables. ```php mode(Mode::CURL)->sendMessage($chatId, 'Synchronous message'); if ($response['ok']) { echo "Sent! Message ID: " . $response['result']['message_id']; } // Mode::NO_RESPONSE_CURL (64) - Fire-and-forget request // Does not wait for response, runs in background // Ideal for high-throughput scenarios where response doesn't matter $bot->mode(Mode::NO_RESPONSE_CURL)->sendMessage($chatId, 'Async message'); // Using integer values directly $bot->mode(32)->sendMessage($chatId, 'Standard request'); $bot->mode(64)->sendMessage($chatId, 'Background request'); // Configure default mode via environment $_ENV['UPDATE_TYPE'] = 'curl'; // Default to Mode::CURL $_ENV['UPDATE_TYPE'] = 'no_response_curl'; // Default to Mode::NO_RESPONSE_CURL ``` -------------------------------- ### Detecting Telegram Update and Message Types (PHP) Source: https://context7.com/laraxgram/laraquest/llms.txt This code snippet illustrates how to determine the type of an incoming Telegram update and the scope of the chat (private, group, channel). It provides methods to check if a message is a reply and to access the raw update data, enabling conditional routing and handling of different message formats. ```php getUpdateType(); // Possible values: text, photo, video, audio, document, sticker, voice, // video_note, animation, contact, location, venue, poll, dice, // callback_query, inline_query, shipping_query, pre_checkout_query, // my_chat_member, chat_member, chat_join_request, etc. // Get the scope (chat type) of the update $scope = $bot->scope(); // Possible values: private, group, supergroup, channel // Check if message is a reply $isReply = $bot->isReply(); // Get raw update data $rawData = $bot->getData(); // Example routing based on update type switch ($updateType) { case 'text': $text = $bot->message->text; $bot->sendMessage($bot->message->chat->id, "You sent text: {$text}"); break; case 'photo': $photoId = $bot->message->photo[0]->file_id; $bot->sendMessage($bot->message->chat->id, "Photo received!"); break; case 'callback_query': $bot->answerCallbackQuery($bot->callback_query->id, "Button clicked!"); break; case 'inline_query': // Handle inline query break; default: $bot->sendMessage($bot->message->chat->id, "Unknown message type: {$updateType}"); } // Handle based on scope if ($scope === 'private') { // Private chat logic } elseif ($scope === 'group' || $scope === 'supergroup') { // Group chat logic } elseif ($scope === 'channel') { // Channel post logic } ``` -------------------------------- ### Long Polling for Telegram Bot Updates (PHP) Source: https://context7.com/laraxgram/laraquest/llms.txt This snippet demonstrates how to implement long polling to continuously receive and process updates from Telegram without requiring a webhook server. It configures polling parameters like sleep interval, timeout, and message limits, and includes handlers for text messages and callback queries. ```php message->text)) { $chatId = $bot->message->chat->id; $text = $bot->message->text; if ($text === '/start') { $bot->sendMessage($chatId, 'Welcome! Send me a message.'); } elseif ($text === '/help') { $bot->sendMessage($chatId, 'Available commands: /start, /help'); } else { $bot->sendMessage($chatId, 'You said: ' . $text); } } // Handle callback queries (inline button clicks) if (isset($bot->callback_query)) { $callbackId = $bot->callback_query->id; $data = $bot->callback_query->data; $chatId = $bot->callback_query->message->chat->id; $bot->answerCallbackQuery($callbackId, 'You clicked: ' . $data); $bot->sendMessage($chatId, 'Button pressed: ' . $data); } }); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.