R
R
rocket-82020-07-10 17:39:04
API
rocket-8, 2020-07-10 17:39:04

Telegram Api returns the same in getUpdates, what should I do?

I am writing a simple telegram bot using long polling. The problem is that every time Telegram sends the same updates that it has already sent, it was written somewhere that in order for them to be considered old, the bot must respond to them, but this did not help, and it just endlessly sends messages in response to the old updates. Habr what to do?
Bot Code

<?php
require 'Config.php';
require 'utils/API.php';

  $telegram = new Telegram(Config::BOT_TOKEN);

  while (true) {
    sleep(2);

    $updates = $telegram->getUpdates(); // Получаем обновление, методом getUpdates
    foreach ($updates as $update){
      if (isset($update->message->text)) { // Проверяем Update, на наличие текста

        $text = $update->message->text; // Переменная с текстом сообщения
        $chat_id = $update->message->chat->id; // Чат ID пользователя
        $first_name = $update->message->chat->first_name; //Имя пользователя

        print_r($chat_id);
        if ($text == '/start') { // Если пользователь подключился в первый раз, ему поступит приветствие
          $telegram->sendMessage($chat_id, 'Привет'. ' ' . $first_name . '!');
        } else {
          $telegram->sendMessage($chat_id, $first_name . '! Как дела?' );
        }

      }
    }

  }
?>

Telegram class code
<?php

class Telegram {

  public $token;
  public function __construct($token)
  {
    $this->token = $token;
  }

  private function curl_get($url, $params) {

    $url = $url . "?" . http_build_query($params);
    $curl = curl_init($url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    $response = curl_exec($curl);
    curl_close($curl);

    return json_decode($response);
  }

  private function api($method, $params = []) {
      $res = self::curl_get("https://api.tlgr.org/bot".$this->token ."/". $method, $params);

      return $res->result;
  }

  public function sendMessage($chat_id, $text) {
    return $this->api('sendMessage', [
      'chat_id' => $chat_id,
      'text' => $text
    ]);
  }

  public function getUpdates($offset) {
    return $this->api('getUpdates', ['offset' => $offset]);
  }
}
?>

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question