【发布时间】:2020-07-07 07:21:27
【问题描述】:
我正在尝试使用 reactphp 进行 长轮询。
我有一个函数 getNotifications 保持长时间轮询等待 Telegram 的响应。
此电报 api 可以保持请求打开直到 超时 或
如果有通知,可以在 50 秒结束前发送响应。
Telegram 回复后如何调用 getNotifications?
基本上我希望在有响应时再次调用 getNotifications。
这是我的代码,
谢谢大家
<?php
require "vendor/autoload.php";
use Clue\React\Buzz\Browser;
use Psr\Http\Message\ResponseInterface;
use React\EventLoop\LoopInterface;
$loop = React\EventLoop\Factory::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();
【问题讨论】:
-
你检查 cron 作业吗?
-
谢谢,但我不想使用 cron 作业。我想要一个带有事件循环的 php 文件,它以异步方式检查来自电报的更新,同时在我的代码中做其他事情,比如计时器。
-
是什么阻止你在回调后再次调用该函数?
-
我无权访问 $url、$browser、$loop
标签: php asynchronous telegram-bot long-polling reactphp