Symfony 4 WS Получение оповещения от консольной команды
WebSocket поднимаю на основе Symfony приложения консольной командой.
После поднятия сервера сокетов выполняю дополнительную консольную команду, которая опрашивает телеграм на наличие новых сообщений.
При наличии нового сообщения от телеграма необходимо в определенный сокет отправить ответ (на данном этапе - хотя-бы hello world)
Консольная команда Symfony поднимающая сокеты:
$server = IoServer::factory(new HttpServer(
new WsServer(
new Notification($this->getContainer())
)
), 8080);
$server->run();
Класс Notification:
class Notification implements MessageComponentInterface
{
const AUTH_TYPE = "auth";
const MESSAGE_TYPE = "message";
protected $connections = array();
protected $container;
/**
* @var Session
*/
private $session;
public function __construct(ContainerInterface $container)
{
$this->container = $container;
}
/**
* A new websocket connection
*
* @param ConnectionInterface $conn
*/
public function onOpen(ConnectionInterface $conn)
{
$this->connections[] = $conn;
$conn->send('..:: Hello from the Notification Center ::..');
}
/**
* Handle message sending
*
* @param ConnectionInterface $from
* @param string $msg
* @throws \TelegramBot\Api\Exception
* @throws InvalidArgumentException
*/
public function onMessage(ConnectionInterface $from, $msg)
{
$messageService = new MessageService($from);
$messageData = json_decode(trim($msg));
$messageType = $messageData->type;
$messageContent = $messageData->content;
switch ($messageType) {
case Notification::MESSAGE_TYPE:
{
$messageService->handleMessage($messageContent);
break;
}
case Notification::AUTH_TYPE:
{
$index_connection = uniqid("user_");
$all_connections = $this->connections;
foreach ($all_connections as $key => $conn) {
if ($conn === $from) {
$this->connections[$index_connection] = $from;
$from->send('..:: Connected as ' . $index_connection . ' ::..');
unset($this->connections[$key]);
break;
} else {
continue;
}
}
break;
}
}
}
/**
* A connection is closed
* @param ConnectionInterface $conn
*/
public function onClose(ConnectionInterface $conn)
{
foreach ($this->connections as $key => $conn_element) {
if ($conn === $conn_element) {
unset($this->connections[$key]);
break;
}
}
}
/**
* Error handling
*
* @param ConnectionInterface $conn
* @param Exception $e
*/
public function onError(ConnectionInterface $conn, Exception $e)
{
$conn->send("Error : " . $e->getMessage());
$conn->close();
}
}
Команда запускающая телеграм бота:
$bot = new \App\Service\TelegramBotService($this->telegramToken);
$bot->command('ping', function ($message) use ($botApi) {
$bot->sendMessage($message->chat->id, 'pong!');
});
$bot->run();
Пытался добавить сессии, добавить event listener - ничего не вышло. Нет идей даже как эту ситуацию правильно загуглить.