DEV Community

Serhii
Serhii

Posted on Originally published at botservice.biz

Prevent Telegram Bot Webhook Outages with a Yii2 Console Management Controller

Deploying a Telegram bot in a Yii2 production environment requires more than mapping a web controller action to receive incoming POST requests. In high-traffic applications—such as booking systems, lead generation tools, or e-commerce bots—relying on manual curl calls or ad-hoc scripts to configure webhooks creates critical operational failure points.

When developers paste raw curl commands into terminal history to register webhooks, bot tokens leak into shell logs. If Telegram returns an error—such as a 429 Rate Limit or an invalid HTTPS certificate response—manual registration commands frequently mask the underlying API failure, leaving the bot silently disconnected. Furthermore, if incoming webhook payload logs accumulate indefinitely in your database to ensure message idempotency, high update volumes will eventually exhaust disk space or lock database tables during unindexed cleanups.

To prevent silent webhook drops, unauthorized payload spoofing, and database bloat, you need a dedicated Yii2 console controller (commands/TelegramController.php). This guide covers building a complete CLI management tool in Yii2 to register webhooks securely using secret tokens, inspect bot health via getMe and getWebhookInfo, and safely prune high-volume update logs in batch operations.

The Problem with Unmanaged Webhooks and Missing Health Checks

When Telegram attempts to deliver an update to your webhook endpoint and encounters a HTTP error code (such as 500 Internal Server Error or 502 Bad Gateway) repeatedly, Telegram's servers back off delivery exponentially. After extended downtime or repeated failures, Telegram disables the webhook entirely.

If your team does not monitor the status of getWebhookInfo, the application appears functional from the administrative dashboard, but incoming customer messages vanish without triggering server-side exceptions.

Another frequent issue occurs when developers omit the secret_token parameter during webhook registration. Telegram allows you to supply an X-Telegram-Bot-Api-Secret-Token header. Without configuring and checking this secret token inside your Yii2 request processing pipeline, any third party who discovers your public webhook URL can send forged POST payloads, injecting fake user actions or corrupting payment states.

Finally, when webhooks are active, standard practice dictates writing raw update IDs into an audit or deduplication table before executing business logic. Without a structured log rotation console command, tables housing millions of historical updates slow down query execution and degrade overall application throughput.

Building the Base Yii2 Telegram Operations Console Controller

To manage Telegram API interaction cleanly, start by creating a dedicated Yii2 console controller. Avoid hardcoding bot tokens or webhook URLs inside source code. Always pull configuration settings from environment variables or Yii2 application parameters.

Create the file commands/TelegramController.php. We will build a helper method that executes HTTP requests against the Telegram Bot API using cURL, handles JSON decoding failures, checks HTTP status codes, and strictly verifies the ok: true flag returned by Telegram.

<?php

namespace app\commands;

yii\console\Controller;
yii\console\ExitCode;
yii\helpers\Console;

class TelegramController extends Controller
{
    public $defaultAction = 'health';

    /**
     * Executes a GET or POST request to the Telegram Bot API.
     */
    protected function callApi(string $method, array $params = []): array
    {
        $token = getenv('TELEGRAM_BOT_TOKEN');
        if (empty($token)) {
            $this->stdout("Error: TELEGRAM_BOT_TOKEN environment variable is missing.\n", Console::FG_RED);
            exit(ExitCode::CONFIG);
        }

        $url = "https://api.telegram.org/bot{$token}/{$method}";
        $ch = curl_init();

        curl_setopt_array($ch, [
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POST => !empty($params),
            CURLOPT_POSTFIELDS => !empty($params) ? json_encode($params) : null,
            CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
            CURLOPT_TIMEOUT => 15,
            CURLOPT_CONNECTTIMEOUT => 5,
        ]);

        $response = curl_exec($ch);
        $curlError = curl_error($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        if ($response === false) {
            $this->stdout("cURL Network Error: {$curlError}\n", Console::FG_RED);
            return ['ok' => false, 'error_code' => 0, 'description' => $curlError];
        }

        $decoded = json_decode($response, true);
        if (json_last_error() !== JSON_ERROR_NONE) {
            $this->stdout("JSON Parse Error: " . json_last_error_msg() . "\n", Console::FG_RED);
            return ['ok' => false, 'error_code' => $httpCode, 'description' => 'Invalid JSON response from Telegram API'];
        }

        if ($httpCode !== 200 || empty($decoded['ok'])) {
            $desc = $decoded['description'] ?? 'Unknown API error';
            $code = $decoded['error_code'] ?? $httpCode;
            $this->stdout("Telegram API Error [{$code}]: {$desc}\n", Console::FG_RED);
        }

        return $decoded;
    }
}
Enter fullscreen mode Exit fullscreen mode

This base execution wrapper guarantees that API network drops, invalid JSON payloads, or explicit Telegram rejection responses (ok: false) are captured cleanly instead of throwing uncaught PHP warnings.

Implementing Webhook Setup and Deletion Commands

Next, extend TelegramController with CLI commands to attach and detach webhooks. When calling setWebhook, you should enforce a randomly generated secret_token (between 1 and 256 characters using A-Z, a-z, 0-9, _, -).

Here is the implementation of actionSetWebhook and actionDeleteWebhook within commands/TelegramController.php:

