【发布时间】:2021-09-15 21:29:21
【问题描述】:
我有一个 Telegram Bot,它运行了几个月。大约 3-4 周前,Telegram Bot 有时会(!)几次发送相同的消息 - 而不仅仅是一次!
我已经尝试了很多方法来解决这个问题:
我将 update_id 保存在数据库中。如果新的 update_id 高于保存的,则机器人发送消息。如果不是,则会发生错误。 (昨天发现每条重复的消息都有一个新的(更高的)update_id - 所以这个方法没用)
我尝试添加 exit();对每个 PHP 函数 - 都不起作用。
我检查了整个代码,是否存在未闭环。但一切都很好。
我在函数中加了一个?limit=1,但也没机会。
慢慢地,我的想法结束了。也许有人对此有一个很好的答案。
我总是有 $update 和聊天 ID:
define('api', 'https://api.telegram.org/bot'.token.'/');
$data = file_get_contents("php://input");
$update = json_decode($data, true);
$cbid = $update["callback_query"]["from"]["id"];
我的函数如下所示:
function callback($up){
return $up["callback_query"];
}
function tg_send_message($id, $text) {
$params=[
'chat_id' => $id,
'text' => $text,
'parse_mode' => 'Markdown',
];
$ch = curl_init('https://api.telegram.org/bot'.token.'/sendMessage?limit=1');
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT_MS, 3500);
curl_setopt($ch, CURLOPT_TIMEOUT_MS, 3500);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, ($params));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
curl_close($ch);
}
如果我想在有人点击内联按钮时发送消息 Top 10:
if(callback($update) and $cbdata == "top_10"){
tg_send_message($cbid, "This is my message!");
}
一切正常,现在也正常工作 - 机器人有时只是多次发送消息。
额外的消息总是有一个新的 update_id!如果有来自另一个 API 的变量值(如比特币价格),它也会发生变化。就像你在按钮上点击了 22 次(但你只点击了一次)
我非常感谢每一个有用的答案!非常感谢。
最好的问候。
编辑:我还尝试了以下方法:
function tg_btn_click_send_message($id, $text) {
$response = $update["callback_query"];
$botUrl = "https://api.telegram.org/bot" . BOT_TOKEN . "/answerCallbackQuery";
$postFields = array('callback_query_id' => $callback_query_id, 'text' => $response);
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type:multipart/form-data"));
curl_setopt($ch, CURLOPT_URL, $botUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
$output = curl_exec($ch);
//send Text
header("Content-Type: application/json");
$parameters = array('chat_id' => $id, "text" => $text);
$parameters["method"] = "sendMessage";
echo json_encode($parameters);
}
喜欢这里的建议:php telegram answercallbackquery sendmessage
但也无法正常工作。
【问题讨论】:
-
有趣的事情:只是不能在 iPhone 上工作。在 Android 手机上它工作正常!他们只收到一条消息!