Skip to content
Armando Lüscher edited this page May 2, 2017 · 2 revisions

Do you want to know when your bots go down?

Here is a file that you can host on some other server, to fetch your bot's status from api.telegram.org and notify yourself with another bot.

Don't forget to put your data in appropriate places.

<?php
$botsAdminID    = 'YOUR_TELEGRAM_ID';   // Put your Telegram ID here.
$notifierBotKey = 'NOTIFY_BOT_API_KEY'; // Put your notifier bot API Key here.

$botsList = [
    'botOne' => 'API_KEY_FOR_BOT_1', // Name (to show in messages) and API KEY for first bot.
    'botTwo' => 'API_KEY_FOR_BOT_2', // Name and API KEY for second bot. Add more if needed.
];

$botsDown = [];
foreach ($botsList as $botUsername => $apiKey) {
    $botErrorMessage = sprintf('🆘 @%s: Bot status inaccessible', $botUsername);

    $chWI = curl_init('https://api.telegram.org/bot' . $apiKey . '/getWebhookInfo');
    curl_setopt($chWI, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($chWI);
    curl_close($chWI);

    if ($status = json_decode($response, true)) {
        if (isset($status['ok']) && $status['ok']) {
            $result = $status['result'];

            // If there are less than 5 pending updates, bot counts as up and active.
            if (isset($result['pending_update_count']) &&
                $result['pending_update_count'] < 5
            ) {
                continue;
            }

            $botErrorMessage = sprintf(
                '🆘 @%s: %d pending updates;' . PHP_EOL . '%s: %s',
                $botUsername,
                $result['pending_update_count'],
                date('Y-m-d H:i:s', $result['last_error_date']),
                $result['last_error_message']
            );
        } else {
            $botErrorMessage = sprintf(
                '🆘 @%s: (%d) %s',
                $botUsername,
                $status['error_code'],
                $status['description']
            );
        }
    }

    $botsDown[$botUsername] = $botErrorMessage;
}

if (empty($botsDown)) {
    exit;
}

// Send message to notifier chat.
$chSM = curl_init('https://api.telegram.org/bot' . $notifierBotKey . '/sendMessage');
curl_setopt($chSM, CURLOPT_RETURNTRANSFER, true);
curl_setopt($chSM, CURLOPT_POST, 1);
curl_setopt($chSM, CURLOPT_POSTFIELDS, http_build_query([
    'chat_id' => $botsAdminID,
    'text'    => implode(PHP_EOL . PHP_EOL, $botsDown),
]));

curl_exec($chSM);
curl_close($chSM);