    /**
     * Registers the Telegram webhook with secret token protection.
     * Usage: php yii telegram/set-webhook https://example.com/telegram/webhook
     */
    public function actionSetWebhook(string $url): int
    {
        if (!filter_var($url, FILTER_VALIDATE_URL) || strpos($url, 'https://') !== 0) {
            $this->stdout("Error: Webhook URL must be a valid HTTPS URL.\n", Console::FG_RED);
            return ExitCode::DATAERR;
        }

        $secretToken = getenv('TELEGRAM_WEBHOOK_SECRET');
        if (empty($secretToken)) {
            $this->stdout("Error: TELEGRAM_WEBHOOK_SECRET environment variable is missing.\n", Console::FG_RED);
            return ExitCode::CONFIG;
        }

        $params = [
            'url' => $url,
            'secret_token' => $secretToken,
            'allowed_updates' => ['message', 'callback_query', 'my_chat_member'],
            'drop_pending_updates' => false,
        ];

        $this->stdout("Setting webhook to: {$url}...\n", Console::FG_YELLOW);
        $response = $this->callApi('setWebhook', $params);

        if (!empty($response['ok'])) {
            $this->stdout("Success: Webhook configured successfully!\n", Console::FG_GREEN);
            return ExitCode::OK;
        }

        return ExitCode::UNSPECIFIED_ERROR;
    }

    /**
     * Deletes the currently registered Telegram webhook.
     * Usage: php yii telegram/delete-webhook
     */
    public function actionDeleteWebhook(bool $dropPending = false): int
    {
        $this->stdout("Deleting webhook...\n", Console::FG_YELLOW);
        $response = $this->callApi('deleteWebhook', ['drop_pending_updates' => $dropPending]);

        if (!empty($response['ok'])) {
            $this->stdout("Success: Webhook removed successfully.\n", Console::FG_GREEN);
            return ExitCode::OK;
        }

        return ExitCode::UNSPECIFIED_ERROR;
    }
Enter fullscreen mode Exit fullscreen mode

By restricting allowed_updates to only the update types your Yii2 application processes, you reduce unnecessary network bandwidth and server overhead caused by unhandled Telegram events (such as inline queries or channel posts).

Performing Health Monitoring via getMe and getWebhookInfo

To detect silent delivery failures, your CLI tooling must inspect the live state of the bot account and the status of Telegram's webhook queue. The getWebhookInfo response exposes pending_update_count, last_error_date, and last_error_message.

Add the actionHealth command to inspect both getMe and getWebhookInfo:

    /**
     * Runs a health check on the bot credentials and inspects active webhook metrics.
     * Usage: php yii telegram/health
     */
    public function actionHealth(): int
    {
        $this->stdout("--- Telegram Bot Health Check ---\n", Console::FG_CYAN);

        $meResponse = $this->callApi('getMe');
        if (empty($meResponse['ok'])) {
            $this->stdout("FAILED: Bot token is invalid or API is unreachable.\n", Console::FG_RED);
            return ExitCode::UNSPECIFIED_ERROR;
        }

        $bot = $meResponse['result'];
        $this->stdout("Bot Name : {$bot['first_name']} (@{$bot['username']})\n", Console::FG_GREEN);
        $this->stdout("Bot ID   : {$bot['id']}\n", Console::FG_GREEN);

        $webhookResponse = $this->callApi('getWebhookInfo');
        if (empty($webhookResponse['ok'])) {
            $this->stdout("FAILED: Could not retrieve webhook status.\n", Console::FG_RED);
            return ExitCode::UNSPECIFIED_ERROR;
        }

        $info = $webhookResponse['result'];
        $this->stdout("Webhook URL          : " . ($info['url'] ?: '[NONE]') . "\n");
        $this->stdout("Pending Update Count : {$info['pending_update_count']}\n");

        if (!empty($info['last_error_date'])) {
            $errorTime = date('Y-m-d H:i:s', $info['last_error_date']);
            $this->stdout("LAST DELIVERY ERROR  : {$info['last_error_message']} at {$errorTime}\n", Console::FG_RED);
            return ExitCode::UNSPECIFIED_ERROR;
        }

        if (empty($info['url'])) {
            $this->stdout("WARNING: Webhook is currently NOT set!\n", Console::FG_YELLOW);
            return ExitCode::UNSPECIFIED_ERROR;
        }

        $this->stdout("Status               : HEALTHY\n", Console::FG_GREEN);
        return ExitCode::OK;
    }
Enter fullscreen mode Exit fullscreen mode

If actionHealth encounters a delivery error or notices an unconfigured webhook, it returns a non-zero exit code (ExitCode::UNSPECIFIED_ERROR). This design enables automated monitoring systems (like Nagios, Zabbix, or Cron alerts) to catch webhook failures before users report broken bot commands.

Rotating and Pruning Stale Update Logs safely

When handling webhooks in production, saving incoming update IDs inside a database table ensures idempotency. If Telegram re-sends a payload due to network instability, your application drops duplicate update_id rows.

However, if this table stores full JSON payloads without periodic cleanup, table sizes grow uncontrollably. Running a naive DELETE FROM telegram_update_log WHERE created_at < ... query on a table with hundreds of thousands of rows causes prolonged table locks, blocking incoming webhook web requests.

Below is the implementation of actionRotateLogs in commands/TelegramController.php, which prunes historical records in indexed batches:

