Completed
Push — 811-helper_for_media_groups ( d77b66 )
by Armando
02:52
created

Telegram::getCustomInput()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 0
cts 2
cp 0
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
crap 2
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
defined('TB_BASE_PATH') || define('TB_BASE_PATH', __DIR__);
14 1
defined('TB_BASE_COMMANDS_PATH') || define('TB_BASE_COMMANDS_PATH', TB_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.55.1';
34
35
    /**
36
     * Telegram API key
37
     *
38
     * @var string
39
     */
40
    protected $api_key = '';
41
42
    /**
43
     * Telegram Bot username
44
     *
45
     * @var string
46
     */
47
    protected $bot_username = '';
48
49
    /**
50
     * Telegram Bot id
51
     *
52
     * @var string
53
     */
54
    protected $bot_id = '';
55
56
    /**
57
     * Raw request data (json) for webhook methods
58
     *
59
     * @var string
60
     */
61
    protected $input;
62
63
    /**
64
     * Custom commands paths
65
     *
66
     * @var array
67
     */
68
    protected $commands_paths = [];
69
70
    /**
71
     * Current Update object
72
     *
73
     * @var \Longman\TelegramBot\Entities\Update
74
     */
75
    protected $update;
76
77
    /**
78
     * Upload path
79
     *
80
     * @var string
81
     */
82
    protected $upload_path;
83
84
    /**
85
     * Download path
86
     *
87
     * @var string
88
     */
89
    protected $download_path;
90
91
    /**
92
     * MySQL integration
93
     *
94
     * @var boolean
95
     */
96
    protected $mysql_enabled = false;
97
98
    /**
99
     * PDO object
100
     *
101
     * @var \PDO
102
     */
103
    protected $pdo;
104
105
    /**
106
     * Commands config
107
     *
108
     * @var array
109
     */
110
    protected $commands_config = [];
111
112
    /**
113
     * Admins list
114
     *
115
     * @var array
116
     */
117
    protected $admins_list = [];
118
119
    /**
120
     * ServerResponse of the last Command execution
121
     *
122
     * @var \Longman\TelegramBot\Entities\ServerResponse
123
     */
124
    protected $last_command_response;
125
126
    /**
127
     * Check if runCommands() is running in this session
128
     *
129
     * @var boolean
130
     */
131
    protected $run_commands = false;
132
133
    /**
134
     * Is running getUpdates without DB enabled
135
     *
136
     * @var bool
137
     */
138
    protected $getupdates_without_database = false;
139
140
    /**
141
     * Last update ID
142
     * Only used when running getUpdates without a database
143
     *
144
     * @var integer
145
     */
146
    protected $last_update_id = null;
147
148
    /**
149
     * Telegram constructor.
150
     *
151
     * @param string $api_key
152
     * @param string $bot_username
153
     *
154
     * @throws \Longman\TelegramBot\Exception\TelegramException
155
     */
156 30
    public function __construct($api_key, $bot_username = '')
157
    {
158 30
        if (empty($api_key)) {
159 1
            throw new TelegramException('API KEY not defined!');
160
        }
161 30
        preg_match('/(\d+)\:[\w\-]+/', $api_key, $matches);
162 30
        if (!isset($matches[1])) {
163 1
            throw new TelegramException('Invalid API KEY defined!');
164
        }
165 30
        $this->bot_id  = $matches[1];
166 30
        $this->api_key = $api_key;
167
168 30
        if (!empty($bot_username)) {
169 30
            $this->bot_username = $bot_username;
170
        }
171
172
        //Add default system commands path
173 30
        $this->addCommandsPath(TB_BASE_COMMANDS_PATH . '/SystemCommands');
174
175 30
        Request::initialize($this);
176 30
    }
177
178
    /**
179
     * Initialize Database connection
180
     *
181
     * @param array  $credential
182
     * @param string $table_prefix
183
     * @param string $encoding
184
     *
185
     * @return \Longman\TelegramBot\Telegram
186
     * @throws \Longman\TelegramBot\Exception\TelegramException
187
     */
188 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...
189
    {
190 9
        $this->pdo = DB::initialize($credential, $this, $table_prefix, $encoding);
191 9
        ConversationDB::initializeConversation();
192 9
        $this->mysql_enabled = true;
193
194 9
        return $this;
195
    }
196
197
    /**
198
     * Initialize Database external connection
199
     *
200
     * @param PDO    $external_pdo_connection PDO database object
201
     * @param string $table_prefix
202
     *
203
     * @return \Longman\TelegramBot\Telegram
204
     * @throws \Longman\TelegramBot\Exception\TelegramException
205
     */
206 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...
207
    {
208
        $this->pdo = DB::externalInitialize($external_pdo_connection, $this, $table_prefix);
209
        ConversationDB::initializeConversation();
210
        $this->mysql_enabled = true;
211
212
        return $this;
213
    }
214
215
    /**
216
     * Get commands list
217
     *
218
     * @return array $commands
219
     * @throws \Longman\TelegramBot\Exception\TelegramException
220
     */
221 1
    public function getCommandsList()
222
    {
223 1
        $commands = [];
224
225 1
        foreach ($this->commands_paths as $path) {
226
            try {
227
                //Get all "*Command.php" files
228 1
                $files = new RegexIterator(
229 1
                    new RecursiveIteratorIterator(
230 1
                        new RecursiveDirectoryIterator($path)
231
                    ),
232 1
                    '/^.+Command.php$/'
233
                );
234
235 1
                foreach ($files as $file) {
236
                    //Remove "Command.php" from filename
237 1
                    $command      = $this->sanitizeCommand(substr($file->getFilename(), 0, -11));
238 1
                    $command_name = strtolower($command);
239
240 1
                    if (array_key_exists($command_name, $commands)) {
241
                        continue;
242
                    }
243
244 1
                    require_once $file->getPathname();
245
246 1
                    $command_obj = $this->getCommandObject($command);
247 1
                    if ($command_obj instanceof Command) {
248 1
                        $commands[$command_name] = $command_obj;
249
                    }
250
                }
251
            } catch (Exception $e) {
252
                throw new TelegramException('Error getting commands from path: ' . $path);
253
            }
254
        }
255
256 1
        return $commands;
257
    }
258
259
    /**
260
     * Get an object instance of the passed command
261
     *
262
     * @param string $command
263
     *
264
     * @return \Longman\TelegramBot\Commands\Command|null
265
     */
266 1
    public function getCommandObject($command)
267
    {
268 1
        $which = ['System'];
269 1
        $this->isAdmin() && $which[] = 'Admin';
270 1
        $which[] = 'User';
271
272 1
        foreach ($which as $auth) {
273 1
            $command_namespace = __NAMESPACE__ . '\\Commands\\' . $auth . 'Commands\\' . $this->ucfirstUnicode($command) . 'Command';
274 1
            if (class_exists($command_namespace)) {
275 1
                return new $command_namespace($this, $this->update);
276
            }
277
        }
278
279
        return null;
280
    }
281
282
    /**
283
     * Set custom input string for debug purposes
284
     *
285
     * @param string $input (json format)
286
     *
287
     * @return \Longman\TelegramBot\Telegram
288
     */
289
    public function setCustomInput($input)
290
    {
291
        $this->input = $input;
292
293
        return $this;
294
    }
295
296
    /**
297
     * Get custom input string for debug purposes
298
     *
299
     * @return string
300
     */
301
    public function getCustomInput()
302
    {
303
        return $this->input;
304
    }
305
306
    /**
307
     * Get the ServerResponse of the last Command execution
308
     *
309
     * @return \Longman\TelegramBot\Entities\ServerResponse
310
     */
311
    public function getLastCommandResponse()
312
    {
313
        return $this->last_command_response;
314
    }
315
316
    /**
317
     * Handle getUpdates method
318
     *
319
     * @param int|null $limit
320
     * @param int|null $timeout
321
     *
322
     * @return \Longman\TelegramBot\Entities\ServerResponse
323
     * @throws \Longman\TelegramBot\Exception\TelegramException
324
     */
325
    public function handleGetUpdates($limit = null, $timeout = null)
326
    {
327
        if (empty($this->bot_username)) {
328
            throw new TelegramException('Bot Username is not defined!');
329
        }
330
331
        if (!DB::isDbConnected() && !$this->getupdates_without_database) {
332
            return new ServerResponse(
333
                [
334
                    'ok'          => false,
335
                    'description' => 'getUpdates needs MySQL connection! (This can be overridden - see documentation)',
336
                ],
337
                $this->bot_username
338
            );
339
        }
340
341
        $offset = 0;
342
343
        //Take custom input into account.
344
        if ($custom_input = $this->getCustomInput()) {
345
            $response = new ServerResponse(json_decode($custom_input, true), $this->bot_username);
346
        } else {
347
            if (DB::isDbConnected()) {
348
                //Get last update id from the database
349
                $last_update = DB::selectTelegramUpdate(1);
350
                $last_update = reset($last_update);
351
352
                $this->last_update_id = isset($last_update['id']) ? $last_update['id'] : null;
353
            }
354
355
            if ($this->last_update_id !== null) {
356
                $offset = $this->last_update_id + 1;    //As explained in the telegram bot API documentation
357
            }
358
359
            $response = Request::getUpdates(
360
                [
361
                    'offset'  => $offset,
362
                    'limit'   => $limit,
363
                    'timeout' => $timeout,
364
                ]
365
            );
366
        }
367
368
        if ($response->isOk()) {
369
            $results = $response->getResult();
370
371
            //Process all updates
372
            /** @var Update $result */
373
            foreach ($results as $result) {
374
                $this->processUpdate($result);
375
            }
376
377
            if (!DB::isDbConnected() && !$custom_input && $this->last_update_id !== null && $offset === 0) {
378
                //Mark update(s) as read after handling
379
                Request::getUpdates(
380
                    [
381
                        'offset'  => $this->last_update_id + 1,
382
                        'limit'   => 1,
383
                        'timeout' => $timeout,
384
                    ]
385
                );
386
            }
387
        }
388
389
        return $response;
390
    }
391
392
    /**
393
     * Handle bot request from webhook
394
     *
395
     * @return bool
396
     *
397
     * @throws \Longman\TelegramBot\Exception\TelegramException
398
     */
399
    public function handle()
400
    {
401
        if (empty($this->bot_username)) {
402
            throw new TelegramException('Bot Username is not defined!');
403
        }
404
405
        $this->input = Request::getInput();
406
407
        if (empty($this->input)) {
408
            throw new TelegramException('Input is empty!');
409
        }
410
411
        $post = json_decode($this->input, true);
412
        if (empty($post)) {
413
            throw new TelegramException('Invalid JSON!');
414
        }
415
416
        if ($response = $this->processUpdate(new Update($post, $this->bot_username))) {
417
            return $response->isOk();
418
        }
419
420
        return false;
421
    }
422
423
    /**
424
     * Get the command name from the command type
425
     *
426
     * @param string $type
427
     *
428
     * @return string
429
     */
430
    protected function getCommandFromType($type)
431
    {
432
        return $this->ucfirstUnicode(str_replace('_', '', $type));
433
    }
434
435
    /**
436
     * Process bot Update request
437
     *
438
     * @param \Longman\TelegramBot\Entities\Update $update
439
     *
440
     * @return \Longman\TelegramBot\Entities\ServerResponse
441
     * @throws \Longman\TelegramBot\Exception\TelegramException
442
     */
443
    public function processUpdate(Update $update)
444
    {
445
        $this->update = $update;
446
        $this->last_update_id = $update->getUpdateId();
447
448
        //If all else fails, it's a generic message.
449
        $command = 'genericmessage';
450
451
        $update_type = $this->update->getUpdateType();
452
        if ($update_type === 'message') {
453
            $message = $this->update->getMessage();
454
455
            //Load admin commands
456
            if ($this->isAdmin()) {
457
                $this->addCommandsPath(TB_BASE_COMMANDS_PATH . '/AdminCommands', false);
458
            }
459
460
            $type = $message->getType();
461
            if ($type === 'command') {
462
                $command = $message->getCommand();
463
            } elseif (in_array($type, [
464
                'new_chat_members',
465
                'left_chat_member',
466
                'new_chat_title',
467
                'new_chat_photo',
468
                'delete_chat_photo',
469
                'group_chat_created',
470
                'supergroup_chat_created',
471
                'channel_chat_created',
472
                'migrate_to_chat_id',
473
                'migrate_from_chat_id',
474
                'pinned_message',
475
                'invoice',
476
                'successful_payment',
477
            ], true)
478
            ) {
479
                $command = $this->getCommandFromType($type);
480
            }
481
        } else {
482
            $command = $this->getCommandFromType($update_type);
483
        }
484
485
        //Make sure we have an up-to-date command list
486
        //This is necessary to "require" all the necessary command files!
487
        $this->getCommandsList();
488
489
        //Make sure we don't try to process update that was already processed
490
        $last_id = DB::selectTelegramUpdate(1, $this->update->getUpdateId());
491
        if ($last_id && count($last_id) === 1) {
492
            TelegramLog::debug('Duplicate update received, processing aborted!');
493
            return Request::emptyResponse();
494
        }
495
496
        DB::insertRequest($this->update);
497
498
        return $this->executeCommand($command);
499
    }
500
501
    /**
502
     * Execute /command
503
     *
504
     * @param string $command
505
     *
506
     * @return mixed
507
     * @throws \Longman\TelegramBot\Exception\TelegramException
508
     */
509
    public function executeCommand($command)
510
    {
511
        $command     = strtolower($command);
512
        $command_obj = $this->getCommandObject($command);
513
514
        if (!$command_obj || !$command_obj->isEnabled()) {
515
            //Failsafe in case the Generic command can't be found
516
            if ($command === 'generic') {
517
                throw new TelegramException('Generic command missing!');
518
            }
519
520
            //Handle a generic command or non existing one
521
            $this->last_command_response = $this->executeCommand('generic');
522
        } else {
523
            //execute() method is executed after preExecute()
524
            //This is to prevent executing a DB query without a valid connection
525
            $this->last_command_response = $command_obj->preExecute();
526
        }
527
528
        return $this->last_command_response;
529
    }
530
531
    /**
532
     * Sanitize Command
533
     *
534
     * @param string $command
535
     *
536
     * @return string
537
     */
538 1
    protected function sanitizeCommand($command)
539
    {
540 1
        return str_replace(' ', '', $this->ucwordsUnicode(str_replace('_', ' ', $command)));
541
    }
542
543
    /**
544
     * Enable a single Admin account
545
     *
546
     * @param integer $admin_id Single admin id
547
     *
548
     * @return \Longman\TelegramBot\Telegram
549
     */
550 1
    public function enableAdmin($admin_id)
551
    {
552 1
        if (!is_int($admin_id) || $admin_id <= 0) {
553 1
            TelegramLog::error('Invalid value "%s" for admin.', $admin_id);
554 1
        } elseif (!in_array($admin_id, $this->admins_list, true)) {
555 1
            $this->admins_list[] = $admin_id;
556
        }
557
558 1
        return $this;
559
    }
560
561
    /**
562
     * Enable a list of Admin Accounts
563
     *
564
     * @param array $admin_ids List of admin ids
565
     *
566
     * @return \Longman\TelegramBot\Telegram
567
     */
568 1
    public function enableAdmins(array $admin_ids)
569
    {
570 1
        foreach ($admin_ids as $admin_id) {
571 1
            $this->enableAdmin($admin_id);
572
        }
573
574 1
        return $this;
575
    }
576
577
    /**
578
     * Get list of admins
579
     *
580
     * @return array
581
     */
582 1
    public function getAdminList()
583
    {
584 1
        return $this->admins_list;
585
    }
586
587
    /**
588
     * Check if the passed user is an admin
589
     *
590
     * If no user id is passed, the current update is checked for a valid message sender.
591
     *
592
     * @param int|null $user_id
593
     *
594
     * @return bool
595
     */
596 1
    public function isAdmin($user_id = null)
597
    {
598 1
        if ($user_id === null && $this->update !== null) {
599
            //Try to figure out if the user is an admin
600
            $update_methods = [
601
                'getMessage',
602
                'getEditedMessage',
603
                'getChannelPost',
604
                'getEditedChannelPost',
605
                'getInlineQuery',
606
                'getChosenInlineResult',
607
                'getCallbackQuery',
608
            ];
609
            foreach ($update_methods as $update_method) {
610
                $object = call_user_func([$this->update, $update_method]);
611
                if ($object !== null && $from = $object->getFrom()) {
612
                    $user_id = $from->getId();
613
                    break;
614
                }
615
            }
616
        }
617
618 1
        return ($user_id === null) ? false : in_array($user_id, $this->admins_list, true);
619
    }
620
621
    /**
622
     * Check if user required the db connection
623
     *
624
     * @return bool
625
     */
626
    public function isDbEnabled()
627
    {
628
        if ($this->mysql_enabled) {
629
            return true;
630
        } else {
631
            return false;
632
        }
633
    }
634
635
    /**
636
     * Add a single custom commands path
637
     *
638
     * @param string $path   Custom commands path to add
639
     * @param bool   $before If the path should be prepended or appended to the list
640
     *
641
     * @return \Longman\TelegramBot\Telegram
642
     */
643 30
    public function addCommandsPath($path, $before = true)
644
    {
645 30
        if (!is_dir($path)) {
646 1
            TelegramLog::error('Commands path "%s" does not exist.', $path);
647 30
        } elseif (!in_array($path, $this->commands_paths, true)) {
648 30
            if ($before) {
649 30
                array_unshift($this->commands_paths, $path);
650
            } else {
651
                $this->commands_paths[] = $path;
652
            }
653
        }
654
655 30
        return $this;
656
    }
657
658
    /**
659
     * Add multiple custom commands paths
660
     *
661
     * @param array $paths  Custom commands paths to add
662
     * @param bool  $before If the paths should be prepended or appended to the list
663
     *
664
     * @return \Longman\TelegramBot\Telegram
665
     */
666 1
    public function addCommandsPaths(array $paths, $before = true)
667
    {
668 1
        foreach ($paths as $path) {
669 1
            $this->addCommandsPath($path, $before);
670
        }
671
672 1
        return $this;
673
    }
674
675
    /**
676
     * Return the list of commands paths
677
     *
678
     * @return array
679
     */
680 1
    public function getCommandsPaths()
681
    {
682 1
        return $this->commands_paths;
683
    }
684
685
    /**
686
     * Set custom upload path
687
     *
688
     * @param string $path Custom upload path
689
     *
690
     * @return \Longman\TelegramBot\Telegram
691
     */
692
    public function setUploadPath($path)
693
    {
694
        $this->upload_path = $path;
695
696
        return $this;
697
    }
698
699
    /**
700
     * Get custom upload path
701
     *
702
     * @return string
703
     */
704
    public function getUploadPath()
705
    {
706
        return $this->upload_path;
707
    }
708
709
    /**
710
     * Set custom download path
711
     *
712
     * @param string $path Custom download path
713
     *
714
     * @return \Longman\TelegramBot\Telegram
715
     */
716
    public function setDownloadPath($path)
717
    {
718
        $this->download_path = $path;
719
720
        return $this;
721
    }
722
723
    /**
724
     * Get custom download path
725
     *
726
     * @return string
727
     */
728
    public function getDownloadPath()
729
    {
730
        return $this->download_path;
731
    }
732
733
    /**
734
     * Set command config
735
     *
736
     * Provide further variables to a particular commands.
737
     * For example you can add the channel name at the command /sendtochannel
738
     * Or you can add the api key for external service.
739
     *
740
     * @param string $command
741
     * @param array  $config
742
     *
743
     * @return \Longman\TelegramBot\Telegram
744
     */
745 14
    public function setCommandConfig($command, array $config)
746
    {
747 14
        $this->commands_config[$command] = $config;
748
749 14
        return $this;
750
    }
751
752
    /**
753
     * Get command config
754
     *
755
     * @param string $command
756
     *
757
     * @return array
758
     */
759 15
    public function getCommandConfig($command)
760
    {
761 15
        return isset($this->commands_config[$command]) ? $this->commands_config[$command] : [];
762
    }
763
764
    /**
765
     * Get API key
766
     *
767
     * @return string
768
     */
769 1
    public function getApiKey()
770
    {
771 1
        return $this->api_key;
772
    }
773
774
    /**
775
     * Get Bot name
776
     *
777
     * @return string
778
     */
779 1
    public function getBotUsername()
780
    {
781 1
        return $this->bot_username;
782
    }
783
784
    /**
785
     * Get Bot Id
786
     *
787
     * @return string
788
     */
789
    public function getBotId()
790
    {
791
        return $this->bot_id;
792
    }
793
794
    /**
795
     * Get Version
796
     *
797
     * @return string
798
     */
799
    public function getVersion()
800
    {
801
        return $this->version;
802
    }
803
804
    /**
805
     * Set Webhook for bot
806
     *
807
     * @param string $url
808
     * @param array  $data Optional parameters.
809
     *
810
     * @return \Longman\TelegramBot\Entities\ServerResponse
811
     * @throws \Longman\TelegramBot\Exception\TelegramException
812
     */
813
    public function setWebhook($url, array $data = [])
814
    {
815
        if (empty($url)) {
816
            throw new TelegramException('Hook url is empty!');
817
        }
818
819
        $data        = array_intersect_key($data, array_flip([
820
            'certificate',
821
            'max_connections',
822
            'allowed_updates',
823
        ]));
824
        $data['url'] = $url;
825
826
        // If the certificate is passed as a path, encode and add the file to the data array.
827
        if (!empty($data['certificate']) && is_string($data['certificate'])) {
828
            $data['certificate'] = Request::encodeFile($data['certificate']);
829
        }
830
831
        $result = Request::setWebhook($data);
832
833 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...
834
            throw new TelegramException(
835
                'Webhook was not set! Error: ' . $result->getErrorCode() . ' ' . $result->getDescription()
836
            );
837
        }
838
839
        return $result;
840
    }
