Completed
Push — develop ( 284b1e...4e511e )
by Armando
9s
created

Telegram::runCommands()   B

Complexity

Conditions 5
Paths 4

Size

Total Lines 45
Code Lines 27

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 30

Importance

Changes 0
Metric Value
dl 0
loc 45
ccs 0
cts 0
cp 0
rs 8.439
c 0
b 0
f 0
cc 5
eloc 27
nc 4
nop 1
crap 30
1
<?php
2
/**
3
 * This file is part of the TelegramBot package.
4
 *
5
 * (c) Avtandil Kikabidze aka LONGMAN <[email protected]>
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 */
10
11
namespace Longman\TelegramBot;
12
13 1
define('BASE_PATH', __DIR__);
14 1
define('BASE_COMMANDS_PATH', BASE_PATH . '/Commands');
15
16
use Exception;
17
use Longman\TelegramBot\Commands\Command;
18
use Longman\TelegramBot\Entities\ServerResponse;
19
use Longman\TelegramBot\Entities\Update;
20
use Longman\TelegramBot\Exception\TelegramException;
21
use PDO;
22
use RecursiveDirectoryIterator;
23
use RecursiveIteratorIterator;
24
use RegexIterator;
25
26
class Telegram
27
{
28
    /**
29
     * Version
30
     *
31
     * @var string
32
     */
33
    protected $version = '0.38.1';
34
35
    /**
36
     * Telegram API key
37
     *
38
     * @var string
39
     */
40
    protected $api_key = '';
41
42
    /**
43
     * Telegram Bot name
44
     *
45
     * @var string
46
     */
47
    protected $bot_name = '';
48
49
    /**
50
     * Raw request data (json) for webhook methods
51
     *
52
     * @var string
53
     */
54
    protected $input;
55
56
    /**
57
     * Custom commands paths
58
     *
59
     * @var array
60
     */
61
    protected $commands_paths = [];
62
63
    /**
64
     * Current Update object
65
     *
66
     * @var \Longman\TelegramBot\Entities\Update
67
     */
68
    protected $update;
69
70
    /**
71
     * Upload path
72
     *
73
     * @var string
74
     */
75
    protected $upload_path;
76
77
    /**
78
     * Download path
79
     *
80
     * @var string
81
     */
82
    protected $download_path;
83
84
    /**
85
     * MySQL integration
86
     *
87
     * @var boolean
88
     */
89
    protected $mysql_enabled = false;
90
91
    /**
92
     * PDO object
93
     *
94
     * @var \PDO
95
     */
96
    protected $pdo;
97
98
    /**
99
     * Commands config
100
     *
101
     * @var array
102
     */
103
    protected $commands_config = [];
104
105
    /**
106
     * Admins list
107
     *
108
     * @var array
109
     */
110
    protected $admins_list = [];
111
112
    /**
113
     * ServerResponse of the last Command execution
114
     *
115
     * @var \Longman\TelegramBot\Entities\ServerResponse
116
     */
117
    protected $last_command_response;
118
119
    /**
120
     * Botan.io integration
121
     *
122
     * @var boolean
123
     */
124
    protected $botan_enabled = false;
125
126
    /**
127
     * Telegram constructor.
128
     *
129
     * @param string $api_key
130
     * @param string $bot_name
131
     *
132
     * @throws \Longman\TelegramBot\Exception\TelegramException
133
     */
134 39
    public function __construct($api_key, $bot_name)
135
    {
136 39
        if (empty($api_key)) {
137 1
            throw new TelegramException('API KEY not defined!');
138
        }
139
140 39
        if (empty($bot_name)) {
141 1
            throw new TelegramException('Bot Username not defined!');
142
        }
143
144 39
        $this->api_key  = $api_key;
145 39
        $this->bot_name = $bot_name;
146
147
        //Set default download and upload path
148 39
        $this->setDownloadPath(BASE_PATH . '/../Download');
149 39
        $this->setUploadPath(BASE_PATH . '/../Upload');
150
151
        //Add default system commands path
152 39
        $this->addCommandsPath(BASE_COMMANDS_PATH . '/SystemCommands');
153
154 39
        Request::initialize($this);
155 39
    }
156
157
    /**
158
     * Initialize Database connection
159
     *
160
     * @param array  $credential
161
     * @param string $table_prefix
162
     * @param string $encoding
163
     *
164
     * @return \Longman\TelegramBot\Telegram
165
     * @throws \Longman\TelegramBot\Exception\TelegramException
166
     */
167 9 View Code Duplication
    public function enableMySql(array $credential, $table_prefix = null, $encoding = 'utf8mb4')
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
168
    {
169 9
        $this->pdo = DB::initialize($credential, $this, $table_prefix, $encoding);
170 9
        ConversationDB::initializeConversation();
171 9
        $this->mysql_enabled = true;
172
173 9
        return $this;
174
    }
175
176
    /**
177
     * Initialize Database external connection
178
     *
179
     * @param PDO    $external_pdo_connection PDO database object
180
     * @param string $table_prefix
181
     *
182
     * @return \Longman\TelegramBot\Telegram
183
     * @throws \Longman\TelegramBot\Exception\TelegramException
184
     */
185 View Code Duplication
    public function enableExternalMySql($external_pdo_connection, $table_prefix = null)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
186
    {
187
        $this->pdo = DB::externalInitialize($external_pdo_connection, $this, $table_prefix);
188
        ConversationDB::initializeConversation();
189
        $this->mysql_enabled = true;
190
191
        return $this;
192
    }
193
194
    /**
195
     * Get commands list
196
     *
197
     * @return array $commands
198
     * @throws \Longman\TelegramBot\Exception\TelegramException
199
     */
200 10
    public function getCommandsList()
201
    {
202 10
        $commands = [];
203
204 10
        foreach ($this->commands_paths as $path) {
205
            try {
206
                //Get all "*Command.php" files
207 10
                $files = new RegexIterator(
208 10
                    new RecursiveIteratorIterator(
209 10
                        new RecursiveDirectoryIterator($path)
210
                    ),
211 10
                    '/^.+Command.php$/'
212
                );
213
214 10
                foreach ($files as $file) {
215
                    //Remove "Command.php" from filename
216 10
                    $command      = $this->sanitizeCommand(substr($file->getFilename(), 0, -11));
217 10
                    $command_name = strtolower($command);
218
219 10
                    if (array_key_exists($command_name, $commands)) {
220
                        continue;
221
                    }
222
223 10
                    require_once $file->getPathname();
224
225 10
                    $command_obj = $this->getCommandObject($command);
226 10
                    if ($command_obj instanceof Command) {
227 10
                        $commands[$command_name] = $command_obj;
228
                    }
229
                }
230
            } catch (Exception $e) {
231 10
                throw new TelegramException('Error getting commands from path: ' . $path);
232
            }
233
        }
234
235 10
        return $commands;
236
    }
237
238
    /**
239
     * Get an object instance of the passed command
240
     *
241
     * @param string $command
242
     *
243
     * @return \Longman\TelegramBot\Commands\Command|null
244
     */
245 11
    public function getCommandObject($command)
246
    {
247 11
        $which = ['System'];
248 11
        $this->isAdmin() && $which[] = 'Admin';
249 11
        $which[] = 'User';
250
251 11
        foreach ($which as $auth) {
252 11
            $command_namespace = __NAMESPACE__ . '\\Commands\\' . $auth . 'Commands\\' . $this->ucfirstUnicode($command) . 'Command';
253 11
            if (class_exists($command_namespace)) {
254 11
                return new $command_namespace($this, $this->update);
255
            }
256
        }
257
258
        return null;
259
    }
260
261
    /**
262
     * Set custom input string for debug purposes
263
     *
264
     * @param string $input (json format)
265
     *
266
     * @return \Longman\TelegramBot\Telegram
267
     */
268
    public function setCustomInput($input)
269
    {
270
        $this->input = $input;
271
272
        return $this;
273
    }
274
275
    /**
276
     * Get custom input string for debug purposes
277
     *
278
     * @return string
279
     */
280
    public function getCustomInput()
281
    {
282
        return $this->input;
283
    }
284
285
    /**
286
     * Get the ServerResponse of the last Command execution
287
     *
288
     * @return \Longman\TelegramBot\Entities\ServerResponse
289
     */
290
    public function getLastCommandResponse()
291
    {
292
        return $this->last_command_response;
293
    }
294
295
    /**
296
     * Handle getUpdates method
297
     *
298
     * @param int|null $limit
299
     * @param int|null $timeout
300
     *
301
     * @return \Longman\TelegramBot\Entities\ServerResponse
302
     * @throws \Longman\TelegramBot\Exception\TelegramException
303
     */
304
    public function handleGetUpdates($limit = null, $timeout = null)
305
    {
306
        if (!DB::isDbConnected()) {
307
            return new ServerResponse(
308
                [
309
                    'ok'          => false,
310
                    'description' => 'getUpdates needs MySQL connection!',
311
                ],
312
                $this->bot_name
313
            );
314
        }
315
316
        //DB Query
317
        $last_update = DB::selectTelegramUpdate(1);
318
        $last_update = reset($last_update);
319
320
        //As explained in the telegram bot api documentation
321
        $offset = isset($last_update['id']) ? $last_update['id'] + 1 : null;
322
323
        $response = Request::getUpdates(
324
            [
325
                'offset'  => $offset,
326
                'limit'   => $limit,
327
                'timeout' => $timeout,
328
            ]
329
        );
330
331
        if ($response->isOk()) {
332
            //Process all updates
333
            /** @var Update $result */
334
            foreach ((array) $response->getResult() as $result) {
335
                $this->processUpdate($result);
336
            }
337
        }
338
339
        return $response;
340
    }
341
342
    /**
343
     * Handle bot request from webhook
344
     *
345
     * @return bool
346
     *
347
     * @throws \Longman\TelegramBot\Exception\TelegramException
348
     */
349
    public function handle()
350
    {
351
        $this->input = Request::getInput();
352
353
        if (empty($this->input)) {
354
            throw new TelegramException('Input is empty!');
355
        }
356
357
        $post = json_decode($this->input, true);
358
        if (empty($post)) {
359
            throw new TelegramException('Invalid JSON!');
360
        }
361
362
        if ($response = $this->processUpdate(new Update($post, $this->bot_name))) {
363
            return $response->isOk();
364
        }
365
366
        return false;
367
    }
368
369
    /**
370
     * Get the command name from the command type
371
     *
372
     * @param string $type
373
     *
374
     * @return string
375
     */
376
    private function getCommandFromType($type)
377
    {
378
        return $this->ucfirstUnicode(str_replace('_', '', $type));
379
    }
380
381
    /**
382
     * Process bot Update request
383
     *
384
     * @param \Longman\TelegramBot\Entities\Update $update
385
     *
386
     * @return \Longman\TelegramBot\Entities\ServerResponse
387
     * @throws \Longman\TelegramBot\Exception\TelegramException
388
     */
389
    public function processUpdate(Update $update)
390
    {
391
        $this->update = $update;
392
393
        //If all else fails, it's a generic message.
394
        $command = 'genericmessage';
395
396
        $update_type = $this->update->getUpdateType();
397
        if (in_array($update_type, ['edited_message', 'channel_post', 'edited_channel_post', 'inline_query', 'chosen_inline_result', 'callback_query'], true)) {
398
            $command = $this->getCommandFromType($update_type);
399
        } elseif ($update_type === 'message') {
400
            $message = $this->update->getMessage();
401
402
            //Load admin commands
403
            if ($this->isAdmin()) {
404
                $this->addCommandsPath(BASE_COMMANDS_PATH . '/AdminCommands', false);
405
            }
406
407
            $this->addCommandsPath(BASE_COMMANDS_PATH . '/UserCommands', false);
408
409
            $type = $message->getType();
410
            if ($type === 'command') {
411
                $command = $message->getCommand();
412
            } elseif (in_array($type, [
413
                'channel_chat_created',
414
                'delete_chat_photo',
415
                'group_chat_created',
416
                'left_chat_member',
417
                'migrate_from_chat_id',
418
                'migrate_to_chat_id',
419
                'new_chat_member',
420
                'new_chat_photo',
421
                'new_chat_title',
422
                'pinned_message',
423
                'supergroup_chat_created',
424
            ], true)
425
            ) {
426
                $command = $this->getCommandFromType($type);
427
            }
428
        }
429
430
        //Make sure we have an up-to-date command list
431
        //This is necessary to "require" all the necessary command files!
432
        $this->getCommandsList();
433
434
        DB::insertRequest($this->update);
435
436
        return $this->executeCommand($command);
0 ignored issues
show
Bug introduced by
It seems like $command defined by $message->getCommand() on line 411 can also be of type boolean; however, Longman\TelegramBot\Telegram::executeCommand() does only seem to accept string, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
437
    }
438
439
    /**
440
     * Execute /command
441
     *
442
     * @param string $command
443
     *
444
     * @return mixed
445
     * @throws \Longman\TelegramBot\Exception\TelegramException
446
     */
447
    public function executeCommand($command)
448
    {
449
        $command_obj = $this->getCommandObject($command);
450
451
        if (!$command_obj || !$command_obj->isEnabled()) {
452
            //Failsafe in case the Generic command can't be found
453
            if ($command === 'Generic') {
454
                throw new TelegramException('Generic command missing!');
455
            }
456
457
            //Handle a generic command or non existing one
458
            $this->last_command_response = $this->executeCommand('Generic');
459
        } else {
460
            //Botan.io integration, make sure only the actual command user executed is reported
461
            if ($this->botan_enabled) {
462
                Botan::lock($command);
463
            }
464
465
            //execute() method is executed after preExecute()
466
            //This is to prevent executing a DB query without a valid connection
467
            $this->last_command_response = $command_obj->preExecute();
468
469
            //Botan.io integration, send report after executing the command
470
            if ($this->botan_enabled) {
471
                Botan::track($this->update, $command);
472
            }
473
        }
474
475
        return $this->last_command_response;
476
    }
477
478
    /**
479
     * Sanitize Command
480
     *
481
     * @param string $command
482
     *
483
     * @return string
484
     */
485 10
    protected function sanitizeCommand($command)
486
    {
487 10
        return str_replace(' ', '', $this->ucwordsUnicode(str_replace('_', ' ', $command)));
488
    }
489
490
    /**
491
     * Enable a single Admin account
492
     *
493
     * @param integer $admin_id Single admin id
494
     *
495
     * @return \Longman\TelegramBot\Telegram
496
     */
497 1
    public function enableAdmin($admin_id)
498
    {
499 1
        if (is_int($admin_id) && $admin_id > 0 && !in_array($admin_id, $this->admins_list, true)) {
500 1
            $this->admins_list[] = $admin_id;
501
        } else {
502 1
            TelegramLog::error('Invalid value "%s" for admin.', $admin_id);
503
        }
504
505 1
        return $this;
506
    }
507
508
    /**
509
     * Enable a list of Admin Accounts
510
     *
511
     * @param array $admin_ids List of admin ids
512
     *
513
     * @return \Longman\TelegramBot\Telegram
514
     */
515 1
    public function enableAdmins(array $admin_ids)
516
    {
517 1
        foreach ($admin_ids as $admin_id) {
518 1
            $this->enableAdmin($admin_id);
519
        }
520
521 1
        return $this;
522
    }
523
524
    /**
525
     * Get list of admins
526
     *
527
     * @return array
528
     */
529 1
    public function getAdminList()
530
    {
531 1
        return $this->admins_list;
532
    }
533
534
    /**
535
     * Check if the passed user is an admin
536
     *
537
     * If no user id is passed, the current update is checked for a valid message sender.
538
     *
539
     * @param int|null $user_id
540
     *
541
     * @return bool
542
     */
543 11
    public function isAdmin($user_id = null)
544
    {
545 11
        if ($user_id === null && $this->update !== null) {
546
            //Try to figure out if the user is an admin
547
            $update_methods = [
548
                'getMessage',
549
                'getEditedMessage',
550
                'getChannelPost',
551
                'getEditedChannelPost',
552
                'getInlineQuery',
553
                'getChosenInlineResult',
554
                'getCallbackQuery',
555
            ];
556
            foreach ($update_methods as $update_method) {
557
                $object = call_user_func([$this->update, $update_method]);
558
                if ($object !== null && $from = $object->getFrom()) {
559
                    $user_id = $from->getId();
560
                    break;
561
                }
562
            }
563
        }
564
565 11
        return ($user_id === null) ? false : in_array($user_id, $this->admins_list, true);
566
    }
567
568
    /**
569
     * Check if user required the db connection
570
     *
571
     * @return bool
572
     */
573
    public function isDbEnabled()
574
    {
575
        if ($this->mysql_enabled) {
576
            return true;
577
        } else {
578
            return false;
579
        }
580
    }
581
582
    /**
583
     * Add a single custom commands path
584
     *
585
     * @param string $path   Custom commands path to add
586
     * @param bool   $before If the path should be prepended or appended to the list
587
     *
588
     * @return \Longman\TelegramBot\Telegram
589
     */
590 39
    public function addCommandsPath($path, $before = true)
591
    {
592 39
        if (!is_dir($path)) {
593 1
            TelegramLog::error('Commands path "%s" does not exist.', $path);
594 39
        } elseif (!in_array($path, $this->commands_paths, true)) {
595 39
            if ($before) {
596 39
                array_unshift($this->commands_paths, $path);
597
            } else {
598
                $this->commands_paths[] = $path;
599
            }
600
        }
601
602 39
        return $this;
603
    }
604
605
    /**
606
     * Add multiple custom commands paths
607
     *
608
     * @param array $paths  Custom commands paths to add
609
     * @param bool  $before If the paths should be prepended or appended to the list
610
     *
611
     * @return \Longman\TelegramBot\Telegram
612
     */
613 1
    public function addCommandsPaths(array $paths, $before = true)
614
    {
615 1
        foreach ($paths as $path) {
616 1
            $this->addCommandsPath($path, $before);
617
        }
618
619 1
        return $this;
620
    }
621
622
    /**
623
     * Set custom upload path
624
     *
625
     * @param string $path Custom upload path
626
     *
627
     * @return \Longman\TelegramBot\Telegram
628
     */
629 39
    public function setUploadPath($path)
630
    {
631 39
        $this->upload_path = $path;
632
633 39
        return $this;
634
    }
635
636
    /**
637
     * Get custom upload path
638
     *
639
     * @return string
640
     */
641
    public function getUploadPath()
642
    {
643
        return $this->upload_path;
644
    }
645
646
    /**
647
     * Set custom download path
648
     *
649
     * @param string $path Custom download path
650
     *
651
     * @return \Longman\TelegramBot\Telegram
652
     */
653 39
    public function setDownloadPath($path)
654
    {
655 39
        $this->download_path = $path;
656
657 39
        return $this;
658
    }
659
660
    /**
661
     * Get custom download path
662
     *
663
     * @return string
664
     */
665
    public function getDownloadPath()
666
    {
667
        return $this->download_path;
668
    }
669
670
    /**
671
     * Set command config
672
     *
673
     * Provide further variables to a particular commands.
674
     * For example you can add the channel name at the command /sendtochannel
675
     * Or you can add the api key for external service.
676
     *
677
     * @param string $command
678
     * @param array  $config
679
     *
680
     * @return \Longman\TelegramBot\Telegram
681
     */
682 13
    public function setCommandConfig($command, array $config)
683
    {
684 13
        $this->commands_config[$command] = $config;
685
686 13
        return $this;
687
    }
688
689
    /**
690
     * Get command config
691
     *
692
     * @param string $command
693
     *
694
     * @return array
695
     */
696 24
    public function getCommandConfig($command)
697
    {
698 24
        return isset($this->commands_config[$command]) ? $this->commands_config[$command] : [];
699
    }
700
701
    /**
702
     * Get API key
703
     *
704
     * @return string
705
     */
706 1
    public function getApiKey()
707
    {
708 1
        return $this->api_key;
709
    }
710
711
    /**
712
     * Get Bot name
713
     *
714
     * @return string
715
     */
716 6
    public function getBotName()
717
    {
718 6
        return $this->bot_name;
719
    }
720
721
    /**
722
     * Get Version
723
     *
724
     * @return string
725
     */
726 1
    public function getVersion()
727
    {
728 1
        return $this->version;
729
    }
730
731
    /**
732
     * Set Webhook for bot
733
     *
734
     * @param string $url
735
     * @param array  $data Optional parameters.
736
     *
737
     * @return \Longman\TelegramBot\Entities\ServerResponse
738
     * @throws \Longman\TelegramBot\Exception\TelegramException
739
     */
740
    public function setWebhook($url, array $data = [])
741
    {
742
        if (empty($url)) {
743
            throw new TelegramException('Hook url is empty!');
744
        }
745
746
        $result = Request::setWebhook($url, $data);
747
748 View Code Duplication
        if (!$result->isOk()) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
749
            throw new TelegramException(
750
                'Webhook was not set! Error: ' . $result->getErrorCode() . ' ' . $result->getDescription()
751
            );
752
        }
753
754
        return $result;
755
    }
