diff --git a/src/Command/Telegram/GetUpdatesCommand.php b/src/Command/Telegram/GetUpdatesCommand.php new file mode 100644 index 0000000..bec9274 --- /dev/null +++ b/src/Command/Telegram/GetUpdatesCommand.php @@ -0,0 +1,62 @@ +setDescription('Handles a Telegram updates via long polling'); + $this->setAliases([ + 'tg:handle-updates' + ]); + } + + protected function execute(InputInterface $input, OutputInterface $output): int + { + $io = new SymfonyStyle($input, $output); + $io->title("Starting a telegram update handling"); + + $lastUpdateId = -1; + while (true) { + try { + $updates = $this->telegram->getUpdates( + offset: $lastUpdateId + 1, + timeout: 30 + ); + + $io->text(sprintf('Handled %d updates', count($updates))); + + foreach ($updates as $update) { + $lastUpdateId = $update->id->getValue(); + $this->eventDispatcher->dispatch(new UpdateEvent($update), UpdateEvent::NAME); + } + } catch (Throwable $e) { + $io->error($e->getMessage()); + break; + } + } + + return Command::FAILURE; + } +} diff --git a/src/Event/Telegram/UpdateEvent.php b/src/Event/Telegram/UpdateEvent.php new file mode 100644 index 0000000..a78b5d4 --- /dev/null +++ b/src/Event/Telegram/UpdateEvent.php @@ -0,0 +1,27 @@ +update; + } +} diff --git a/tests-src/Command/Telegram/GetUpdatesCommandTest.php b/tests-src/Command/Telegram/GetUpdatesCommandTest.php new file mode 100644 index 0000000..6499910 --- /dev/null +++ b/tests-src/Command/Telegram/GetUpdatesCommandTest.php @@ -0,0 +1,50 @@ +createMock(EventDispatcherInterface::class); + $command = new GetUpdatesCommand($eventDispatcher, $botApi); + $commandTester = new CommandTester($command); + + $botApi + ->method('getUpdates') + ->willReturn( + new Updates([ + new Update( + new Update\Id(10) + ) + ]) + ); + + $eventDispatcher + ->method('dispatch') + ->willThrowException(new JsonException()); + + $commandTester->execute([]); + + self::assertEquals( + Command::FAILURE, + $commandTester->execute([]) + ); + } +} diff --git a/tests-src/Event/Telegram/UpdateEventTest.php b/tests-src/Event/Telegram/UpdateEventTest.php new file mode 100644 index 0000000..83e06c5 --- /dev/null +++ b/tests-src/Event/Telegram/UpdateEventTest.php @@ -0,0 +1,26 @@ +assertEquals( + 10, + $event->getUpdate()->id->getValue() + ); + } +}