TelegramApiServer/examples/websocket-events.php

58 lines
1.5 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
*/
use Amp\Websocket\Client\WebsocketHandshake;
2023-06-23 20:27:26 +02:00
use Revolt\EventLoop;
use function Amp\async;
use function Amp\delay;
use function Amp\Websocket\Client\connect;
2020-01-12 20:25:12 +01:00
require 'vendor/autoload.php';
$shortopts = 'u::';
$longopts = [
'url::',
];
$options = getopt($shortopts, $longopts);
$options = [
'url' => $options['url'] ?? $options['u'] ?? 'ws://127.0.0.1:9503/events',
];
echo "Connecting to: {$options['url']}" . PHP_EOL;
2020-01-12 20:25:12 +01:00
2023-04-11 01:56:45 +02:00
async(function () use ($options) {
2022-06-05 00:21:08 +02:00
while (true) {
2021-02-26 23:29:44 +01:00
try {
$handshake = (new WebsocketHandshake($options['url']));
$connection = connect($handshake);
2021-02-26 23:29:44 +01:00
$connection->onClose(static function () use ($connection) {
if ($connection->isClosed()) {
printf("Connection closed. Reason: %s\n", $connection->getCloseReason());
}
2021-02-26 23:29:44 +01:00
});
echo 'Waiting for events...' . PHP_EOL;
while ($message = $connection->receive()) {
$payload = $message->buffer();
2022-06-05 00:21:08 +02:00
printf("[%s] Received event: %s\n", date('Y-m-d H:i:s'), $payload);
2021-02-26 23:29:44 +01:00
}
2023-04-11 01:56:45 +02:00
} catch (Throwable $e) {
2021-02-26 23:29:44 +01:00
printf("Error: %s\n", $e->getMessage());
2020-01-13 22:01:48 +01:00
}
delay(0.1);
2020-01-12 20:25:12 +01:00
}
});
2020-01-13 22:01:48 +01:00
2023-06-23 20:27:26 +02:00
if (defined('SIGINT')) {
$signal = Amp\trapSignal([SIGINT, SIGTERM]);
} else {
EventLoop::run();
}