Telegram 机器人获取更新 API - PHP

Telegram Bot Getupdates API - PHP

我开发了一个电报机器人,它的工作是在用户请求时将 information/message 发送到群组。它是这样工作的:假设如果我 post 组中的“x player score”文本,它会带来该特定玩家的板球得分,并且这种机制发生在无限期 while 循环(长轮询)

问题是,除非我也为其他玩家发送请求信息,否则它会一直显示该特定玩家的分数。所以我想要实现的是,机器人应该只检查该消息一次并满足请求。

这是我的代码

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


while(true){

$get_msg = file_get_contents("https://api.telegram.org/bot%7B$token%7D/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);    

} 

您需要“确认”收到 message/update。否则您的机器人将一遍又一遍地查询相同的更新。

您实际上可以打开 https://api.telegram.org/botYOUR_TOKEN/getUpdates 并查看发送到您的机器人的所有消息。此列表需要清除。

See Api Docs.

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

要快速修复您的代码,请尝试类似

的方法
$token = 'xyz';
$group_name = 'xyz';
$offset = 0;

while(true){

$get_msg = file_get_contents("https://api.telegram.org/bot%7B$token%7D/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);    

} 

我建议创建一个函数来发送 API 请求。

现在,此代码将接收所有更新,并且代码可读。

$BOT_TOKEN = 'xyz';
$GROUP_NAME = 'xyz';
$SLEEP_TIME = 1;

$curl = curl_init();
function bot(string $method, array $params = [])
{
    curl_setopt($curl, CURLOPT_URL, "https://api.telegram.org/bot{$BOT_TOKEN}/{$method}");
    curl_setopt($curl, CURLOPT_POSTFIELDS, $params[0] ?? []);

    $result = curl_exec($curl);
    if ($result->ok)
    {
        return $result->result;
    }
    return $result;
}

$LastUpdateID = 0;
$x_player_score = 50;
while (true)
{
    $updates = bot('getUpdates', [
        'offset' => $LastUpdateID
    ]);
    
    # Loop on all of the updates
    foreach ($updates as $update)
    {
        if ($update->message->text == x_player_score){
            bot('sendMessage', [
                'chat_id' => $GROUP_NAME,
                'text' => $x_player_score
            ]);
        }
        $LastUpdateID = $update->update_id;
    }

    sleep($SLEEP_TIME);
}

curl_close($curl);