你好,我的机器人继续向我发送消息。我的代码是:
while(true)
{
header('Content-Type: text/html; charset=utf-8');
$token= "MY-TOKEN";
$url= "https://api.telegram.org/bot".$token."/getUpdates";
$update = file_get_contents($url);
$arrayUpdate= json_decode($update, true);
foreach ($arrayUpdate['result'] as $key) {
$chat_id = $key['message']['from']['id'];
$command = $key['message']['text'];
}
if($command == "/start"){
$text= "starting...";
$url= "https://api.telegram.org/bot".$token."/sendMessage?chat_id=".$chat_id."&text=".$text;
file_get_contents($url);
}
}
Run Code Online (Sandbox Code Playgroud)
我的机器人向我发送无限消息我希望我的机器人在我使用它时向我发送消息然后停止并等待下一个请求。
您的问题是您将检查更新的代码置于无限while循环中。所以你会收到无限的消息。要解决这个问题:
update_id. 每次收到更新时,它update_id等于update_id最后一条消息 + 1(每次更新到达时,它update_id都会增加 1)。您可以update_id通过offset在执行时传递来要求 bot api 仅获取大于或等于您指定的更新getUpdates:api.telegram.org/bot<TOKEN>/getUpdates?offset=<UPDATE_ID>update_id您收到的最后一条消息。1。下一次,当你要求更新通过添加它getUpdates,通过这个新update_id的offset如上图所示(或通过POST)。api 会给你带来下一条收到的消息。此外,当您使用 offset 获取新消息时,旧消息会被删除. 无法使用getUpdates.getUpdates随着每个旧消息在每个请求中被删除,保存在队列中的消息最终会变空。不要忘记照顾这种情况。更多信息getUpdates:API 文档
| 归档时间: |
|
| 查看次数: |
6960 次 |
| 最近记录: |