Skip to content
chuv1 edited this page May 2, 2017 · 2 revisions

Do you want to know when your bots goes 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 notifer 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.
    ];
    
    foreach($botsList as $botName => $apiKey){
      
      $status = file_get_contents('https://api.telegram.org/bot'.$apiKey.'/getWebhookInfo');
      
      $status = !empty($status) && !empty(json_decode($status, true)) ? json_decode($status, true) : false;
      
      $status = !empty($status) && !empty($status['result']['pending_update_count']) && $status['result']['pending_update_count'] > 5 ? $status['result'] : 'ok';
      
      if($status != 'ok'){
        $botsDown[$botName]   = [
            'key'     => $apiKey,
            'status'  => $status
        ];
      }
    }
    
    if(empty($botsDown)) exit();
    
    $message = '';
    
    foreach($botsDown as $botName => $botData){
    
      $message .= sprintf('🆘 @'.$botName.' errors count - %s, last one occurred %s - (%s)',
          $botData['status']['pending_update_count'],
          date("H:i:s", $botData['status']['last_error_date']),
          $botData['status']['last_error_message']
      ).PHP_EOL.PHP_EOL;
      
    }
    
    $fields_string = '';
    $url = 'https://api.telegram.org/bot'.$notifierBotKey.'/sendMessage';
    $fields = array(
        'chat_id' => urlencode($botsAdminID),
        'text' => urlencode(''.$message)
    );
    
    //url-ify the data for the POST
    foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
    rtrim($fields_string, '&');
    
    //open connection
    $ch = curl_init();
    
    //set the url, number of POST vars, POST data
    curl_setopt($ch,CURLOPT_URL, $url);
    curl_setopt($ch,CURLOPT_POST, count($fields));
    curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
    
    //execute post
    $result = curl_exec($ch);
    
    //close connection
    curl_close($ch);
    
    exit();