Completed
Push — master ( df2568...3ba296 )
by Irfaq
05:04
created

Api::removeCommands()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 4
ccs 0
cts 2
cp 0
rs 10
cc 1
eloc 2
nc 1
nop 1
crap 2
1
<?php
2
3
namespace Telegram\Bot;
4
5
use Illuminate\Contracts\Container\Container;
6
use Telegram\Bot\Commands\CommandBus;
7
use Telegram\Bot\Commands\CommandInterface;
8
use Telegram\Bot\Exceptions\TelegramSDKException;
9
use Telegram\Bot\FileUpload\InputFile;
10
use Telegram\Bot\HttpClients\GuzzleHttpClient;
11
use Telegram\Bot\HttpClients\HttpClientInterface;
12
use Telegram\Bot\Objects\File;
13
use Telegram\Bot\Objects\Message;
14
use Telegram\Bot\Objects\Update;
15
use Telegram\Bot\Objects\User;
16
use Telegram\Bot\Objects\UserProfilePhotos;
17
18
/**
19
 * Class Api.
20
 */
21
class Api
22
{
23
    /**
24
     * @var string Version number of the Telegram Bot PHP SDK.
25
     */
26
    const VERSION = '2.0.0';
27
28
    /**
29
     * @var string The name of the environment variable that contains the Telegram Bot API Access Token.
30
     */
31
    const BOT_TOKEN_ENV_NAME = 'TELEGRAM_BOT_TOKEN';
32
33
    /**
34
     * @var TelegramClient The Telegram client service.
35
     */
36
    protected $client;
37
38
    /**
39
     * @var string Telegram Bot API Access Token.
40
     */
41
    protected $accessToken = null;
42
43
    /**
44
     * @var TelegramResponse|null Stores the last request made to Telegram Bot API.
45
     */
46
    protected $lastResponse;
47
48
    /**
49
     * @var bool Indicates if the request to Telegram will be asynchronous (non-blocking).
50
     */
51
    protected $isAsyncRequest = false;
52
53
    /**
54
     * @var CommandBus|null Telegram Command Bus.
55
     */
56
    protected $commandBus = null;
57
58
    /**
59
     * @var Container IoC Container
60
     */
61
    protected static $container = null;
62
63
    /**
64
     * Instantiates a new Telegram super-class object.
65
     *
66
     *
67
     * @param string                     $token               The Telegram Bot API Access Token.
68
     * @param bool                       $async               (Optional) Indicates if the request to Telegram
69
     *                                                        will be asynchronous (non-blocking).
70
     * @param string|HttpClientInterface $http_client_handler (Optional) Custom HTTP Client Handler.
71
     *
72
     * @throws TelegramSDKException
73
     */
74 72
    public function __construct($token = null, $async = false, $http_client_handler = null)
75
    {
76 72
        $this->accessToken = isset($token) ? $token : getenv(static::BOT_TOKEN_ENV_NAME);
77 72
        if (!$this->accessToken) {
78 2
            throw new TelegramSDKException('Required "token" not supplied in config and could not find fallback environment variable "'.static::BOT_TOKEN_ENV_NAME.'"');
79
        }
80
81 72
        $httpClientHandler = null;
82 72
        if (isset($http_client_handler)) {
83 44
            if ($http_client_handler instanceof HttpClientInterface) {
84 40
                $httpClientHandler = $http_client_handler;
85 44
            } elseif ($http_client_handler === 'guzzle') {
86 2
                $httpClientHandler = new GuzzleHttpClient();
87 2
            } else {
88 2
                throw new \InvalidArgumentException('The HTTP Client Handler must be set to "guzzle", or be an instance of Telegram\Bot\HttpClients\HttpClientInterface');
89
            }
90 42
        }
91
92 72
        if (isset($async)) {
93 72
            $this->setAsyncRequest($async);
94 72
        }
95
96 72
        $this->client = new TelegramClient($httpClientHandler);
97 72
    }
98
99
    /**
100
     * Returns the TelegramClient service.
101
     *
102
     * @return TelegramClient
103
     */
104 4
    public function getClient()
105
    {
106 4
        return $this->client;
107
    }
108
109
    /**
110
     * Returns Telegram Bot API Access Token.
111
     *
112
     * @return string
113
     */
114 40
    public function getAccessToken()
115
    {
116 40
        return $this->accessToken;
117
    }
118
119
    /**
120
     * Returns the last response returned from API request.
121
     *
122
     * @return TelegramResponse
123
     */
124 2
    public function getLastResponse()
125
    {
126 2
        return $this->lastResponse;
127
    }
128
129
    /**
130
     * Sets the bot access token to use with API requests.
131
     *
132
     * @param string $accessToken The bot access token to save.
133
     *
134
     * @throws \InvalidArgumentException
135
     *
136
     * @return Api
137
     */
138 8
    public function setAccessToken($accessToken)
139
    {
140 8
        if (is_string($accessToken)) {
141 2
            $this->accessToken = $accessToken;
142
143 2
            return $this;
144
        }
145
146 6
        throw new \InvalidArgumentException('The Telegram bot access token must be of type "string"');
147
    }
148
149
    /**
150
     * Make this request asynchronous (non-blocking).
151
     *
152
     * @param bool $isAsyncRequest
153
     *
154
     * @return Api
155
     */
156 72
    public function setAsyncRequest($isAsyncRequest)
157
    {
158 72
        $this->isAsyncRequest = $isAsyncRequest;
159
160 72
        return $this;
161
    }
162
163
    /**
164
     * Check if this is an asynchronous request (non-blocking).
165
     *
166
     * @return bool
167
     */
168 40
    public function isAsyncRequest()
169
    {
170 40
        return $this->isAsyncRequest;
171
    }
172
173
    /**
174
     * Returns SDK's Command Bus.
175
     *
176
     * @return CommandBus
177
     */
178 8
    public function getCommandBus()
179
    {
180 8
        if (is_null($this->commandBus)) {
181 8
            return $this->commandBus = new CommandBus($this);
182
        }
183
184 2
        return $this->commandBus;
185
    }
186
187
    /**
188
     * Add Telegram Command to the Command Bus.
189
     *
190
     * @param CommandInterface|string $command
191
     *
192
     * @return CommandBus
193
     */
194
    public function addCommand($command)
195
    {
196
        return $this->getCommandBus()->addCommand($command);
197
    }
198
199
    /**
200
     * Add Telegram Commands to the Command Bus.
201
     *
202
     * @param array $commands
203
     *
204
     * @return CommandBus
205
     */
206 2
    public function addCommands(array $commands)
207
    {
208 2
        return $this->getCommandBus()->addCommands($commands);
209
    }
210
211
    /**
212
     * Remove Telegram Command to the Command Bus.
213
     *
214
     * @param string $name
215
     *
216
     * @return CommandBus
217
     */
218
    public function removeCommand($name)
219
    {
220
        return $this->getCommandBus()->removeCommand($name);
221
    }
222
223
    /**
224
     * Remove Telegram Commands from the Command Bus.
225
     *
226
     * @param array $names
227
     *
228
     * @return CommandBus
229
     */
230
    public function removeCommands(array $names)
231
    {
232
        return $this->getCommandBus()->removeCommands($names);
233
    }
234
235
    /**
236
     * Returns list of available commands.
237
     *
238
     * @return Commands\Command[]
239
     */
240
    public function getCommands()
241
    {
242
        return $this->getCommandBus()->getCommands();
243
    }
244
245
    /**
246
     * A simple method for testing your bot's auth token.
247
     * Returns basic information about the bot in form of a User object.
248
     *
249
     * @link https://core.telegram.org/bots/api#getme
250
     *
251
     * @return User
252
     */
253 4
    public function getMe()
254
    {
255 4
        $response = $this->post('getMe');
256
257 2
        return new User($response->getDecodedBody());
258
    }
259
260
    /**
261
     * Send text messages.
262
     *
263
     * <code>
264
     * $params = [
265
     *   'chat_id'                  => '',
266
     *   'text'                     => '',
267
     *   'parse_mode'               => '',
268
     *   'disable_web_page_preview' => '',
269
     *   'reply_to_message_id'      => '',
270
     *   'reply_markup'             => '',
271
     * ];
272
     * </code>
273
     *
274
     * @link https://core.telegram.org/bots/api#sendmessage
275
     *
276
     * @param array    $params
277
     *
278
     * @var int|string $params ['chat_id']
279
     * @var string     $params ['text']
280
     * @var string     $params ['parse_mode']
281
     * @var bool       $params ['disable_web_page_preview']
282
     * @var int        $params ['reply_to_message_id']
283
     * @var string     $params ['reply_markup']
284
     *
285
     * @return Message
286
     */
287 2
    public function sendMessage(array $params)
288
    {
289 2
        $response = $this->post('sendMessage', $params);
290
291 2
        return new Message($response->getDecodedBody());
292
    }
293
294
    /**
295
     * Forward messages of any kind.
296
     *
297
     * <code>
298
     * $params = [
299
     *   'chat_id'      => '',
300
     *   'from_chat_id' => '',
301
     *   'message_id'   => '',
302
     * ];
303
     * </code>
304
     *
305
     * @link https://core.telegram.org/bots/api#forwardmessage
306
     *
307
     * @param array    $params
308
     *
309
     * @var int|string $params ['chat_id']
310
     * @var int        $params ['from_chat_id']
311
     * @var int        $params ['message_id']
312
     *
313
     * @return Message
314
     */
315 2
    public function forwardMessage(array $params)
316
    {
317 2
        $response = $this->post('forwardMessage', $params);
318
319 2
        return new Message($response->getDecodedBody());
320
    }
321
322
    /**
323
     * Send Photos.
324
     *
325
     * <code>
326
     * $params = [
327
     *   'chat_id'             => '',
328
     *   'photo'               => '',
329
     *   'caption'             => '',
330
     *   'reply_to_message_id' => '',
331
     *   'reply_markup'        => '',
332
     * ];
333
     * </code>
334
     *
335
     * @link https://core.telegram.org/bots/api#sendphoto
336
     *
337
     * @param array    $params
338
     *
339
     * @var int|string $params ['chat_id']
340
     * @var string     $params ['photo']
341
     * @var string     $params ['caption']
342
     * @var int        $params ['reply_to_message_id']
343
     * @var string     $params ['reply_markup']
344
     *
345
     * @return Message
346
     */
347 4
    public function sendPhoto(array $params)
348
    {
349 4
        return $this->uploadFile('sendPhoto', $params);
350
    }
351
352
    /**
353
     * Send regular audio files.
354
     *
355
     * <code>
356
     * $params = [
357
     *   'chat_id'             => '',
358
     *   'audio'               => '',
359
     *   'duration'            => '',
360
     *   'performer'           => '',
361
     *   'title'               => '',
362
     *   'reply_to_message_id' => '',
363
     *   'reply_markup'        => '',
364
     * ];
365
     * </code>
366
     *
367
     * @link https://core.telegram.org/bots/api#sendaudio
368
     *
369
     * @param array    $params
370
     *
371
     * @var int|string $params ['chat_id']
372
     * @var string     $params ['audio']
373
     * @var int        $params ['duration']
374
     * @var string     $params ['performer']
375
     * @var string     $params ['title']
376
     * @var int        $params ['reply_to_message_id']
377
     * @var string     $params ['reply_markup']
378
     *
379
     * @return Message
380
     */
381 2
    public function sendAudio(array $params)
382
    {
383 2
        return $this->uploadFile('sendAudio', $params);
384
    }
385
386
    /**
387
     * Send general files.
388
     *
389
     * <code>
390
     * $params = [
391
     *   'chat_id'             => '',
392
     *   'document'            => '',
393
     *   'reply_to_message_id' => '',
394
     *   'reply_markup'        => '',
395
     * ];
396
     * </code>
397
     *
398
     * @link https://core.telegram.org/bots/api#senddocument
399
     *
400
     * @param array    $params
401
     *
402
     * @var int|string $params ['chat_id']
403
     * @var string     $params ['document']
404
     * @var int        $params ['reply_to_message_id']
405
     * @var string     $params ['reply_markup']
406
     *
407
     * @return Message
408
     */
409 2
    public function sendDocument(array $params)
410
    {
411 2
        return $this->uploadFile('sendDocument', $params);
412
    }
413
414
    /**
415
     * Send .webp stickers.
416
     *
417
     * <code>
418
     * $params = [
419
     *   'chat_id' => '',
420
     *   'sticker' => '',
421
     *   'reply_to_message_id' => '',
422
     *   'reply_markup' => '',
423
     * ];
424
     * </code>
425
     *
426
     * @link https://core.telegram.org/bots/api#sendsticker
427
     *
428
     * @param array    $params
429
     *
430
     * @var int|string $params ['chat_id']
431
     * @var string     $params ['sticker']
432
     * @var int        $params ['reply_to_message_id']
433
     * @var string     $params ['reply_markup']
434
     *
435
     * @throws TelegramSDKException
436
     *
437
     * @return Message
438
     */
439 2
    public function sendSticker(array $params)
440
    {
441 2
        if (is_file($params['sticker']) && (pathinfo($params['sticker'], PATHINFO_EXTENSION) !== 'webp')) {
442
            throw new TelegramSDKException('Invalid Sticker Provided. Supported Format: Webp');
443
        }
444
445 2
        return $this->uploadFile('sendSticker', $params);
446
    }
447
448
    /**
449
     * Send Video File, Telegram clients support mp4 videos (other formats may be sent as Document).
450
     *
451
     * <code>
452
     * $params = [
453
     *   'chat_id'             => '',
454
     *   'video'               => '',
455
     *   'duration'            => '',
456
     *   'caption'             => '',
457
     *   'reply_to_message_id' => '',
458
     *   'reply_markup'        => '',
459
     * ];
460
     * </code>
461
     *
462
     * @see  sendDocument
463
     * @link https://core.telegram.org/bots/api#sendvideo
464
     *
465
     * @param array    $params
466
     *
467
     * @var int|string $params ['chat_id']
468
     * @var string     $params ['video']
469
     * @var int        $params ['duration']
470
     * @var string     $params ['caption']
471
     * @var int        $params ['reply_to_message_id']
472
     * @var string     $params ['reply_markup']
473
     *
474
     * @return Message
475
     */
476 2
    public function sendVideo(array $params)
477
    {
478 2
        return $this->uploadFile('sendVideo', $params);
479
    }
480
481
    /**
482
     * Send voice audio files.
483
     *
484
     * <code>
485
     * $params = [
486
     *   'chat_id'             => '',
487
     *   'voice'               => '',
488
     *   'duration'            => '',
489
     *   'reply_to_message_id' => '',
490
     *   'reply_markup'        => '',
491
     * ];
492
     * </code>
493
     *
494
     * @link https://core.telegram.org/bots/api#sendaudio
495
     *
496
     * @param array    $params
497
     *
498
     * @var int|string $params ['chat_id']
499
     * @var string     $params ['voice']
500
     * @var int        $params ['duration']
501
     * @var int        $params ['reply_to_message_id']
502
     * @var string     $params ['reply_markup']
503
     *
504
     * @return Message
505
     */
506 2
    public function sendVoice(array $params)
507
    {
508 2
        return $this->uploadFile('sendVoice', $params);
509
    }
510
511
    /**
512
     * Send point on the map.
513
     *
514
     * <code>
515
     * $params = [
516
     *   'chat_id'             => '',
517
     *   'latitude'            => '',
518
     *   'longitude'           => '',
519
     *   'reply_to_message_id' => '',
520
     *   'reply_markup'        => '',
521
     * ];
522
     * </code>
523
     *
524
     * @link https://core.telegram.org/bots/api#sendlocation
525
     *
526
     * @param array    $params
527
     *
528
     * @var int|string $params ['chat_id']
529
     * @var float      $params ['latitude']
530
     * @var float      $params ['longitude']
531
     * @var int        $params ['reply_to_message_id']
532
     * @var string     $params ['reply_markup']
533
     *
534
     * @return Message
535
     */
536 2
    public function sendLocation(array $params)
537
    {
538 2
        $response = $this->post('sendLocation', $params);
539
540 2
        return new Message($response->getDecodedBody());
541
    }
542
543
    /**
544
     * Broadcast a Chat Action.
545
     *
546
     * <code>
547
     * $params = [
548
     *   'chat_id' => '',
549
     *   'action'  => '',
550
     * ];
551
     * </code>
552
     *
553
     * @link https://core.telegram.org/bots/api#sendchataction
554
     *
555
     * @param array    $params
556
     *
557
     * @var int|string $params ['chat_id']
558
     * @var string     $params ['action']
559
     *
560
     * @throws TelegramSDKException
561
     *
562
     * @return TelegramResponse
563
     */
564 4
    public function sendChatAction(array $params)
565
    {
566
        $validActions = [
567 4
            'typing',
568 4
            'upload_photo',
569 4
            'record_video',
570 4
            'upload_video',
571 4
            'record_audio',
572 4
            'upload_audio',
573 4
            'upload_document',
574 4
            'find_location',
575 4
        ];
576
577 4
        if (isset($params['action']) && in_array($params['action'], $validActions)) {
578 2
            return $this->post('sendChatAction', $params);
579
        }
580
581 2
        throw new TelegramSDKException('Invalid Action! Accepted value: '.implode(', ', $validActions));
582
    }
583
584
    /**
585
     * Returns a list of profile pictures for a user.
586
     *
587
     * <code>
588
     * $params = [
589
     *   'user_id' => '',
590
     *   'offset'  => '',
591
     *   'limit'   => '',
592
     * ];
593
     * </code>
594
     *
595
     * @link https://core.telegram.org/bots/api#getuserprofilephotos
596
     *
597
     * @param array $params
598
     *
599
     * @var int     $params ['user_id']
600
     * @var int     $params ['offset']
601
     * @var int     $params ['limit']
602
     *
603
     * @return UserProfilePhotos
604
     */
605
    public function getUserProfilePhotos(array $params)
606
    {
607
        $response = $this->post('getUserProfilePhotos', $params);
608
609
        return new UserProfilePhotos($response->getDecodedBody());
610
    }
611
612
    /**
613
     * Returns basic info about a file and prepare it for downloading.
614
     *
615
     * <code>
616
     * $params = [
617
     *   'file_id' => '',
618
     * ];
619
     * </code>
620
     *
621
     * The file can then be downloaded via the link
622
     * https://api.telegram.org/file/bot<token>/<file_path>,
623
     * where <file_path> is taken from the response.
624
     *
625
     * @link https://core.telegram.org/bots/api#getFile
626
     *
627
     * @param array $params
628
     *
629
     * @var string  $params ['file_id']
630
     *
631
     * @return File
632
     */
633 2
    public function getFile(array $params)
634
    {
635 2
        $response = $this->post('getFile', $params);
636
637 2
        return new File($response->getDecodedBody());
638
    }
639
640
    /**
641
     * Set a Webhook to receive incoming updates via an outgoing webhook.
642
     *
643
     * <code>
644
     * $params = [
645
     *   'url'         => '',
646
     *   'certificate' => '',
647
     * ];
648
     * </code>
649
     *
650
     * @link https://core.telegram.org/bots/api#setwebhook
651
     *
652
     * @param array $params
653
     *
654
     * @var string  $params ['url']         HTTPS url to send updates to.
655
     * @var string  $params ['certificate'] Upload your public key certificate so that the root certificate in
656
     *                                      use can be checked.
657
     *
658
     * @throws TelegramSDKException
659
     *
660
     * @return TelegramResponse
661
     */
662 6
    public function setWebhook(array $params)
663
    {
664 6
        if (filter_var($params['url'], FILTER_VALIDATE_URL) === false) {
665 2
            throw new TelegramSDKException('Invalid URL Provided');
666
        }
667
668 4
        if (parse_url($params['url'], PHP_URL_SCHEME) !== 'https') {
669 2
            throw new TelegramSDKException('Invalid URL, should be a HTTPS url.');
670
        }
671
672 2
        return $this->uploadFile('setWebhook', $params);
673
    }
674
675
    /**
676
     * Returns webhook updates sent by Telegram.
677
     * Works only if you set a webhook.
678
     *
679
     * @see setWebhook
680
     *
681
     * @return Update
682
     */
683
    public function getWebhookUpdates()
684
    {
685
        $body = json_decode(file_get_contents('php://input'), true);
686
687
        return new Update($body);
688
    }
689
690
    /**
691
     * Removes the outgoing webhook (if any).
692
     *
693
     * @return TelegramResponse
694
     */
695 2
    public function removeWebhook()
696
    {
697 2
        $url = '';
698
699 2
        return $this->post('setWebhook', compact('url'));
700
    }
701
702
    /**
703
     * Use this method to receive incoming updates using long polling.
704
     *
705
     * <code>
706
     * $params = [
707
     *   'offset'  => '',
708
     *   'limit'   => '',
709
     *   'timeout' => '',
710
     * ];
711
     * </code>
712
     *
713
     * @link https://core.telegram.org/bots/api#getupdates
714
     *
715
     * @param array  $params
716
     *
717
     * @var int|null $params ['offset']
718
     * @var int|null $params ['limit']
719
     * @var int|null $params ['timeout']
720
     *
721
     * @return Update[]
722
     */
723 6
    public function getUpdates(array $params = [])
724
    {
725 6
        $response = $this->post('getUpdates', $params);
726 6
        $updates = $response->getDecodedBody();
727
728 6
        $data = [];
729 6
        foreach ($updates['result'] as $update) {
730 6
            $data[] = new Update($update);
731 6
        }
732
733 6
        return $data;
734
    }
735
736
    /**
737
     * Builds a custom keyboard markup.
738
     *
739
     * <code>
740
     * $params = [
741
     *   'keyboard'          => '',
742
     *   'resize_keyboard'   => '',
743
     *   'one_time_keyboard' => '',
744
     *   'selective'         => '',
745
     * ];
746
     * </code>
747
     *
748
     * @link https://core.telegram.org/bots/api#replykeyboardmarkup
749
     *
750
     * @param array $params
751
     *
752
     * @var array   $params ['keyboard']
753
     * @var bool    $params ['resize_keyboard']
754
     * @var bool    $params ['one_time_keyboard']
755
     * @var bool    $params ['selective']
756
     *
757
     * @return string
758
     */
759 2
    public function replyKeyboardMarkup(array $params)
760
    {
761 2
        return json_encode($params);
762
    }
763
764
    /**
765
     * Hide the current custom keyboard and display the default letter-keyboard.
766
     *
767
     * <code>
768
     * $params = [
769
     *   'hide_keyboard' => true,
770
     *   'selective'     => false,
771
     * ];
772
     * </code>
773
     *
774
     * @link https://core.telegram.org/bots/api#replykeyboardhide
775
     *
776
     * @param array $params
777
     *
778
     * @var bool    $params ['hide_keyboard']
779
     * @var bool    $params ['selective']
780
     *
781
     * @return string
782
     */
783 2
    public static function replyKeyboardHide(array $params = [])
784
    {
785 2
        return json_encode(array_merge(['hide_keyboard' => true, 'selective' => false], $params));
786
    }
787
788
    /**
789
     * Display a reply interface to the user (act as if the user has selected the bot‘s message and tapped ’Reply').
790
     *
791
     * <code>
792
     * $params = [
793
     *   'force_reply' => true,
794
     *   'selective'   => false,
795
     * ];
796
     * </code>
797
     *
798
     * @link https://core.telegram.org/bots/api#forcereply
799
     *
800
     * @param array $params
801
     *
802
     * @var bool    $params ['force_reply']
803
     * @var bool    $params ['selective']
804
     *
805
     * @return string
806
     */
807 2
    public static function forceReply(array $params = [])
808
    {
809 2
        return json_encode(array_merge(['force_reply' => true, 'selective' => false], $params));
810
    }
811
812
    /**
813
     * Processes Inbound Commands.
814
     *
815
     * @param bool $webhook
816
     *
817
     * @return Update|Update[]
818
     */
819 6
    public function commandsHandler($webhook = false)
820
    {
821 6
        if ($webhook) {
822
            $update = $this->getWebhookUpdates();
823
            $this->processCommand($update);
824
825
            return $update;
826
        }
827
828 6
        $updates = $this->getUpdates();
829 6
        $highestId = -1;
830
831 6
        foreach ($updates as $update) {
832 6
            $highestId = $update->getUpdateId();
833 6
            $this->processCommand($update);
834 6
        }
835
836
        //An update is considered confirmed as soon as getUpdates is called with an offset higher than its update_id.
837 6
        if ($highestId != -1) {
838 6
            $params = [];
839 6
            $params['offset'] = $highestId + 1;
840 6
            $params['limit'] = 1;
841 6
            $this->getUpdates($params);
842 6
        }
843
844 6
        return $updates;
845
    }
846
847
    /**
848
     * Check update object for a command and process.
849
     *
850
     * @param Update $update
851
     */
852 6
    protected function processCommand(Update $update)
853
    {
854 6
        $message = $update->getMessage();
855
856 6
        if ($message->has('text')) {
857 6
            $this->getCommandBus()->handler($message->getText(), $update);
858 6
        }
859 6
    }
860
861
    /**
862
     * Determine if a given type is the message.
863
     *
864
     * @param string         $type
865
     * @param Update|Message $object
866
     *
867
     * @return bool
868
     */
869
    public function isMessageType($type, $object)
870
    {
871
        if ($object instanceof Update) {
872
            $object = $object->getMessage();
873
        }
874
875
        if ($object->has(strtolower($type))) {
876
            return true;
877
        }
878
879
        return $this->detectMessageType($object) === $type;
880
    }
881
882
    /**
883
     * Detect Message Type Based on Update or Message Object.
884
     *
885
     * @param Update|Message $object
886
     *
887
     * @return string|null
888
     */
889
    public function detectMessageType($object)
890
    {
891
        if ($object instanceof Update) {
892
            $object = $object->getMessage();
893
        }
894
895
        $types = ['audio', 'document', 'photo', 'sticker', 'video', 'voice', 'contact', 'location', 'text'];
896
897
        return $object->keys()
898
            ->intersect($types)
899
            ->pop();
900
    }
901
902
    /**
903
     * Sends a GET request to Telegram Bot API and returns the result.
904
     *
905
     * @param string $endpoint
906
     * @param array  $params
907
     *
908
     * @throws TelegramSDKException
909
     *
910
     * @return TelegramResponse
911
     */
912
    protected function get($endpoint, $params = [])
913
    {
914
        return $this->sendRequest(
915
            'GET',
916
            $endpoint,
917
            $params
918
        );
919
    }
920
921
    /**
922
     * Sends a POST request to Telegram Bot API and returns the result.
923
     *
924
     * @param string $endpoint
925
     * @param array  $params
926
     * @param bool   $fileUpload Set true if a file is being uploaded.
927
     *
928
     * @return TelegramResponse
929
     */
930 38
    protected function post($endpoint, array $params = [], $fileUpload = false)
931
    {
932 38
        if ($fileUpload) {
933 16
            $params = ['multipart' => $params];
934 16
        } else {
935 22
            $params = ['form_params' => $params];
936
        }
937
938 38
        return $this->sendRequest(
939 38
            'POST',
940 38
            $endpoint,
941
            $params
942 38
        );
943
    }
944
945
    /**
946
     * Sends a multipart/form-data request to Telegram Bot API and returns the result.
947
     * Used primarily for file uploads.
948
     *
949
     * @param string $endpoint
950
     * @param array  $params
951
     *
952
     * @throws TelegramSDKException
953
     *
954
     * @return Message
955
     */
956 16
    protected function uploadFile($endpoint, array $params = [])
957
    {
958 16
        $i = 0;
959 16
        $multipart_params = [];
960 16
        foreach ($params as $name => $contents) {
961 16
            if (is_null($contents)) {
962
                continue;
963
            }
964
965 16
            if (!is_resource($contents) && $name !== 'url') {
966 14
                $validUrl = filter_var($contents, FILTER_VALIDATE_URL);
967 14
                $contents = (is_file($contents) || $validUrl) ? (new InputFile($contents))->open() : (string)$contents;
968 14
            }
969
970 16
            $multipart_params[$i]['name'] = $name;
971 16
            $multipart_params[$i]['contents'] = $contents;
972 16
            ++$i;
973 16
        }
974
975 16
        $response = $this->post($endpoint, $multipart_params, true);
976
977 16
        return new Message($response->getDecodedBody());
978
    }
979
980
    /**
981
     * Sends a request to Telegram Bot API and returns the result.
982
     *
983
     * @param string $method
984
     * @param string $endpoint
985
     * @param array  $params
986
     *
987
     * @throws TelegramSDKException
988
     *
989
     * @return TelegramResponse
990
     */
991 38
    protected function sendRequest(
992
        $method,
993
        $endpoint,
994
        array $params = []
995
    ) {
996 38
        $request = $this->request($method, $endpoint, $params);
997
998 38
        return $this->lastResponse = $this->client->sendRequest($request);
999
    }
1000
1001
    /**
1002
     * Instantiates a new TelegramRequest entity.
1003
     *
1004
     * @param string $method
1005
     * @param string $endpoint
1006
     * @param array  $params
1007
     *
1008
     * @return TelegramRequest
1009
     */
1010 38
    protected function request(
1011
        $method,
1012
        $endpoint,
1013
        array $params = []
1014
    ) {
1015 38
        return new TelegramRequest(
1016 38
            $this->getAccessToken(),
1017 38
            $method,
1018 38
            $endpoint,
1019 38
            $params,
1020 38
            $this->isAsyncRequest()
1021 38
        );
1022
    }
1023
1024
    /**
1025
     * Magic method to process any "get" requests.
1026
     *
1027
     * @param $method
1028
     * @param $arguments
1029
     *
1030
     * @return bool|TelegramResponse
1031
     */
1032
    public function __call($method, $arguments)
1033
    {
1034
        $action = substr($method, 0, 3);
1035
        if ($action === 'get') {
1036
            /* @noinspection PhpUndefinedFunctionInspection */
1037
            $class_name = studly_case(substr($method, 3));
1038
            $class = 'Telegram\Bot\Objects\\'.$class_name;
1039
            $response = $this->post($method, $arguments[0] ?: []);
1040
1041
            if (class_exists($class)) {
1042
                return new $class($response->getDecodedBody());
1043
            }
1044
1045
            return $response;
1046
        }
1047
1048
        return false;
1049
    }
1050
1051
    /**
1052
     * Set the IoC Container.
1053
     *
1054
     * @param $container Container instance
1055
     *
1056
     * @return void
1057
     */
1058
    public static function setContainer(Container $container)
1059
    {
1060
        self::$container = $container;
1061
    }
1062
1063
    /**
1064
     * Get the IoC Container.
1065
     *
1066
     * @return Container
1067
     */
1068
    public function getContainer()
1069
    {
1070
        return self::$container;
1071
    }
1072
1073
    /**
1074
     * Check if IoC Container has been set.
1075
     *
1076
     * @return boolean
1077
     */
1078
    public function hasContainer()
1079
    {
1080
        return self::$container !== null;
1081
    }
1082
}
1083