How to handle multiple requests in PHP?

亡梦爱人 提交于 2019-12-24 15:21:00

问题


I'm using the below code to make a simple telegram bot in 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");

But the problem is responding to multiple requests in same time. Users aren't receiving responses in real time (delay). I'm sure that the last line causes the delay and waits for respond of telegram servers. How can I figure out that?

Update I found this code but it still has delay:

$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);

Where is the problem?


回答1:


AS said in the comments you can use a simple print statement to output (log) a timestamp after each command. By looking at the differences you see how long each command took. That should be enough jsut to identify the time consuming step in a simple function.

An alternative would be to use a profiler. XDebug has one built in. But you have to set that up, I doubt that is justified just to find out which step takes so long...

However the most elegant idea in my eyes is to use a little known feature in php: ticks ;-)

This allows to register a "tick" function once and have automatically output a tick with each command executed. This saves you from having to mess your code. The documentation gives a good example.




回答2:


Telegram Bots work in two different ways:

  • Direct https requests (you have to set-up a ssl certificate);
  • Long polling requests (your script continues to search for updates).

In the former case you set a webhook, in the latter you don't need it, just polling with getUpdates API method. Well, you're getting input stream, so I guess you're using the first recommended method, which is faster than polling because you receive real time request and you're able to manage it on the fly. Telegram sends you that JSON with one or more elements that you have to process during the same request in order to avoid delay between more consecutive messages:

// 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");

}

Let me know if this reduces delay, happy dev! :)



来源:https://stackoverflow.com/questions/31815502/how-to-handle-multiple-requests-in-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!