841
842
    /**
843
     * Delete any assigned webhook
844
     *
845
     * @return mixed
846
     * @throws \Longman\TelegramBot\Exception\TelegramException
847
     */
848
    public function deleteWebhook()
849
    {
850
        $result = Request::deleteWebhook();
851
852 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...
853
            throw new TelegramException(
854
                'Webhook was not deleted! Error: ' . $result->getErrorCode() . ' ' . $result->getDescription()
855
            );
856
        }
857
858
        return $result;
859
    }
860
861
    /**
862
     * Replace function `ucwords` for UTF-8 characters in the class definition and commands
863
     *
864
     * @param string $str
865
     * @param string $encoding (default = 'UTF-8')
866
     *
867
     * @return string
868
     */
869 1
    protected function ucwordsUnicode($str, $encoding = 'UTF-8')
870
    {
871 1
        return mb_convert_case($str, MB_CASE_TITLE, $encoding);
872
    }
873
874
    /**
875
     * Replace function `ucfirst` for UTF-8 characters in the class definition and commands
876
     *
877
     * @param string $str
878
     * @param string $encoding (default = 'UTF-8')
879
     *
880
     * @return string
881
     */
882 1
    protected function ucfirstUnicode($str, $encoding = 'UTF-8')
883
    {
884 1
        return mb_strtoupper(mb_substr($str, 0, 1, $encoding), $encoding)
885 1
               . mb_strtolower(mb_substr($str, 1, mb_strlen($str), $encoding), $encoding);
886
    }
