Projects

Webhook + queue

Explains the concept of projects with an emphasis on webhook + queue, demonstrates the use of telegramApi() from the first chapter, and provides an example of a PHP implementation for processing updates via a queue.

Projects - a section where we implement full-fledged applications based on a Telegram bot. The main focus is on integrating a webhook connection with an asynchronous update processing queue. This approach surpasses the polling model, as it reduces server load and provides an instant user response.

Webhook works on the principle: upon receiving a new message or event, the Telegram server sends a POST request to your external URL. Your application accepts this request, parses the payload, and executes the necessary logic. To implement this mechanism, you need to set up an HTTP endpoint that will accept requests from api.telegram.org.

The main idea of the project is to divide update processing into two stages: reception and processing. First, long polling is used to get a list of update IDs, then these updates are intercepted via webhook in real time. This allows not maintaining a constant connection and effectively scaling the system.

For implementation, we use the telegramApi() library, which is already described in chapter Первый запрос: getMe. This function returns a bot object with an update_id, which is necessary for subscribing to updates.


<?php
function webhookHandler($request) {
// Проверяем, что запрос пришел от Telegram
if (!isset($request->incomingWebhook)) {
http_response_code(403);
exit;
}

// Парсим payload
$data = json_decode($request->getContent(), true);
if (json_last_error() !== JSON_ERROR_NONE) {
http_response_code(400);
exit;
}

// Обрабатываем обновления
if (\$data["type"] === "message") {
handleMessage(\$data["message"]); // Функция из главы sendmessage
}
}
EOF

After receiving updates via webhook, they should be sent to a queue for further processing. The queue can be implemented using Redis, RabbitMQ, or even a simple file log. It is important to handle errors and retry failed database entries.

Example of a complete queue implementation in PHP: 1. Configure the webhook endpoint with the correct `X-Telegram-Bot-Api-Version` header. 2. Create a handler that accepts POST requests. 3. Extract the list of update_id and add them to the queue. 4. Start a background process (worker) that periodically retrieves tasks from the queue and performs the corresponding actions (sending messages, updating order status, etc.). This approach is used in projects Webhook + очередь and demonstrates the practical application of the Telegram API in real-world conditions."