如何处理 PHP 中的多个请求?

How to handle multiple requests in PHP?

我正在使用下面的代码在 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);

问题出在哪里?

正如评论中所说,您可以使用简单的打印语句在每个命令后输出(记录)时间戳。通过查看差异,您可以了解每个命令花费的时间。这应该足以识别简单函数中耗时的步骤。

另一种方法是使用探查器。 XDebug 有一个内置的。但你必须设置它,我怀疑这是否合理只是为了找出哪个步骤需要这么长时间......

然而,在我看来最优雅的想法是使用 php 中一个鲜为人知的功能:ticks ;-)

这允许注册一个 "tick" 函数一次,并在执行每个命令时自动输出一个刻度。这使您不必弄乱代码。该文档提供了一个很好的例子。

Telegram 机器人以两种不同的方式工作:

  • 直接https请求(必须设置ssl证书);
  • 长轮询请求(您的脚本继续搜索更新)。

在前一种情况下,您设置了一个 webhook,在后者中,您不需要它,只需使用 getUpdates API 方法进行轮询。 好吧,你正在获取输入流,所以我猜你正在使用第一个推荐的方法,它比轮询更快,因为你收到实时请求并且你能够即时管理它。 Telegram 向您发送 JSON,其中包含您必须在同一请求期间处理的一个或多个元素,以避免更多连续消息之间的延迟:

// receives the request from telegram server
$message = json_decode(file_get_contents('php://input'), true);

// if it's not a valid JSON return
if(is_null($message)) return;

// check if data received doesn't contain telegram-side errors
if (!$message["ok"]) { return; }

// define remote endpoint
$endpoint = "https://api.telegram.org/bot<token>/";

// process each message contained in JSON request 
foreach ($message["result"] as $request) {

    // make sure if text and chat_id is set into the payload
    if(!isset($request["message"]["text"]) || !isset($request["message"]["chat"]["id"])) return;

    // remove special characters, needed for the interpreter apparently
    $text = $request["message"]["text"];
    //$text = str_replace(["\r", "\n", "\t"], ' ', $text);
    // saving chat_id for convenience
    $chat_id = $request["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");

}

让我知道这是否会减少延迟,祝开发者愉快! :)