TelegramApiServer/examples/websocket-events.php

47 lines
1.3 KiB
PHP
Raw Normal View History

2020-01-12 20:25:12 +01:00
<?php
/**
* Get all updates from MadelineProto EventHandler running inside TelegramApiServer via websocket
* @see \TelegramApiServer\Controllers\EventsController
*/
require 'vendor/autoload.php';
use Amp\Websocket\Client\Connection;
use Amp\Websocket\Message;
use function Amp\Websocket\Client\connect;
$shortopts = 'u::';
$longopts = [
'url::',
];
$options = getopt($shortopts, $longopts);
$options = [
'url' => $options['url'] ?? $options['u'] ?? 'ws://127.0.0.1:9503/events',
];
Amp\Loop::run(static function () use($options) {
2020-01-12 20:25:12 +01:00
echo "Connecting to: {$options['url']}" . PHP_EOL;
2021-02-26 23:29:44 +01:00
while(true) {
try {
/** @var Connection $connection */
$connection = yield connect($options['url']);
$connection->onClose(static function() use($connection) {
printf("Connection closed. Reason: %s\n", $connection->getCloseReason());
});
echo 'Waiting for events...' . PHP_EOL;
while ($message = yield $connection->receive()) {
/** @var Message $message */
$payload = yield $message->buffer();
printf("Received event: %s\n", $payload);
}
} catch (\Throwable $e) {
printf("Error: %s\n", $e->getMessage());
2020-01-13 22:01:48 +01:00
}
2021-02-26 23:29:44 +01:00
yield new Amp\Delayed(500);
2020-01-12 20:25:12 +01:00
}
2020-01-13 22:01:48 +01:00
2020-01-12 20:25:12 +01:00
});