ReactPHP异步长轮询电报



我正在尝试使用reactphp进行长轮询

我有一个函数getNotifications,它会在长时间轮询中等待Telegram的响应

此电报api可以保持请求打开,直到超时或如果有通知,可以在50秒结束前发送响应

Telegram回复后,我如何回忆getNotifications?基本上,我希望在有响应时再次调用getNotifications

这是我的代码,
感谢所有

<?php
require "vendor/autoload.php";
use ClueReactBuzzBrowser;
use PsrHttpMessageResponseInterface;
use ReactEventLoopLoopInterface;
$loop = ReactEventLoopFactory::create();
$browser = new Browser($loop);
$method = "getUpdates";
$timeout = 50;
$params = [
"offset" => 550495530,
"limit" => 1000,
"timeout" => $timeout
];
$bot_key = "your bot token";
$query = http_build_query($params);
$url = "https://api.telegram.org/bot" . $bot_key . "/" . $method . "?" . $query;
$browser = $browser->withOptions(array(
'timeout' => $timeout
));
function callback(){
echo "done";
}
function getNotifications($url, $browser, LoopInterface $loop){
$browser->get($url)->then(function (ResponseInterface $response) {
// response received within 50 seconds. Telegram longpolling
var_dump((string)$response->getBody());
callback();
});
}
function timer($start, LoopInterface $loop)
{
//Timer only used to count seconds
$loop->addPeriodicTimer(1.0, function ($timer) use (&$start, $loop) {
echo "tick ". $start++ . "n";
});
}
timer(0, $loop);
getNotifications($url, $browser, $loop);
$loop->run();

好的,我找到了解决方案。要将参数传递给匿名函数,我需要使用use关键字。然后在函数内部,我可以正确地访问变量。

function getNotifications($url, $browser, LoopInterface $loop){
$browser->get($url)->then(function (ResponseInterface $response) use ($url, $browser,$loop) {
// response received within 50 seconds. Telegram longpolling
var_dump((string)$response->getBody());
callback();
getNotifications($url, $browser,$loop);
});

}

最新更新