756
757
    /**
758
     * Deprecated alias for deleteWebhook
759
     *
760
     * This is kept for backwards compatibility!
761
     *
762
     * @return mixed
763
     * @throws \Longman\TelegramBot\Exception\TelegramException
764
     */
765
    public function unsetWebhook()
766
    {
767
        return $this->deleteWebhook();
768
    }
769
770
    /**
771
     * Delete any assigned webhook
772
     *
773
     * @return mixed
774
     * @throws \Longman\TelegramBot\Exception\TelegramException
775
     */
776
    public function deleteWebhook()
777
    {
778
        $result = Request::deleteWebhook();
779
780 View Code Duplication
        if (!$result->isOk()) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
781
            throw new TelegramException(
782
                'Webhook was not deleted! Error: ' . $result->getErrorCode() . ' ' . $result->getDescription()
783
            );
784
        }
785
786
        return $result;
787
    }
788
789
    /**
790
     * Replace function `ucwords` for UTF-8 characters in the class definition and commands
791
     *
792
     * @param string $str
793
     * @param string $encoding (default = 'UTF-8')
794
     *
795
     * @return string
796
     */
797 10
    protected function ucwordsUnicode($str, $encoding = 'UTF-8')
798
    {
799 10
        return mb_convert_case($str, MB_CASE_TITLE, $encoding);
800
    }