887
888
    /**
889
     * Enable Botan.io integration
890
     *
891
     * @deprecated Botan.io service is no longer working
892
     *
893
     * @param  string $token
894
     * @param  array  $options
895
     *
896
     * @return \Longman\TelegramBot\Telegram
897
     */
898
    public function enableBotan($token, array $options = [])
0 ignored issues
show
Unused Code introduced by
The parameter $token is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $options is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
899
    {
900
        trigger_error('Longman\TelegramBot\Telegram::enableBotan is deprecated and will be removed in future release.', E_USER_DEPRECATED);
901
902
        return $this;
903
    }
904
905
    /**
906
     * Enable requests limiter
907
     *
908
     * @param  array $options
909
     *
910
     * @return \Longman\TelegramBot\Telegram
911
     */
912
    public function enableLimiter(array $options = [])
913
    {
914
        Request::setLimiter(true, $options);
915
916
        return $this;
917
    }
918
919
    /**
920
     * Run provided commands
921
     *
922
     * @param array $commands
923
     *
924
     * @throws TelegramException
925
     */
926
    public function runCommands($commands)
927
    {
928
        if (!is_array($commands) || empty($commands)) {
929
            throw new TelegramException('No command(s) provided!');
930
        }
931
932
        $this->run_commands  = true;
933
934
        $result = Request::getMe();
935
936
        if ($result->isOk()) {
937
            $result = $result->getResult();
938
939
            $bot_id       = $result->getId();
940
            $bot_name     = $result->getFirstName();
941
            $bot_username = $result->getUsername();
942
        } else {
943
            $bot_id       = $this->getBotId();
944
            $bot_name     = $this->getBotUsername();
945
            $bot_username = $this->getBotUsername();
946
        }
947
948
949
        $this->enableAdmin($bot_id);    // Give bot access to admin commands
950
        $this->getCommandsList();       // Load full commands list
951
952
        foreach ($commands as $command) {
953
            $this->update = new Update(
954
                [
955
                    'update_id' => 0,
956
                    'message'   => [
957
                        'message_id' => 0,
958
                        'from'       => [
959
                            'id'         => $bot_id,
960
                            'first_name' => $bot_name,
961
                            'username'   => $bot_username,
962
                        ],
963
                        'date'       => time(),
964
                        'chat'       => [
965
                            'id'   => $bot_id,
966
                            'type' => 'private',
967
                        ],
968
                        'text'       => $command,
969
                    ],
970
                ]
971
            );
972
973
            $this->executeCommand($this->update->getMessage()->getCommand());
974
        }
975
    }
976
977
    /**
978
     * Is this session initiated by runCommands()
979
     *
980
     * @return bool
981
     */
982
    public function isRunCommands()
983
    {
984
        return $this->run_commands;
985
    }
986
987
    /**
988
     * Switch to enable running getUpdates without a database
989
     *
990
     * @param bool $enable
991
     */
992
    public function useGetUpdatesWithoutDatabase($enable = true)
993
    {
994
        $this->getupdates_without_database = $enable;
995
    }
996
997
    /**
998
     * Return last update id
999
     *
1000
     * @return int
1001
     */
1002
    public function getLastUpdateId()
1003
    {
1004
        return $this->last_update_id;
1005
    }
1006
}
1007