Completed
Push — master ( 06ed87...5fa095 )
by Irfaq
02:33
created

Api::setTimeOut()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 2
Bugs 0 Features 1
Metric Value
c 2
b 0
f 1
dl 0
loc 6
ccs 3
cts 3
cp 1
rs 9.4285
cc 1
eloc 3
nc 1
nop 1
crap 1
1
<?php
2
3
namespace Telegram\Bot;
4
5
use Illuminate\Contracts\Container\Container;
6
use Telegram\Bot\Commands\CommandBus;
7
use Telegram\Bot\Exceptions\TelegramSDKException;
8
use Telegram\Bot\FileUpload\InputFile;
9
use Telegram\Bot\HttpClients\GuzzleHttpClient;
10
use Telegram\Bot\HttpClients\HttpClientInterface;
11
use Telegram\Bot\Objects\File;
12
use Telegram\Bot\Objects\Message;
13
use Telegram\Bot\Objects\UnknownObject;
14
use Telegram\Bot\Objects\Update;
15
use Telegram\Bot\Objects\User;
16
use Telegram\Bot\Objects\UserProfilePhotos;
17
use Telegram\Bot\Keyboard\Keyboard;
18
use Telegram\Bot\Helpers\Emojify;
19
20
/**
21
 * Class Api.
22
 *
23
 * @mixin Commands\CommandBus
24
 */
