Polling::startPolling()   A
last analyzed

Complexity

Conditions 5
Paths 1

Size

Total Lines 37
Code Lines 27

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 5
eloc 27
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 37
rs 9.1768
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Zanzara\UpdateMode;
6
7
use Zanzara\Context;
8
use Zanzara\Telegram\Type\Response\TelegramException;
9
use Zanzara\Telegram\Type\Update;
10
use Zanzara\Telegram\Type\Webhook\WebhookInfo;
11
12
/**
13
 *
14
 */
15
class Polling extends UpdateMode
16
{
17
18
    /**
19
     * @inheritDoc
20
     */
21
    public function run()
22
    {
23
        $this->telegram->getWebhookInfo()->then(
24
            function (WebhookInfo $webhookInfo) {
25
                if (!$webhookInfo->getUrl()) {
26
                    $this->loop->futureTick([$this, 'startPolling']);
27
                    $this->logger->logIsListening();
28
                    return;
29
                }
30
                $message = "Your bot has a webhook set, please delete it before running Zanzara in polling mode. " .
31
                    "See https://core.telegram.org/bots/api#deletewebhook";
32
                $this->logger->error($message);
33
                echo "Type 'yes' if you want to delete the webhook: ";
34
                $answer = readline();
35
                if (strtoupper($answer) === "YES") {
36
                    $this->telegram->deleteWebhook()->then(
37
                        function ($res) {
38
                            if ($res === true) {
39
                                $this->logger->info("Webhook is deleted, Zanzara is starting in polling ...");
40
                                $this->loop->futureTick([$this, 'startPolling']);
41
                                echo "{$this->logger->getIsListening()}\n";
42
                            } else {
43
                                $this->logger->error("Error deleting webhook");
44
                            }
45
                        }
46
                    );
47
                } else {
48
                    $this->logger->error("Shutdown, you have to manually delete the webhook or start in webhook mode");
49
                }
50
            });
51
    }
52
53
    /**
54
     * @param int $offset
55
     */
56
    public function startPolling(int $offset = 1)
57
    {
58
        $processingUpdate = null;
59
        $this->telegram->getUpdates([
60
            'offset' => $offset,
61
            'limit' => $this->config->getPollingLimit(),
62
            'timeout' => $this->config->getPollingTimeout(),
63
            'allowed_updates' => $this->config->getPollingAllowedUpdates(),
64
        ])->then(function (array $updates) use (&$offset, &$processingUpdate) {
65
            if ($offset === 1) {
66
                //first run I need to get the current updateId from telegram
67
                $lastUpdate = end($updates);
68
                if ($lastUpdate) {
69
                    $offset = $lastUpdate->getUpdateId();
70
                }
71
                $this->startPolling($offset);
72
            } else {
73
                /** @var Update[] $updates */
74
                foreach ($updates as $update) {
75
                    // increase the offset before executing the update, this way if the update processing fails
76
                    // the framework doesn't try to execute it endlessly
77
                    $offset++;
78
                    $processingUpdate = $update;
79
                    $this->processUpdate($update);
80
                }
81
                $this->startPolling($offset);
82
            }
83
        }, function (TelegramException $error) use (&$offset) {
84
            $this->logger->error("Failed to fetch updates from Telegram: $error");
85
            $this->startPolling($offset); // consider place a delay before restarting to poll
86
        })->/** @scrutinizer ignore-call */ otherwise(function ($e) use (&$offset, &$processingUpdate) {
87
            $this->logger->errorUpdate($e);
88
            $errorHandler = $this->config->getErrorHandler();
89
            if ($errorHandler) {
90
                $errorHandler($e, new Context($processingUpdate, $this->container));
91
            }
92
            $this->startPolling($offset); // consider place a delay before restarting to poll
93
        });
94
    }
95
96
}
97