    /**
     * Safely prunes historical Telegram update logs in small batches to avoid lock contention.
     * Usage: php yii telegram/rotate-logs --days=14 --batchSize=500
     */
    public function actionRotateLogs(int $days = 14, int $batchSize = 500): int
    {
        if ($days < 1) {
            $this->stdout("Error: Days threshold must be at least 1.\n", Console::FG_RED);
            return ExitCode::DATAERR;
        }

        $cutoff = date('Y-m-d H:i:s', strtotime("-{$days} days"));
        $this->stdout("Pruning telegram_update_log records older than {$cutoff}...\n", Console::FG_YELLOW);

        $db = \Yii::$app->db;
        $totalDeleted = 0;

        do {
            // Delete using primary key limits to prevent full table lock escalation
            $sql = "DELETE FROM {{%telegram_update_log}} 
                    WHERE created_at < :cutoff 
                    ORDER BY id ASC 
                    LIMIT :batchSize";

            $deleted = $db->createCommand($sql, [
                ':cutoff' => $cutoff,
                ':batchSize' => $batchSize,
            ])->execute();

            $totalDeleted += $deleted;
            if ($deleted > 0) {
                $this->stdout("Deleted {$deleted} records (Total: {$totalDeleted})...\n", Console::FG_GREY);
                usleep(50000); // 50ms pause to let web request transactions execute
            }
        } while ($deleted >= $batchSize);

        $this->stdout("Log rotation complete. Total rows pruned: {$totalDeleted}.\n", Console::FG_GREEN);
        return ExitCode::OK;
    }
Enter fullscreen mode Exit fullscreen mode

Using indexed primary key ranges (ORDER BY id ASC LIMIT :batchSize) combined with a short usleep(50000) pause ensures that background database maintenance never starves active API requests during peak traffic hours.

Production Execution and Deployment Setup

Once commands/TelegramController.php is complete, deploy and configure it within your server environment.

1. Registering the Webhook Post-Deployment

Execute the console command directly within your deployment script (e.g., Ansible, Docker entrypoint, or GitHub Actions deploy step):

php yii telegram/set-webhook https://api.yourdomain.com/telegram/webhook
Enter fullscreen mode Exit fullscreen mode

2. Validating Secret Tokens inside Controller Actions

Ensure your incoming Webhook Web Controller (controllers/TelegramController.php) strictly verifies the header set during setWebhook:

public function actionWebhook()
{
    $headers = Yii::$app->request->headers;
    $incomingSecret = $headers->get('X-Telegram-Bot-Api-Secret-Token');
    $expectedSecret = getenv('TELEGRAM_WEBHOOK_SECRET');

    if (empty($incomingSecret) || !hash_equals($expectedSecret, $incomingSecret)) {
        Yii::warning('Unauthorized webhook payload attempt detected.', 'telegram');
        throw new \yii\web\ForbiddenHttpException('Invalid secret token signature.');
    }

    $rawBody = Yii::$app->request->rawBody;
    $data = json_decode($rawBody, true);

    // Process update safely...
    return $this->asJson(['status' => 'ok']);
}
Enter fullscreen mode Exit fullscreen mode

3. Setting Up Cron Maintenance Tasks

Add daily log rotation and periodic health checks to your system crontab (/etc/cron.d/yii-telegram):

# Run bot health check every 15 minutes
*/15 * * * * www-data /usr/bin/php /var/www/app/yii telegram/health > /dev/null 2>&1

# Rotate update logs every night at 03:00 AM, retaining 7 days of historical logs
0 3 * * * www-data /usr/bin/php /var/www/app/yii telegram/rotate-logs --days=7 --batchSize=1000 > /dev/null 2>&1
Enter fullscreen mode Exit fullscreen mode

Integrating automated webhook management directly into your Yii2 console infrastructure replaces manual setup procedures with predictable deployment pipelines. Your application stays resilient against secret token spoofing, silent message queue buildup, and database bloat.

When building production-ready Telegram integrations or custom WebApp clients, team up with BotCreator — studio that ships Telegram bots / Mini Apps.

Top comments (0)