25
class Api
26
{
27
    /**
28
     * @var string Version number of the Telegram Bot PHP SDK.
29
     */
30
    const VERSION = '3.0.0';
31
32
    /**
33
     * @var string The name of the environment variable that contains the Telegram Bot API Access Token.
34
     */
35
    const BOT_TOKEN_ENV_NAME = 'TELEGRAM_BOT_TOKEN';
36
37
    /**
38
     * @var TelegramClient The Telegram client service.
39
     */
40
    protected $client;
41
42
    /**
43
     * @var string Telegram Bot API Access Token.
44
     */
45
    protected $accessToken = null;
46
47
    /**
48
     * @var TelegramResponse|null Stores the last request made to Telegram Bot API.
49
     */
50
    protected $lastResponse;
51
52
    /**
53
     * @var bool Indicates if the request to Telegram will be asynchronous (non-blocking).
54
     */
55
    protected $isAsyncRequest = false;
56
57
    /**
58
     * @var CommandBus|null Telegram Command Bus.
59
     */
60
    protected $commandBus = null;
61
62
    /**
63
     * @var Container IoC Container
64
     */
65
    protected static $container = null;
66
67
    /**
68
     * Timeout of the request in seconds.
69
     *
70
     * @var int
71
     */
72
    protected $timeOut = 60;
73
74
    /**
75
     * Connection timeout of the request in seconds.
76
     *
77
     * @var int
78
     */
79
    protected $connectTimeOut = 10;
80
81
    /**
82
     * Instantiates a new Telegram super-class object.
83
     *
84
     *
85
     * @param string              $token                      The Telegram Bot API Access Token.
86
     * @param bool                $async                      (Optional) Indicates if the request to Telegram
87
     *                                                        will be asynchronous (non-blocking).
88
     * @param HttpClientInterface $httpClientHandler          (Optional) Custom HTTP Client Handler.
89
     *
90
     * @throws TelegramSDKException
91
     */
92 68
    public function __construct($token = null, $async = false, $httpClientHandler = null)
93
    {
94 68
        $this->accessToken = isset($token) ? $token : getenv(static::BOT_TOKEN_ENV_NAME);
95 68
        if (!$this->accessToken) {
96 2
            throw new TelegramSDKException('Required "token" not supplied in config and could not find fallback environment variable "'.static::BOT_TOKEN_ENV_NAME.'"');
97
        }
98
99 68
        if (isset($async)) {
100 68
            $this->setAsyncRequest($async);
101 68
        }
102
103 68
        $this->client = new TelegramClient($httpClientHandler);
104 68
        $this->commandBus = new CommandBus($this);
105 68
    }
106
107
    /**
108
     * Invoke Bots Manager.
109
     *
110
     * @param $config
111
     *
112
     * @return BotsManager
113
     */
114
    public static function manager($config)
115
    {
116
        return new BotsManager($config);
117
    }
118
119
    /**
120
     * Returns the TelegramClient service.
121
     *
122
     * @return TelegramClient
123
     */
124 6
    public function getClient()
125
    {
126 6
        return $this->client;
127
    }
128
129
    /**
130
     * Returns Telegram Bot API Access Token.
131
     *
132
     * @return string
133
     */
134 42
    public function getAccessToken()
135
    {
136 42
        return $this->accessToken;
137
    }
138
139
    /**
140
     * Returns the last response returned from API request.
141
     *
142
     * @return TelegramResponse
143
     */
144 2
    public function getLastResponse()
145
    {
146 2
        return $this->lastResponse;
147
    }
148
149
    /**
150
     * Sets the bot access token to use with API requests.
151
     *
152
     * @param string $accessToken The bot access token to save.
153
     *
154
     * @throws \InvalidArgumentException
155
     *
156
     * @return Api
157
     */
158 8
    public function setAccessToken($accessToken)
159
    {
160 8
        if (is_string($accessToken)) {
161 2
            $this->accessToken = $accessToken;
162
163 2
            return $this;
164
        }
165
166 6
        throw new \InvalidArgumentException('The Telegram bot access token must be of type "string"');
167
    }
168
169
    /**
170
     * Make this request asynchronous (non-blocking).
171
     *
172
     * @param bool $isAsyncRequest
173
     *
174
     * @return Api
175
     */
176 68
    public function setAsyncRequest($isAsyncRequest)
177
    {
178 68
        $this->isAsyncRequest = $isAsyncRequest;
179
180 68
        return $this;
181
    }
182
183
    /**
184
     * Check if this is an asynchronous request (non-blocking).
185
     *
186
     * @return bool
187
     */
188 42
    public function isAsyncRequest()
189
    {
190 42
        return $this->isAsyncRequest;
191
    }
192
193
    /**
194
     * Returns SDK's Command Bus.
195
     *
196
     * @return CommandBus
197
     */
198 8
    public function getCommandBus()
199
    {
200 8
        return $this->commandBus;
201
    }
202
203
    /**
204
     * A simple method for testing your bot's auth token.
205
     * Returns basic information about the bot in form of a User object.
206
     *
207
     * @link https://core.telegram.org/bots/api#getme
208
     *
209
     * @return User
210
     */
211 4
    public function getMe()
212
    {
213 4
        $response = $this->post('getMe');
214
215 2
        return new User($response->getDecodedBody());
216
    }
217
218
    /**
219
     * Send text messages.
220
     *
221
     * <code>
222
     * $params = [
223
     *   'chat_id'                  => '',
224
     *   'text'                     => '',
225
     *   'parse_mode'               => '',
226
     *   'disable_web_page_preview' => '',
227
     *   'disable_notification'     => '',
228
     *   'reply_to_message_id'      => '',
229
     *   'reply_markup'             => '',
230
     * ];
231
     * </code>
232
     *
233
     * @link https://core.telegram.org/bots/api#sendmessage
234
     *
235
     * @param array    $params
236
     *
237
     * @var int|string $params ['chat_id']
238
     * @var string     $params ['text']
239
     * @var string     $params ['parse_mode']
240
     * @var bool       $params ['disable_web_page_preview']
241
     * @var bool       $params ['disable_notification']
242
     * @var int        $params ['reply_to_message_id']
243
     * @var string     $params ['reply_markup']
244
     *
245
     * @return Message
246
     */
247 4 View Code Duplication
    public function sendMessage(array $params)
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...
248
    {
249 4
        $params = $this->emojify($params, 'text');
250 4
        $response = $this->post('sendMessage', $params);
251
252 4
        return new Message($response->getDecodedBody());
253
    }
254
255
    /**
256
     * Forward messages of any kind.
257
     *
258
     * <code>
259
     * $params = [
260
     *   'chat_id'              => '',
261
     *   'from_chat_id'         => '',
262
     *   'disable_notification' => '',
263
     *   'message_id'           => '',
264
     * ];
265
     * </code>
266
     *
267
     * @link https://core.telegram.org/bots/api#forwardmessage
268
     *
269
     * @param array    $params
270
     *
271
     * @var int|string $params ['chat_id']
272
     * @var int        $params ['from_chat_id']
273
     * @var bool       $params ['disable_notification']
274
     * @var int        $params ['message_id']
275
     *
276
     * @return Message
277
     */
278 2
    public function forwardMessage(array $params)
279
    {
280 2
        $response = $this->post('forwardMessage', $params);
281
282 2
        return new Message($response->getDecodedBody());
283
    }
284
285
    /**
286
     * Send Photos.
287
     *
288
     * <code>
289
     * $params = [
290
     *   'chat_id'              => '',
291
     *   'photo'                => '',
292
     *   'caption'              => '',
293
     *   'disable_notification' => '',
294
     *   'reply_to_message_id'  => '',
295
     *   'reply_markup'         => '',
296
     * ];
297
     * </code>
298
     *
299
     * @link https://core.telegram.org/bots/api#sendphoto
300
     *
301
     * @param array    $params
302
     *
303
     * @var int|string $params ['chat_id']
304
     * @var string     $params ['photo']
305
     * @var string     $params ['caption']
306
     * @var bool       $params ['disable_notification']
307
     * @var int        $params ['reply_to_message_id']
308
     * @var string     $params ['reply_markup']
309
     *
310
     * @return Message
311
     */
312 4
    public function sendPhoto(array $params)
313
    {
314 4
        $params = $this->emojify($params, 'caption');
315
316 4
        return $this->uploadFile('sendPhoto', $params);
317
    }
318
319
    /**
320
     * Send regular audio files.
321
     *
322
     * <code>
323
     * $params = [
324
     *   'chat_id'              => '',
325
     *   'audio'                => '',
326
     *   'duration'             => '',
327
     *   'performer'            => '',
328
     *   'title'                => '',
329
     *   'disable_notification' => '',
330
     *   'reply_to_message_id'  => '',
331
     *   'reply_markup'         => '',
332
     * ];
333
     * </code>
334
     *
335
     * @link https://core.telegram.org/bots/api#sendaudio
336
     *
337
     * @param array    $params
338
     *
339
     * @var int|string $params ['chat_id']
340
     * @var string     $params ['audio']
341
     * @var int        $params ['duration']
342
     * @var string     $params ['performer']
343
     * @var string     $params ['title']
344
     * @var bool       $params ['disable_notification']
345
     * @var int        $params ['reply_to_message_id']
346
     * @var string     $params ['reply_markup']
347
     *
348
     * @return Message
349
     */
350 2
    public function sendAudio(array $params)
351
    {
352 2
        return $this->uploadFile('sendAudio', $params);
353
    }
354
355
    /**
356
     * Send general files.
357
     *
358
     * <code>
359
     * $params = [
360
     *   'chat_id'              => '',
361
     *   'document'             => '',
362
     *   'caption'              => '',
363
     *   'disable_notification' => '',
364
     *   'reply_to_message_id'  => '',
365
     *   'reply_markup'         => '',
366
     * ];
367
     * </code>
368
     *
369
     * @link https://core.telegram.org/bots/api#senddocument
370
     *
371
     * @param array    $params
372
     *
373
     * @var int|string $params ['chat_id']
374
     * @var string     $params ['document']
375
     * @var string     $params ['caption']
376
     * @var bool       $params ['disable_notification']
377
     * @var int        $params ['reply_to_message_id']
378
     * @var string     $params ['reply_markup']
379
     *
380
     * @return Message
381
     */
382 2
    public function sendDocument(array $params)
383
    {
384 2
        $params = $this->emojify($params, 'caption');
385
386 2
        return $this->uploadFile('sendDocument', $params);
387
    }
388
389
    /**
390
     * Send .webp stickers.
391
     *
392
     * <code>
393
     * $params = [
394
     *   'chat_id'              => '',
395
     *   'sticker'              => '',
396
     *   'disable_notification' => '',
397
     *   'reply_to_message_id'  => '',
398
     *   'reply_markup'         => '',
399
     * ];
400
     * </code>
401
     *
402
     * @link https://core.telegram.org/bots/api#sendsticker
403
     *
404
     * @param array    $params
405
     *
406
     * @var int|string $params ['chat_id']
407
     * @var string     $params ['sticker']
408
     * @var bool       $params ['disable_notification']
409
     * @var int        $params ['reply_to_message_id']
410
     * @var string     $params ['reply_markup']
411
     *
412
     * @throws TelegramSDKException
413
     *
414
     * @return Message
415
     */
416 2
    public function sendSticker(array $params)
417
    {
418 2
        if (is_file($params['sticker']) && (pathinfo($params['sticker'], PATHINFO_EXTENSION) !== 'webp')) {
419
            throw new TelegramSDKException('Invalid Sticker Provided. Supported Format: Webp');
420
        }
421
422 2
        return $this->uploadFile('sendSticker', $params);
423
    }
424
425
    /**
426
     * Send Video File, Telegram clients support mp4 videos (other formats may be sent as Document).
427
     *
428
     * <code>
429
     * $params = [
430
     *   'chat_id'              => '',
431
     *   'video'                => '',
432
     *   'duration'             => '',
433
     *   'width'                => '',
434
     *   'height'               => '',
435
     *   'caption'              => '',
436
     *   'disable_notification' => '',
437
     *   'reply_to_message_id'  => '',
438
     *   'reply_markup'         => '',
439
     * ];
440
     * </code>
441
     *
442
     * @see  sendDocument
443
     * @link https://core.telegram.org/bots/api#sendvideo
444
     *
445
     * @param array    $params
446
     *
447
     * @var int|string $params ['chat_id']
448
     * @var string     $params ['video']
449
     * @var int        $params ['duration']
450
     * @var int        $params ['width']
451
     * @var int        $params ['height']
452
     * @var string     $params ['caption']
453
     * @var bool       $params ['disable_notification']
454
     * @var int        $params ['reply_to_message_id']
455
     * @var string     $params ['reply_markup']
456
     *
457
     * @return Message
458
     */
459 2
    public function sendVideo(array $params)
460
    {
461 2
        $params = $this->emojify($params, 'caption');
462
463 2
        return $this->uploadFile('sendVideo', $params);
464
    }
465
466
    /**
467
     * Send voice audio files.
468
     *
469
     * <code>
470
     * $params = [
471
     *   'chat_id'              => '',
472
     *   'voice'                => '',
473
     *   'duration'             => '',
474
     *   'disable_notification' => '',
475
     *   'reply_to_message_id'  => '',
476
     *   'reply_markup'         => '',
477
     * ];
478
     * </code>
479
     *
480
     * @link https://core.telegram.org/bots/api#sendaudio
481
     *
482
     * @param array    $params
483
     *
484
     * @var int|string $params ['chat_id']
485
     * @var string     $params ['voice']
486
     * @var int        $params ['duration']
487
     * @var bool       $params ['disable_notification']
488
     * @var int        $params ['reply_to_message_id']
489
     * @var string     $params ['reply_markup']
490
     *
491
     * @return Message
492
     */
493 2
    public function sendVoice(array $params)
494
    {
495 2
        return $this->uploadFile('sendVoice', $params);
496
    }
497
498
    /**
499
     * Send point on the map.
500
     *
501
     * <code>
502
     * $params = [
503
     *   'chat_id'              => '',
504
     *   'latitude'             => '',
505
     *   'longitude'            => '',
506
     *   'disable_notification' => '',
507
     *   'reply_to_message_id'  => '',
508
     *   'reply_markup'         => '',
509
     * ];
510
     * </code>
511
     *
512
     * @link https://core.telegram.org/bots/api#sendlocation
513
     *
514
     * @param array    $params
515
     *
516
     * @var int|string $params ['chat_id']
517
     * @var float      $params ['latitude']
518
     * @var float      $params ['longitude']
519
     * @var bool       $params ['disable_notification']
520
     * @var int        $params ['reply_to_message_id']
521
     * @var string     $params ['reply_markup']
522
     *
523
     * @return Message
524
     */
525 2
    public function sendLocation(array $params)
526
    {
527 2
        $response = $this->post('sendLocation', $params);
528
529 2
        return new Message($response->getDecodedBody());
530
    }
531
532
    /**
533
     * Send information about a venue.
534
     *
535
     * <code>
536
     * $params = [
537
     *   'chat_id'              => '',
538
     *   'latitude'             => '',
539
     *   'longitude'            => '',
540
     *   'title'                => '',
541
     *   'address'              => '',
542
     *   'foursquare_id'        => '',
543
     *   'disable_notification' => '',
544
     *   'reply_to_message_id'  => '',
545
     *   'reply_markup'         => '',
546
     * ];
547
     * </code>
548
     *
549
     * @link https://core.telegram.org/bots/api#sendvenue
550
     *
551
     * @param array    $params
552
     *
553
     * @var int|string $params ['chat_id']
554
     * @var float      $params ['latitude']
555
     * @var float      $params ['longitude']
556
     * @var string     $params ['title']
557
     * @var string     $params ['address']
558
     * @var string     $params ['foursquare_id']
559
     * @var bool       $params ['disable_notification']
560
     * @var int        $params ['reply_to_message_id']
561
     * @var string     $params ['reply_markup']
562
     *
563
     * @return Message
564
     */
565
    public function sendVenue(array $params)
566
    {
567
        $response = $this->post('sendVenue', $params);
568
569
        return new Message($response->getDecodedBody());
570
    }
571
572
    /**
573
     * Send phone contacts.
574
     *
575
     * <code>
576
     * $params = [
577
     *   'chat_id'              => '',
578
     *   'phone_number'         => '',
579
     *   'first_name'           => '',
580
     *   'last_name'            => '',
581
     *   'disable_notification' => '',
582
     *   'reply_to_message_id'  => '',
583
     *   'reply_markup'         => '',
584
     * ];
585
     * </code>
586
     *
587
     * @link https://core.telegram.org/bots/api#sendcontact
588
     *
589
     * @param array    $params
590
     *
591
     * @var int|string $params ['chat_id']
592
     * @var string     $params ['phone_number']
593
     * @var string     $params ['first_name']
594
     * @var string     $params ['last_name']
595
     * @var bool       $params ['disable_notification']
596
     * @var int        $params ['reply_to_message_id']
597
     * @var string     $params ['reply_markup']
598
     *
599
     * @return Message
600
     */
601
    public function sendContact(array $params)
602
    {
603
        $response = $this->post('sendContact', $params);
604
605
        return new Message($response->getDecodedBody());
606
    }
607
608
    /**
609
     * Broadcast a Chat Action.
610
     *
611
     * <code>
612
     * $params = [
613
     *   'chat_id' => '',
614
     *   'action'  => '',
615
     * ];
616
     * </code>
617
     *
618
     * @link https://core.telegram.org/bots/api#sendchataction
619
     *
620
     * @param array    $params
621
     *
622
     * @var int|string $params ['chat_id']
623
     * @var string     $params ['action']
624
     *
625
     * @throws TelegramSDKException
626
     *
627
     * @return TelegramResponse
628
     */
629 4
    public function sendChatAction(array $params)
630
    {
631
        $validActions = [
632 4
            'typing',
633 4
            'upload_photo',
634 4
            'record_video',
635 4
            'upload_video',
636 4
            'record_audio',
637 4
            'upload_audio',
638 4
            'upload_document',
639 4
            'find_location',
640 4
        ];
641
642 4
        if (isset($params['action']) && in_array($params['action'], $validActions)) {
643 2
            return $this->post('sendChatAction', $params);
644
        }
645
646 2
        throw new TelegramSDKException('Invalid Action! Accepted value: '.implode(', ', $validActions));
647
    }
648
649
    /**
650
     * Returns a list of profile pictures for a user.
651
     *
652
     * <code>
653
     * $params = [
654
     *   'user_id' => '',
655
     *   'offset'  => '',
656
     *   'limit'   => '',
657
     * ];
658
     * </code>
659
     *
660
     * @link https://core.telegram.org/bots/api#getuserprofilephotos
661
     *
662
     * @param array $params
663
     *
664
     * @var int     $params ['user_id']
665
     * @var int     $params ['offset']
666
     * @var int     $params ['limit']
667
     *
668
     * @return UserProfilePhotos
669
     */
670
    public function getUserProfilePhotos(array $params)
671
    {
672
        $response = $this->post('getUserProfilePhotos', $params);
673
674
        return new UserProfilePhotos($response->getDecodedBody());
675
    }
676
677
    /**
678
     * Returns basic info about a file and prepare it for downloading.
679
     *
680
     * <code>
681
     * $params = [
682
     *   'file_id' => '',
683
     * ];
684
     * </code>
685
     *
686
     * The file can then be downloaded via the link
687
     * https://api.telegram.org/file/bot<token>/<file_path>,
688
     * where <file_path> is taken from the response.
689
     *
690
     * @link https://core.telegram.org/bots/api#getFile
691
     *
692
     * @param array $params
693
     *
694
     * @var string  $params ['file_id']
695
     *
696
     * @return File
697
     */
698 2
    public function getFile(array $params)
699
    {
700 2
        $response = $this->post('getFile', $params);
701
702 2
        return new File($response->getDecodedBody());
703
    }
704
705
    /**
706
     * Kick a user from a group or a supergroup.
707
     *
708
     * In the case of supergroups, the user will not be able to return to the group on their own using
709
     * invite links etc., unless unbanned first.
710
     *
711
     * The bot must be an administrator in the group for this to work.
712
     *
713
     * <code>
714
     * $params = [
715
     *   'chat_id'              => '',
716
     *   'user_id'              => '',
717
     * ];
718
     * </code>
719
     *
720
     * @link https://core.telegram.org/bots/api#kickchatmember
721
     *
722
     * @param array    $params
723
     *
724
     * @var int|string $params ['chat_id']
725
     * @var int        $params ['user_id']
726
     *
727
     * @return TelegramResponse
728
     */
729
    public function kickChatMember(array $params)
730
    {
731
        return $this->post('kickChatMember', $params);
732
    }
733
734
    /**
735
     * Unban a previously kicked user in a supergroup.
736
     *
737
     * The user will not return to the group automatically, but will be able to join via link, etc.
738
     *
739
     * The bot must be an administrator in the group for this to work.
740
     *
741
     * <code>
742
     * $params = [
743
     *   'chat_id'              => '',
744
     *   'user_id'              => '',
745
     * ];
746
     * </code>
747
     *
748
     * @link https://core.telegram.org/bots/api#unbanchatmember
749
     *
750
     * @param array    $params
751
     *
752
     * @var int|string $params ['chat_id']
753
     * @var int        $params ['user_id']
754
     *
755
     * @return TelegramResponse
756
     */
757
    public function unbanChatMember(array $params)
758
    {
759
        return $this->post('unbanChatMember', $params);
760
    }
761
762
    /**
763
     * Send answers to callback queries sent from inline keyboards.
764
     *
765
     * he answer will be displayed to the user as a notification at the top of the chat screen or as an alert.
766
     *
767
     * <code>
768
     * $params = [
769
     *   'callback_query_id'  => '',
770
     *   'text'               => '',
771
     *   'show_alert'         => '',
772
     * ];
773
     * </code>
774
     *
775
     * @link https://core.telegram.org/bots/api#answerCallbackQuery
776
     *
777
     * @param array $params
778
     *
779
     * @var string  $params ['callback_query_id']
780
     * @var string  $params ['text']
781
     * @var bool    $params ['show_alert']
782
     *
783
     * @return TelegramResponse
784
     */
785
    public function answerCallbackQuery(array $params)
786
    {
787
        $params = $this->emojify($params, 'text');
788
789
        return $this->post('answerCallbackQuery', $params);
790
    }
791
792
    /**
793
     * Edit text messages sent by the bot or via the bot (for inline bots).
794
     *
795
     * <code>
796
     * $params = [
797
     *   'chat_id'                  => '',
798
     *   'message_id'               => '',
799
     *   'inline_message_id'        => '',
800
     *   'text'                     => '',
801
     *   'parse_mode'               => '',
802
     *   'disable_web_page_preview' => '',
803
     *   'reply_markup'             => '',
804
     * ];
805
     * </code>
806
     *
807
     * @link https://core.telegram.org/bots/api#editMessageText
808
     *
809
     * @param array    $params
810
     *
811
     * @var int|string $params ['chat_id']
812
     * @var int        $params ['message_id']
813
     * @var string     $params ['inline_message_id']
814
     * @var string     $params ['text']
815
     * @var string     $params ['parse_mode']
816
     * @var bool       $params ['disable_web_page_preview']
817
     * @var string     $params ['reply_markup']
818
     *
819
     * @return TelegramResponse
820
     */
821 View Code Duplication
    public function editMessageText(array $params)
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...
822
    {
823
        $params = $this->emojify($params, 'text');
824
        $response = $this->post('editMessageText', $params);
825
826
        return new Message($response->getDecodedBody());
827
    }
828
829
    /**
830
     * Edit captions of messages sent by the bot or via the bot (for inline bots).
831
     *
832
     * <code>
833
     * $params = [
834
     *   'chat_id'                  => '',
835
     *   'message_id'               => '',
836
     *   'inline_message_id'        => '',
837
     *   'caption'                  => '',
838
     *   'reply_markup'             => '',
839
     * ];
840
     * </code>
841
     *
842
     * @link https://core.telegram.org/bots/api#editMessageCaption
843
     *
844
     * @param array    $params
845
     *
846
     * @var int|string $params ['chat_id']
847
     * @var int        $params ['message_id']
848
     * @var string     $params ['inline_message_id']
849
     * @var string     $params ['caption']
850
     * @var string     $params ['reply_markup']
851
     *
852
     * @return TelegramResponse
853
     */
854
    public function editMessageCaption(array $params)
855
    {
856
        $params = $this->emojify($params, 'caption');
857
        $response = $this->post('editMessageCaption', $params);
858
859
        return new Message($response->getDecodedBody());
860
    }
861
862
    /**
863
     * Edit only the reply markup of messages sent by the bot or via the bot (for inline bots).
864
     *
865
     * <code>
866
     * $params = [
867
     *   'chat_id'                  => '',
868
     *   'message_id'               => '',
869
     *   'inline_message_id'        => '',
870
     *   'reply_markup'             => '',
871
     * ];
872
     * </code>
873
     *
874
     * @link https://core.telegram.org/bots/api#editMessageReplyMarkup
875
     *
876
     * @param array    $params
877
     *
878
     * @var int|string $params ['chat_id']
879
     * @var int        $params ['message_id']
880
     * @var string     $params ['inline_message_id']
881
     * @var string     $params ['reply_markup']
882
     *
883
     * @return TelegramResponse
884
     */
885
    public function editMessageReplyMarkup(array $params)
886
    {
887
        $response = $this->post('editMessageReplyMarkup', $params);
888
889
        return new Message($response->getDecodedBody());
890
    }
891
892
    /**
893
     * Use this method to send answers to an inline query.
894
     *
895
     * <code>
896
     * $params = [
897
     *   'inline_query_id'      => '',
898
     *   'results'              => [],
899
     *   'cache_time'           => 0,
900
     *   'is_personal'          => false,
901
     *   'next_offset'          => '',
902
     *   'switch_pm_text'       => '',
903
     *   'switch_pm_parameter'  => '',
904
     * ];
905
     * </code>
906
     *
907
     * @link https://core.telegram.org/bots/api#answerinlinequery
908
     *
909
     * @param array     $params
910
     *
911
     * @var string      $params ['inline_query_id']
912
     * @var array       $params ['results']
913
     * @var int|null    $params ['cache_time']
914
     * @var bool|null   $params ['is_personal']
915
     * @var string|null $params ['next_offset']
916
     * @var string|null $params ['switch_pm_text']
917
     * @var string|null $params ['switch_pm_parameter']
918
     *
919
     * @return bool
920
     */
921
    public function answerInlineQuery(array $params = [])
922
    {
923
        if (is_array($params['results'])) {
924
            $params['results'] = json_encode($params['results']);
925
        }
926
927
        return $this->post('answerInlineQuery', $params);
928
    }
929
930
    /**
931
     * Set a Webhook to receive incoming updates via an outgoing webhook.
932
     *
933
     * <code>
934
     * $params = [
935
     *   'url'         => '',
936
     *   'certificate' => '',
937
     * ];
938
     * </code>
939
     *
940
     * @link https://core.telegram.org/bots/api#setwebhook
941
     *
942
     * @param array $params
943
     *
944
     * @var string  $params ['url']         HTTPS url to send updates to.
945
     * @var string  $params ['certificate'] Upload your public key certificate so that the root certificate in
946
     *                                      use can be checked.
947
     *
948
     * @throws TelegramSDKException
949
     *
950
     * @return TelegramResponse
951
     */
952 6
    public function setWebhook(array $params)
953
    {
954 6
        if (filter_var($params['url'], FILTER_VALIDATE_URL) === false) {
955 2
            throw new TelegramSDKException('Invalid URL Provided');
956
        }
957
958 4
        if (parse_url($params['url'], PHP_URL_SCHEME) !== 'https') {
959 2
            throw new TelegramSDKException('Invalid URL, should be a HTTPS url.');
960
        }
961
962 2
        return $this->uploadFile('setWebhook', $params);
963
    }
964
965
    /**
966
     * Returns webhook updates sent by Telegram.
967
     * Works only if you set a webhook.
968
     *
969
     * @see setWebhook
970
     *
971
     * @return Update
972
     */
973
    public function getWebhookUpdates()
974
    {
975
        $body = json_decode(file_get_contents('php://input'), true);
976
977
        return new Update($body);
978
    }
979
980
    /**
981
     * Removes the outgoing webhook (if any).
982
     *
983
     * @return TelegramResponse
984
     */
985 2
    public function removeWebhook()
986
    {
987 2
        $url = '';
988
989 2
        return $this->post('setWebhook', compact('url'));
990
    }
991
992
    /**
993
     * Use this method to receive incoming updates using long polling.
994
     *
995
     * <code>
996
     * $params = [
997
     *   'offset'  => '',
998
     *   'limit'   => '',
999
     *   'timeout' => '',
1000
     * ];
1001
     * </code>
1002
     *
1003
     * @link https://core.telegram.org/bots/api#getupdates
1004
     *
1005
     * @param array  $params
1006
     *
1007
     * @var int|null $params ['offset']
1008
     * @var int|null $params ['limit']
1009
     * @var int|null $params ['timeout']
1010
     *
1011
     * @return Update[]
1012
     */
1013 6
    public function getUpdates(array $params = [])
1014
    {
1015 6
        $response = $this->post('getUpdates', $params);
1016 6
        $updates = $response->getDecodedBody();
1017
1018 6
        $data = [];
1019 6
        if (isset($updates['result'])) {
1020 6
            foreach ($updates['result'] as $update) {
1021 6
                $data[] = new Update($update);
1022 6
            }
1023 6
        }
1024
1025 6
        return $data;
1026
    }
1027
1028
1029
    /**
1030
     * Builds a custom keyboard markup.
1031
     *
1032
     * <code>
1033
     * $params = [
1034
     *   'keyboard'          => '',
1035
     *   'resize_keyboard'   => '',
1036
     *   'one_time_keyboard' => '',
1037
     *   'selective'         => '',
1038
     * ];
1039
     * </code>
1040
     *
1041
     * @deprecated Use Telegram\Bot\Keyboard\Keyboard::make(array $params = []) instead.
1042
     *             To be removed in next major version.
1043
     *
1044
     * @link       https://core.telegram.org/bots/api#replykeyboardmarkup
1045
     *
1046
     * @param array $params
1047
     *
1048
     * @var array   $params ['keyboard']
1049
     * @var bool    $params ['resize_keyboard']
1050
     * @var bool    $params ['one_time_keyboard']
1051
     * @var bool    $params ['selective']
1052
     *
1053
     * @return string
1054
     */
1055
    public function replyKeyboardMarkup(array $params)
1056
    {
1057
        return Keyboard::make($params);
1058
    }
1059
1060
    /**
1061
     * Hide the current custom keyboard and display the default letter-keyboard.
1062
     *
1063
     * <code>
1064
     * $params = [
1065
     *   'hide_keyboard' => true,
1066
     *   'selective'     => false,
1067
     * ];
1068
     * </code>
1069
     *
1070
     * @deprecated Use Telegram\Bot\Keyboard\Keyboard::make()->hide(array $params = []) instead.
1071
     *             To be removed in next major version.
1072
     *
1073
     * @link       https://core.telegram.org/bots/api#replykeyboardhide
1074
     *
1075
     * @param array $params
1076
     *
1077
     * @var bool    $params ['hide_keyboard']
1078
     * @var bool    $params ['selective']
1079
     *
1080
     * @return string
1081
     */
1082
    public static function replyKeyboardHide(array $params = [])
1083
    {
1084
        return Keyboard::make()->hide($params);
1085
    }
1086
1087
    /**
1088
     * Display a reply interface to the user (act as if the user has selected the bot‘s message and tapped ’Reply').
1089
     *
1090
     * <code>
1091
     * $params = [
1092
     *   'force_reply' => true,
1093
     *   'selective'   => false,
1094
     * ];
1095
     * </code>
1096
     *
1097
     * @deprecated Use Telegram\Bot\Keyboard\Keyboard::make()->forceReply(array $params = []) instead.
1098
     *             To be removed in next major version.
1099
     *
1100
     * @link       https://core.telegram.org/bots/api#forcereply
1101
     *
1102
     * @param array $params
1103
     *
1104
     * @var bool    $params ['force_reply']
1105
     * @var bool    $params ['selective']
1106
     *
1107
     * @return string
1108
     */
1109
    public static function forceReply(array $params = [])
1110
    {
1111
        return Keyboard::make()->forceReply($params);
1112
    }
1113
1114
    /**
1115
     * Processes Inbound Commands.
1116
     *
1117
     * @param bool $webhook
1118
     *
1119
     * @return Update|Update[]
1120
     */
1121 6
    public function commandsHandler($webhook = false)
1122
    {
1123 6
        if ($webhook) {
1124
            $update = $this->getWebhookUpdates();
1125
            $this->processCommand($update);
1126
1127
            return $update;
1128
        }
1129
1130 6
        $updates = $this->getUpdates();
1131 6
        $highestId = -1;
1132
1133 6
        foreach ($updates as $update) {
1134 6
            $highestId = $update->getUpdateId();
1135 6
            $this->processCommand($update);
1136 6
        }
1137
1138
        //An update is considered confirmed as soon as getUpdates is called with an offset higher than its update_id.
1139 6
        if ($highestId != -1) {
1140 6
            $params = [];
1141 6
            $params['offset'] = $highestId + 1;
1142 6
            $params['limit'] = 1;
1143 6
            $this->getUpdates($params);
1144 6
        }
1145
1146 6
        return $updates;
1147
    }
1148
1149
    /**
1150
     * Check update object for a command and process.
1151
     *
1152
     * @param Update $update
1153
     */
1154 6
    protected function processCommand(Update $update)
1155
    {
1156 6
        $message = $update->getMessage();
1157
1158 6
        if ($message !== null && $message->has('text')) {
1159 6
            $this->getCommandBus()->handler($message->getText(), $update);
1160 6
        }
1161 6
    }
1162
1163
    /**
1164
     * Helper to Trigger Commands.
1165
     *
1166
     * @param string $name   Command Name
1167
     * @param Update $update Update Object
1168
     *
1169
     * @return mixed
1170
     */
1171
    public function triggerCommand($name, Update $update)
1172
    {
1173
        return $this->getCommandBus()->execute($name, $update->getMessage()->getText(), $update);
1174
    }
1175
1176
    /**
1177
     * Determine if a given type is the message.
1178
     *
1179
     * @param string         $type
1180
     * @param Update|Message $object
1181
     *
1182
     * @return bool
1183
     */
1184
    public function isMessageType($type, $object)
1185
    {
1186
        if ($object instanceof Update) {
1187
            $object = $object->getMessage();
1188
        }
1189
1190
        if ($object->has(strtolower($type))) {
1191
            return true;
1192
        }
1193
1194
        return $this->detectMessageType($object) === $type;
1195
    }
1196
1197
    /**
1198
     * Detect Message Type Based on Update or Message Object.
1199
     *
1200
     * @param Update|Message $object
1201
     *
1202
     * @return string|null
1203
     */
1204
    public function detectMessageType($object)
1205
    {
1206
        if ($object instanceof Update) {
1207
            $object = $object->getMessage();
1208
        }
1209
1210
        $types = [
1211
            'text',
1212
            'audio',
1213
            'document',
1214
            'photo',
1215
            'sticker',
1216
            'video',
1217
            'voice',
1218
            'contact',
1219
            'location',
1220
            'venue',
1221
            'new_chat_member',
1222
            'left_chat_member',
1223
            'new_chat_title',
1224
            'new_chat_photo',
1225
            'delete_chat_photo',
1226
            'group_chat_created',
1227
            'supergroup_chat_created',
1228
            'channel_chat_created',
1229
            'migrate_to_chat_id',
1230
            'migrate_from_chat_id',
1231
            'pinned_message',
1232
        ];
1233
1234
        return $object->keys()
1235
            ->intersect($types)
1236
            ->pop();
1237
    }
1238
1239
    /**
1240
     * Sends a GET request to Telegram Bot API and returns the result.
1241
     *
1242
     * @param string $endpoint
1243
     * @param array  $params
1244
     *
1245
     * @throws TelegramSDKException
1246
     *
1247
     * @return TelegramResponse
1248
     */
1249
    protected function get($endpoint, $params = [])
1250
    {
1251
        if (array_key_exists('reply_markup', $params)) {
1252
            $params['reply_markup'] = (string)$params['reply_markup'];
1253
        }
1254
1255
        return $this->sendRequest(
1256
            'GET',
1257
            $endpoint,
1258
            $params
1259
        );
1260
    }
1261
1262
    /**
1263
     * Sends a POST request to Telegram Bot API and returns the result.
1264
     *
1265
     * @param string $endpoint
1266
     * @param array  $params
1267
     * @param bool   $fileUpload Set true if a file is being uploaded.
1268
     *
1269
     * @return TelegramResponse
1270
     */
1271 40
    protected function post($endpoint, array $params = [], $fileUpload = false)
1272
    {
1273 40
        if ($fileUpload) {
1274 16
            $params = ['multipart' => $params];
1275 16
        } else {
1276
1277 24
            if (array_key_exists('reply_markup', $params)) {
1278
                $params['reply_markup'] = (string)$params['reply_markup'];
1279
            }
1280
1281 24
            $params = ['form_params' => $params];
1282
        }
1283
1284 40
        return $this->sendRequest(
1285 40
            'POST',
1286 40
            $endpoint,
1287
            $params
1288 40
        );
1289
    }
1290
1291
    /**
1292
     * Sends a multipart/form-data request to Telegram Bot API and returns the result.
1293
     * Used primarily for file uploads.
1294
     *
1295
     * @param string $endpoint
1296
     * @param array  $params
1297
     *
1298
     * @throws TelegramSDKException
1299
     *
1300
     * @return Message
1301
     */
1302 16
    protected function uploadFile($endpoint, array $params = [])
1303
    {
1304 16
        $i = 0;
1305 16
        $multipart_params = [];
1306 16
        foreach ($params as $name => $contents) {
1307 16
            if (is_null($contents)) {
1308
                continue;
1309
            }
1310
1311 16
            if (!is_resource($contents) && $name !== 'url') {
1312 14
                $validUrl = filter_var($contents, FILTER_VALIDATE_URL);
1313 14
                $contents = (is_file($contents) || $validUrl) ? (new InputFile($contents))->open() : (string)$contents;
1314 14
            }
1315
1316 16
            $multipart_params[$i]['name'] = $name;
1317 16
            $multipart_params[$i]['contents'] = $contents;
1318 16
            ++$i;
1319 16
        }
1320
1321 16
        $response = $this->post($endpoint, $multipart_params, true);
1322
1323 16
        return new Message($response->getDecodedBody());
1324
    }
1325
1326
    /**
1327
     * Sends a request to Telegram Bot API and returns the result.
1328
     *
1329
     * @param string $method
1330
     * @param string $endpoint
1331
     * @param array  $params
1332
     *
1333
     * @throws TelegramSDKException
1334
     *
1335
     * @return TelegramResponse
1336
     */
1337 40
    protected function sendRequest(
1338
        $method,
1339
        $endpoint,
1340
        array $params = []
1341
    ) {
1342 40
        $request = $this->request($method, $endpoint, $params);
1343
1344 40
        return $this->lastResponse = $this->client->sendRequest($request);
1345
    }
1346
1347
    /**
1348
     * Instantiates a new TelegramRequest entity.
1349
     *
1350
     * @param string $method
1351
     * @param string $endpoint
1352
     * @param array  $params
1353
     *
1354
     * @return TelegramRequest
1355
     */
1356 40
    protected function request(
1357
        $method,
1358
        $endpoint,
1359
        array $params = []
1360
    ) {
1361 40
        return new TelegramRequest(
1362 40
            $this->getAccessToken(),
1363 40
            $method,
1364 40
            $endpoint,
1365 40
            $params,
1366 40
            $this->isAsyncRequest(),
1367 40
            $this->getTimeOut(),
1368 40
            $this->getConnectTimeOut()
1369 40
        );
1370
    }
1371
1372
    /**
1373
     * Magic method to process any "get" requests.
1374
     *
1375
     * @param $method
1376
     * @param $arguments
1377
     *
1378
     * @return bool|TelegramResponse|UnknownObject
1379
     */
1380 2
    public function __call($method, $arguments)
1381
    {
1382 2
        if (preg_match('/^\w+Commands?/', $method, $matches)) {
1383 2
            return call_user_func_array([$this->getCommandBus(), $matches[0]], $arguments);
1384
        }
1385
1386
        $action = substr($method, 0, 3);
1387
        if ($action === 'get') {
1388
            /* @noinspection PhpUndefinedFunctionInspection */
1389
            $class_name = studly_case(substr($method, 3));
1390
            $class = 'Telegram\Bot\Objects\\'.$class_name;
1391
            $response = $this->post($method, $arguments[0] ?: []);
1392
1393
            if (class_exists($class)) {
1394
                return new $class($response->getDecodedBody());
1395
            }
1396
1397
            return $response;
1398
        }
1399
        $response = $this->post($method, $arguments[0]);
1400
1401
        return new UnknownObject($response->getDecodedBody());
1402
    }
1403
1404
    /**
1405
     * Set the IoC Container.
1406
     *
1407
     * @param $container Container instance
1408
     *
1409
     * @return void
1410
     */
1411 2
    public static function setContainer(Container $container)
1412
    {
1413 2
        self::$container = $container;
1414 2
    }
1415
1416
    /**
1417
     * Get the IoC Container.
1418
     *
1419
     * @return Container
1420
     */
1421 2
    public function getContainer()
1422
    {
1423 2
        return self::$container;
1424
    }
1425
1426
    /**
1427
     * Check if IoC Container has been set.
1428
     *
1429
     * @return boolean
1430
     */
1431
    public function hasContainer()
1432
    {
1433
        return self::$container !== null;
1434
    }
1435
1436
    /**
1437
     * @return int
1438
     */
1439 40
    public function getTimeOut()
1440
    {
1441 40
        return $this->timeOut;
1442
    }
1443
1444
    /**
1445
     * @param int $timeOut
1446
     *
1447
     * @return $this
1448
     */
1449 2
    public function setTimeOut($timeOut)
1450
    {
1451 2
        $this->timeOut = $timeOut;
1452
1453 2
        return $this;
1454
    }
1455
1456
    /**
1457
     * @return int
1458
     */
1459 40
    public function getConnectTimeOut()
1460
    {
1461 40
        return $this->connectTimeOut;
1462
    }
1463
1464
    /**
1465
     * @param int $connectTimeOut
1466
     *
1467
     * @return $this
1468
     */
1469 2
    public function setConnectTimeOut($connectTimeOut)
1470
    {
1471 2
        $this->connectTimeOut = $connectTimeOut;
1472
1473 2
        return $this;
1474
    }
1475
1476
    /**
1477
     * Emojify Given Property in Params.
1478
     *
1479
     * @param array  $params
1480
     * @param string $property
1481
     *
1482
     * @return mixed
1483
     */
1484 12
    protected function emojify(array $params, $property)
1485
    {
1486 12
        if (isset($params[$property])) {
1487 4
            $params[$property] = Emojify::text($params[$property]);
1488 4
        }
1489
1490 12
        return $params;
1491
    }
1492
}
1493