我正在使用以下代码在 php 中制作一个简单的电报机器人:
$message = json_decode(file_get_contents('php://input'), true);
// if it's not a valid JSON return
if(is_null($message)) return;
$endpoint = "https://api.telegram.org/bot<token>/";
// make sure if text and chat_id is set into the payload
if(!isset($message["message"]["text"]) || !isset($message["message"]["chat"]["id"])) return;
// remove special characters, needed for the interpreter apparently
$text = $message["message"]["text"];
//$text = str_replace(["\r", "\n", "\t"], ' ', $text);
// saving chat_id for convenience
$chat_id = $message["message"]["chat"]["id"];
// show to the client that the bot is typing
file_get_contents($endpoint."sendChatAction?chat_id=".$chat_id."&action=typing");
file_get_contents($endpoint."sendMessage?chat_id=".$chat_id."&text=hi");
但问题是同时响应多个请求。用户未实时收到响应(延迟)。我确定最后一行会导致延迟并等待电报服务器的响应。我怎么能弄清楚呢?
更新 我找到了这段代码,但它仍然有延迟:
$ch = curl_init();
$curlConfig = array(
CURLOPT_URL => 'https://api.telegram.org/bot<token>/sendMessage',
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true);
$curlConfig[CURLOPT_POSTFIELDS] = "chat_id=".$chat_id."&text='hi'";
curl_setopt_array($ch, $curlConfig);
$result = curl_exec($ch);
curl_close($ch);
问题出在哪里?