Home > Software design >  Telegram Bot Getupdates API - PHP
Telegram Bot Getupdates API - PHP

Time:10-07

I developed a telegram bot whose job is to send the information/message to the group if the user requests it. This is how it works: Suppose If I post the "x player score" text in the group, it would bring the cricket score of that particular player and this mechanism is happening inside the indefinite while loop (long polling)

the problem is that it would keep bringing the score of that particular player unless I send request information for some other player too. So what I'm trying to achieve is that the bot should go over that message only once and fulfill the request.

Here is my code

$token = 'xyz';
$group_name = 'xyz';


while(true){

$get_msg = file_get_contents("https://api.telegram.org/bot{$token}/getUpdates");
$get_msg_decode = json_decode($get_msg);
$msg_array = $get_msg_decode['result'];
$last_msg_array = end($msg_array); 
$last_msg = $last_msg_array['message']['text']; // this would bring the latest message from telegram group
x_player_score = 50;

// Some actions or logic
        
if($last_msg == x_player_score){
   $bot = "https://api.telegram.org/bot{$token}/sendMessage?chat_id={$group_name}&text={x_player_score}";
  $hit = file_get_contents($bot);      
} 

sleep(5);    

} 

CodePudding user response:

You need to "confirm" a received message/update. Or else your bot will query the same updates over and over again.

You can actually open https://api.telegram.org/botYOUR_TOKEN/getUpdates and see all messages sent to your bot. This list needs to be cleared.

See Api Docs.

An update is considered confirmed as soon as getUpdates is called with an offset higher than its update_id.

For a quick fix to your code try something like

$token = 'xyz';
$group_name = 'xyz';
$offset = 0;

while(true){

$get_msg = file_get_contents("https://api.telegram.org/bot{$token}/getUpdates?offset=$offset");
$get_msg_decode = json_decode($get_msg);
$msg_array = $get_msg_decode['result'];
$last_msg_array = end($msg_array);
$offset= $last_msg_array['update_id'] 1; 
$last_msg = $last_msg_array['message']['text']; // this would bring the latest message from telegram group
x_player_score = 50;

// Some actions or logic
        
if($last_msg == x_player_score){
   $bot = "https://api.telegram.org/bot{$token}/sendMessage?chat_id={$group_name}&text={x_player_score}";
  $hit = file_get_contents($bot);      
} 

sleep(5);    

} 
  • Related