【发布时间】:2016-03-23 21:42:53
【问题描述】:
我正在使用下面的代码在 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);
问题出在哪里?
【问题讨论】:
-
按每一步计时。您只需在每个命令后记录一个时间戳。
-
@arkascha 谢谢。您能否进一步解释或给我一个 php 手册中的链接? :)
-
file_get_contents()是一个阻塞调用。您正在编写同步代码。知道这对你来说可能是一个有用的开始:-) -
@jimbo 谢谢。其实这不是我自己的代码。我在网上找到的;)
标签: php telegram-bot