【问题标题】:Long polling telegram with ReactPHP async使用 ReactPHP 异步的长轮询电报
【发布时间】: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


【解决方案1】:

好的,我找到了解决方案。要将参数传递给匿名函数,我需要使用 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);
});

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-26
    • 2012-02-24
    • 2014-04-25
    • 2019-08-14
    • 2021-01-18
    • 2017-09-09
    • 1970-01-01
    • 2015-10-28
    相关资源
    最近更新 更多