From da553c3bc99bd982f17463f33ac41822878a6895 Mon Sep 17 00:00:00 2001 From: netkas Date: Fri, 1 Nov 2024 15:47:02 -0400 Subject: [PATCH] Add PollingBot class to handle Telegram polling updates --- src/TgBotLib/PollingBot.php | 109 ++++++++++++++++++++++++++++++++++++ 1 file changed, 109 insertions(+) create mode 100644 src/TgBotLib/PollingBot.php diff --git a/src/TgBotLib/PollingBot.php b/src/TgBotLib/PollingBot.php new file mode 100644 index 0000000..0fc062e --- /dev/null +++ b/src/TgBotLib/PollingBot.php @@ -0,0 +1,109 @@ +offset = null; + $this->limit = 100; + $this->timeout = 0; + $this->allowedUpdates = []; + } + + public function setOffset(int $offset): void + { + $this->offset = $offset; + } + + public function getOffset(): int + { + return $this->offset; + } + + public function setLimit(int $limit): void + { + $this->limit = $limit; + } + + public function getLimit(): int + { + return $this->limit; + } + + public function setTimeout(int $timeout): void + { + $this->timeout = $timeout; + } + + public function getTimeout(): int + { + return $this->timeout; + } + + public function setAllowedUpdates(array $allowedUpdates): void + { + $this->allowedUpdates = $allowedUpdates; + } + + public function getAllowedUpdates(): array + { + return $this->allowedUpdates; + } + + public function addAllowedUpdate(string $allowedUpdate): void + { + if(in_array($allowedUpdate, $this->allowedUpdates)) + { + return; + } + + $this->allowedUpdates[] = $allowedUpdate; + } + + public function handleUpdates(): void + { + foreach($this->getUpdates(offset: ($this->offset ?: 0), limit: $this->limit, timeout: $this->timeout, allowed_updates: $this->retrieveAllowedUpdates()) as $update) + { + // Update the last offset if the current Update ID is greater than the offset ID + if($update->getUpdateId() > $this->offset) + { + $this->offset = $update->getUpdateId() + 1; + } + + /** @var UpdateEvent $eventHandler */ + foreach($this->getEventHandlersByType(Utilities::determineEventType($update)) as $eventHandler) + { + (new $eventHandler($update))->handle($this); + } + } + } + + private function retrieveAllowedUpdates(): ?array + { + if(count($this->allowedUpdates) === 0) + { + return null; + } + + return $this->allowedUpdates; + } + } \ No newline at end of file