Completed
Pull Request — master (#152)
by
unknown
16:38 queued 13:59
created

Api::isUseEmojify()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

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