Skip to content

Commit 956a43c

Browse files
committed
Better fetch command
1 parent 7f5cb8c commit 956a43c

File tree

1 file changed

+38
-11
lines changed

1 file changed

+38
-11
lines changed

src/Console/Commands/TelegramFetchCommand.php

Lines changed: 38 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -5,39 +5,66 @@
55

66

77
use Illuminate\Console\Command;
8+
use Longman\TelegramBot\Entities\Update;
89
use Longman\TelegramBot\Exception\TelegramException;
910
use Longman\TelegramBot\Telegram;
1011
use Symfony\Component\Console\Command\SignalableCommandInterface;
1112

1213
class TelegramFetchCommand extends Command implements SignalableCommandInterface
1314
{
1415

15-
protected $signature = 'telegram:fetch';
16+
protected $signature = 'telegram:fetch
17+
{--a|all-update-types : Explicitly allow all updates (including "chat_member")}
18+
{--allowed-updates= : Define allowed updates (comma-seperated)}';
1619

1720
protected $description = 'Fetches Telegram updates periodically';
1821

1922
protected bool $shallExit = false;
2023

24+
protected ?int $childPid = null;
25+
2126
public function handle(Telegram $bot)
2227
{
2328
$this->callSilent('telegram:delete-webhook');
2429

2530
$options = [
26-
'timeout' => 5
31+
'timeout' => 30
2732
];
2833

29-
$this->info("Start fetching updates...\n<comment>(Exit with Ctrl + C. This can take a few seconds.)</comment>");
30-
while (true) {
31-
if ($this->shallExit) {
32-
break;
34+
// allowed_updates
35+
if ($this->option('all-update-types')) {
36+
$options['allowed_updates'] = Update::getUpdateTypes();
37+
} elseif ($allowedUpdates = $this->option('allowed-updates')) {
38+
$options['allowed_updates'] = str($allowedUpdates)->explode(',');
39+
}
40+
41+
$this->info("Start fetching updates...\n<comment>(Exit with Ctrl + C.)</comment>");
42+
43+
if ($this->childPid = pcntl_fork()) {
44+
// Parent process
45+
46+
while (true) {
47+
48+
if ($this->shallExit) {
49+
exec('kill -9 ' . $this->childPid);
50+
break;
51+
}
52+
3353
}
3454

35-
try {
36-
$bot->handleGetUpdates($options);
37-
} catch (TelegramException $e) {
38-
// Only print message
39-
$this->error($e->getMessage());
55+
} else {
56+
// Child process
57+
58+
while (true) {
59+
60+
$response = rescue(fn() => $bot->handleGetUpdates($options));
61+
62+
if ($response !== null && ! $response->isOk()) {
63+
$this->error($response->getDescription());
64+
}
65+
4066
}
67+
4168
}
4269
}
4370

0 commit comments

Comments
 (0)