801
802
    /**
803
     * Replace function `ucfirst` for UTF-8 characters in the class definition and commands
804
     *
805
     * @param string $str
806
     * @param string $encoding (default = 'UTF-8')
807
     *
808
     * @return string
809
     */
810 11
    protected function ucfirstUnicode($str, $encoding = 'UTF-8')
811
    {
812
        return
813 11
            mb_strtoupper(mb_substr($str, 0, 1, $encoding), $encoding)
814 11
            . mb_strtolower(mb_substr($str, 1, mb_strlen($str), $encoding), $encoding);
815
    }
816
817
    /**
818
     * Enable Botan.io integration
819
     *
820
     * @param  string $token
821
     * @param  array $options
822
     *
823
     * @return \Longman\TelegramBot\Telegram
824
     * @throws \Longman\TelegramBot\Exception\TelegramException
825
     */
826
    public function enableBotan($token, array $options = [])
827
    {
828
        Botan::initializeBotan($token, $options);
829
        $this->botan_enabled = true;
830
831
        return $this;
832
    }
833
834
    /**
835
     * Run provided commands
836
     *
837
     * @param array $commands
838
     *
839
     * @throws TelegramException
840
     */
841
    public function runCommands($commands)
842
    {
843
        if (!is_array($commands) || empty($commands)) {
844
            throw new TelegramException('No command(s) provided!');
845
        }
846
847
        $this->botan_enabled = false;   // Force disable Botan.io integration, we don't want to track self-executed commands!
848
849
        $result = Request::getMe()->getResult();
850
851
        if (!$result->getId()) {
852
            throw new TelegramException('Received empty/invalid getMe result!');
853
        }
854
855
        $bot_id       = $result->getId();
856
        $bot_name     = $result->getFirstName();
857
        $bot_username = $result->getUsername();
858
859
        $this->enableAdmin($bot_id);    // Give bot access to admin commands
860
        $this->getCommandsList();       // Load full commands list
861
862
        foreach ($commands as $command) {
863
            $this->update = new Update(
864
                [
865
                    'update_id' => 0,
866
                    'message'   => [
867
                        'message_id' => 0,
868
                        'from'       => [
869
                            'id'         => $bot_id,
870
                            'first_name' => $bot_name,
871
                            'username'   => $bot_username
872
                        ],
873
                        'date'       => time(),
874
                        'chat'       => [
875
                            'id'   => $bot_id,
876
                            'type' => 'private',
877
                        ],
878
                        'text'       => $command
879
                    ]
880
                ]
881
            );
882
883
            $this->executeCommand($this->update->getMessage()->getCommand());
0 ignored issues
show
Bug introduced by
It seems like $this->update->getMessage()->getCommand() targeting Longman\TelegramBot\Entities\Message::getCommand() can also be of type boolean; however, Longman\TelegramBot\Telegram::executeCommand() does only seem to accept string, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
884
        }
885
    }
886
}
887