Completed
Push — 511-custom_http_client ( 6e7024 )
by Armando
02:59
created

Request::leaveChat()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 4
ccs 0
cts 2
cp 0
rs 10
cc 1
eloc 2
nc 1
nop 1
crap 2
1
<?php
2
/**
3
 * This file is part of the TelegramBot package.
4
 *
5
 * (c) Avtandil Kikabidze aka LONGMAN <[email protected]>
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 */
10
11
namespace Longman\TelegramBot;
12
13
use GuzzleHttp\Client;
14
use GuzzleHttp\Exception\RequestException;
15
use Longman\TelegramBot\Entities\File;
16
use Longman\TelegramBot\Entities\ServerResponse;
17
use Longman\TelegramBot\Exception\TelegramException;
18
19
class Request
20
{
21
    /**
22
     * Telegram object
23
     *
24
     * @var \Longman\TelegramBot\Telegram
25
     */
26
    private static $telegram;
27
28
    /**
29
     * URI of the Telegram API
30
     *
31
     * @var string
32
     */
33
    private static $api_base_uri = 'https://api.telegram.org';
34
35
    /**
36
     * Guzzle Client object
37
     *
38
     * @var \GuzzleHttp\Client
39
     */
40
    private static $client;
41
42
    /**
43
     * Input value of the request
44
     *
45
     * @var string
46
     */
47
    private static $input;
48
49
    /**
50
     * Request limiter
51
     *
52
     * @var boolean
53
     */
54
    private static $limiter_enabled;
55
56
    /**
57
     * Request limiter's interval between checks
58
     *
59
     * @var boolean
60
     */
61
    private static $limiter_interval;
62
63
    /**
64
     * Available actions to send
65
     *
66
     * @var array
67
     */
68
    private static $actions = [
69
        'getUpdates',
70
        'setWebhook',
71
        'deleteWebhook',
72
        'getMe',
73
        'sendMessage',
74
        'forwardMessage',
75
        'sendPhoto',
76
        'sendAudio',
77
        'sendDocument',
78
        'sendSticker',
79
        'sendVideo',
80
        'sendVoice',
81
        'sendLocation',
82
        'sendVenue',
83
        'sendContact',
84
        'sendChatAction',
85
        'getUserProfilePhotos',
86
        'getFile',
87
        'kickChatMember',
88
        'leaveChat',
89
        'unbanChatMember',
90
        'getChat',
91
        'getChatAdministrators',
92
        'getChatMember',
93
        'getChatMembersCount',
94
        'answerCallbackQuery',
95
        'answerInlineQuery',
96
        'editMessageText',
97
        'editMessageCaption',
98
        'editMessageReplyMarkup',
99
        'getWebhookInfo',
100
    ];
101
102
    /**
103
     * Initialize
104
     *
105
     * @param \Longman\TelegramBot\Telegram $telegram
106
     *
107
     * @throws TelegramException
108
     */
109 30
    public static function initialize(Telegram $telegram)
110
    {
111 30
        if (!($telegram instanceof Telegram)) {
112
            throw new TelegramException('Invalid Telegram pointer!');
113
        }
114
115 30
        self::$telegram = $telegram;
116 30
        self::setClient(new Client(['base_uri' => self::$api_base_uri]));
117 30
    }
118
119
    /**
120
     * Set a custom Guzzle HTTP Client object
121
     *
122
     * @param Client $client
123
     *
124
     * @throws TelegramException
125
     */
126 30
    public static function setClient(Client $client)
127
    {
128 30
        if (!($client instanceof Client)) {
129
            throw new TelegramException('Invalid GuzzleHttp\Client pointer!');
130
        }
131
132 30
        self::$client = $client;
133 30
    }
134
135
    /**
136
     * Set input from custom input or stdin and return it
137
     *
138
     * @return string
139
     * @throws \Longman\TelegramBot\Exception\TelegramException
140
     */
141
    public static function getInput()
142
    {
143
        // First check if a custom input has been set, else get the PHP input.
144
        if (!($input = self::$telegram->getCustomInput())) {
145
            $input = file_get_contents('php://input');
146
        }
147
148
        // Make sure we have a string to work with.
149
        if (is_string($input)) {
150
            self::$input = $input;
151
        } else {
152
            throw new TelegramException('Input must be a string!');
153
        }
154
155
        TelegramLog::update(self::$input);
156
157
        return self::$input;
158
    }
159
160
    /**
161
     * Generate general fake server response
162
     *
163
     * @param array $data Data to add to fake response
164
     *
165
     * @return array Fake response data
166
     */
167 1
    public static function generateGeneralFakeServerResponse(array $data = [])
168
    {
169
        //PARAM BINDED IN PHPUNIT TEST FOR TestServerResponse.php
170
        //Maybe this is not the best possible implementation
171
172
        //No value set in $data ie testing setWebhook
173
        //Provided $data['chat_id'] ie testing sendMessage
174
175 1
        $fake_response = ['ok' => true]; // :)
176
177 1
        if ($data === []) {
178 1
            $fake_response['result'] = true;
179
        }
180
181
        //some data to let iniatilize the class method SendMessage
182 1
        if (isset($data['chat_id'])) {
183 1
            $data['message_id'] = '1234';
184 1
            $data['date']       = '1441378360';
185 1
            $data['from']       = [
186
                'id'         => 123456789,
187
                'first_name' => 'botname',
188
                'username'   => 'namebot',
189
            ];
190 1
            $data['chat']       = ['id' => $data['chat_id']];
191
192 1
            $fake_response['result'] = $data;
193
        }
194
195 1
        return $fake_response;
196
    }
197
198
    /**
199
     * Properly set up the request params
200
     *
201
     * If any item of the array is a resource, reformat it to a multipart request.
202
     * Else, just return the passed data as form params.
203
     *
204
     * @param array $data
205
     *
206
     * @return array
207
     */
208
    private static function setUpRequestParams(array $data)
209
    {
210
        $has_resource = false;
211
        $multipart = [];
212
213
        // Convert any nested arrays into JSON strings.
214
        array_walk($data, function (&$item) {
215
            is_array($item) && $item = json_encode($item);
216
        });
217
218
        //Reformat data array in multipart way if it contains a resource
219
        foreach ($data as $key => $item) {
220
            $has_resource |= (is_resource($item) || $item instanceof \GuzzleHttp\Psr7\Stream);
221
            $multipart[] = ['name' => $key, 'contents' => $item];
222
        }
223
        if ($has_resource) {
224
            return ['multipart' => $multipart];
225
        }
226
227
        return ['form_params' => $data];
228
    }
229
230
    /**
231
     * Execute HTTP Request
232
     *
233
     * @param string $action Action to execute
234
     * @param array  $data   Data to attach to the execution
235
     *
236
     * @return string Result of the HTTP Request
237
     * @throws \Longman\TelegramBot\Exception\TelegramException
238
     */
239
    public static function execute($action, array $data = [])
240
    {
241
        //Fix so that the keyboard markup is a string, not an object
242
        if (isset($data['reply_markup'])) {
243
            $data['reply_markup'] = json_encode($data['reply_markup']);
244
        }
245
246
        $result = null;
247
        $request_params = self::setUpRequestParams($data);
248
        $request_params['debug'] = TelegramLog::getDebugLogTempStream();
249
250
        try {
251
            $response = self::$client->post(
252
                '/bot' . self::$telegram->getApiKey() . '/' . $action,
253
                $request_params
254
            );
255
            $result = (string) $response->getBody();
256
257
            //Logging getUpdates Update
258
            if ($action === 'getUpdates') {
259
                TelegramLog::update($result);
260
            }
261
        } catch (RequestException $e) {
262
            $result = ($e->getResponse()) ? (string) $e->getResponse()->getBody() : '';
263
        } finally {
264
            //Logging verbose debug output
265
            TelegramLog::endDebugLogTempStream('Verbose HTTP Request output:' . PHP_EOL . '%s' . PHP_EOL);
266
        }
267
268
        return $result;
269
    }
270
271
    /**
272
     * Download file
273
     *
274
     * @param \Longman\TelegramBot\Entities\File $file
275
     *
276
     * @return boolean
277
     * @throws \Longman\TelegramBot\Exception\TelegramException
278
     */
279
    public static function downloadFile(File $file)
280
    {
281
        $tg_file_path = $file->getFilePath();
282
        $file_path    = self::$telegram->getDownloadPath() . '/' . $tg_file_path;
283
284
        $file_dir = dirname($file_path);
285
        //For safety reasons, first try to create the directory, then check that it exists.
286
        //This is in case some other process has created the folder in the meantime.
287
        if (!@mkdir($file_dir, 0755, true) && !is_dir($file_dir)) {
288
            throw new TelegramException('Directory ' . $file_dir . ' can\'t be created');
289
        }
290
291
        $debug_handle = TelegramLog::getDebugLogTempStream();
292
293
        try {
294
            self::$client->get(
295
                '/file/bot' . self::$telegram->getApiKey() . '/' . $tg_file_path,
296
                ['debug' => $debug_handle, 'sink' => $file_path]
297
            );
298
299
            return filesize($file_path) > 0;
300
        } catch (RequestException $e) {
301
            return ($e->getResponse()) ? (string) $e->getResponse()->getBody() : '';
302
        } finally {
303
            //Logging verbose debug output
304
            TelegramLog::endDebugLogTempStream('Verbose HTTP File Download Request output:' . PHP_EOL . '%s' . PHP_EOL);
305
        }
306
    }
307
308
    /**
309
     * Encode file
310
     *
311
     * @param string $file
312
     *
313
     * @return resource
314
     * @throws \Longman\TelegramBot\Exception\TelegramException
315
     */
316
    protected static function encodeFile($file)
317
    {
318
        $fp = fopen($file, 'r');
319
        if ($fp === false) {
320
            throw new TelegramException('Cannot open "' . $file . '" for reading');
321
        }
322
323
        return $fp;
324
    }
325
326
    /**
327
     * Send command
328
     *
329
     * @todo Fake response doesn't need json encoding?
330
     *
331
     * @param string $action
332
     * @param array  $data
333
     *
334
     * @return \Longman\TelegramBot\Entities\ServerResponse
335
     * @throws \Longman\TelegramBot\Exception\TelegramException
336
     */
337
    public static function send($action, array $data = [])
338
    {
339
        self::ensureValidAction($action);
340
341
        $bot_username = self::$telegram->getBotUsername();
342
343
        if (defined('PHPUNIT_TESTSUITE')) {
344
            $fake_response = self::generateGeneralFakeServerResponse($data);
345
346
            return new ServerResponse($fake_response, $bot_username);
347
        }
348
349
        self::ensureNonEmptyData($data);
350
351
        self::limitTelegramRequests($action, $data);
352
353
        $response = json_decode(self::execute($action, $data), true);
354
355
        if (null === $response) {
356
            throw new TelegramException('Telegram returned an invalid response! Please review your bot name and API key.');
357
        }
358
359
        return new ServerResponse($response, $bot_username);
360
    }
361
362
    /**
363
     * Make sure the data isn't empty, else throw an exception
364
     *
365
     * @param array $data
366
     *
367
     * @throws \Longman\TelegramBot\Exception\TelegramException
368
     */
369
    private static function ensureNonEmptyData(array $data)
370
    {
371
        if (count($data) === 0) {
372
            throw new TelegramException('Data is empty!');
373
        }
374
    }
375
376
    /**
377
     * Make sure the action is valid, else throw an exception
378
     *
379
     * @param string $action
380
     *
381
     * @throws \Longman\TelegramBot\Exception\TelegramException
382
     */
383
    private static function ensureValidAction($action)
384
    {
385
        if (!in_array($action, self::$actions, true)) {
386
            throw new TelegramException('The action "' . $action . '" doesn\'t exist!');
387
        }
388
    }
389
390
    /**
391
     * Assign an encoded file to a data array
392
     *
393
     * @param array  $data
394
     * @param string $field
395
     * @param string $file
396
     *
397
     * @throws \Longman\TelegramBot\Exception\TelegramException
398
     */
399
    private static function assignEncodedFile(&$data, $field, $file)
400
    {
401
        if ($file !== null && $file !== '') {
402
            $data[$field] = self::encodeFile($file);
403
        }
404
    }
405
406
    /**
407
     * Returns basic information about the bot in form of a User object
408
     *
409
     * @link https://core.telegram.org/bots/api#getme
410
     *
411
     * @return \Longman\TelegramBot\Entities\ServerResponse
412
     * @throws \Longman\TelegramBot\Exception\TelegramException
413
     */
414
    public static function getMe()
415
    {
416
        // Added fake parameter, because of some cURL version failed POST request without parameters
417
        // see https://github.com/php-telegram-bot/core/pull/228
418
        return self::send('getMe', ['whoami']);
419
    }
420
421
    /**
422
     * Use this method to send text messages. On success, the sent Message is returned
423
     *
424
     * @link https://core.telegram.org/bots/api#sendmessage
425
     *
426
     * @param array $data
427
     *
428
     * @return \Longman\TelegramBot\Entities\ServerResponse
429
     * @throws \Longman\TelegramBot\Exception\TelegramException
430
     */
431
    public static function sendMessage(array $data)
432
    {
433
        $text = $data['text'];
434
435
        do {
436
            //Chop off and send the first message
437
            $data['text'] = mb_substr($text, 0, 4096);
438
            $response     = self::send('sendMessage', $data);
439
440
            //Prepare the next message
441
            $text = mb_substr($text, 4096);
442
        } while (mb_strlen($text, 'UTF-8') > 0);
443
444
        return $response;
445
    }
446
447
    /**
448
     * Use this method to forward messages of any kind. On success, the sent Message is returned
449
     *
450
     * @link https://core.telegram.org/bots/api#forwardmessage
451
     *
452
     * @param array $data
453
     *
454
     * @return \Longman\TelegramBot\Entities\ServerResponse
455
     * @throws \Longman\TelegramBot\Exception\TelegramException
456
     */
457
    public static function forwardMessage(array $data)
458
    {
459
        return self::send('forwardMessage', $data);
460
    }
461
462
    /**
463
     * Use this method to send photos. On success, the sent Message is returned
464
     *
465
     * @link https://core.telegram.org/bots/api#sendphoto
466
     *
467
     * @param array  $data
468
     * @param string $file
469
     *
470
     * @return \Longman\TelegramBot\Entities\ServerResponse
471
     * @throws \Longman\TelegramBot\Exception\TelegramException
472
     */
473
    public static function sendPhoto(array $data, $file = null)
474
    {
475
        self::assignEncodedFile($data, 'photo', $file);
476
477
        return self::send('sendPhoto', $data);
478
    }
479
480
    /**
481
     * Use this method to send audio files
482
     *
483
     * Your audio must be in the .mp3 format. On success, the sent Message is returned.
484
     * Bots can currently send audio files of up to 50 MB in size, this limit may be changed in the future.
485
     * For sending voice messages, use the sendVoice method instead.
486
     *
487
     * @link https://core.telegram.org/bots/api#sendaudio
488
     *
489
     * @param array  $data
490
     * @param string $file
491
     *
492
     * @return \Longman\TelegramBot\Entities\ServerResponse
493
     * @throws \Longman\TelegramBot\Exception\TelegramException
494
     */
495
    public static function sendAudio(array $data, $file = null)
496
    {
497
        self::assignEncodedFile($data, 'audio', $file);
498
499
        return self::send('sendAudio', $data);
500
    }
501
502
    /**
503
     * Use this method to send general files. On success, the sent Message is returned.
504
     *
505
     * Bots can currently send files of any type of up to 50 MB in size, this limit may be changed in the future.
506
     *
507
     * @link https://core.telegram.org/bots/api#senddocument
508
     *
509
     * @param array  $data
510
     * @param string $file
511
     *
512
     * @return \Longman\TelegramBot\Entities\ServerResponse
513
     * @throws \Longman\TelegramBot\Exception\TelegramException
514
     */
515
    public static function sendDocument(array $data, $file = null)
516
    {
517
        self::assignEncodedFile($data, 'document', $file);
518
519
        return self::send('sendDocument', $data);
520
    }
521
522
    /**
523
     * Use this method to send .webp stickers. On success, the sent Message is returned.
524
     *
525
     * @link https://core.telegram.org/bots/api#sendsticker
526
     *
527
     * @param array  $data
528
     * @param string $file
529
     *
530
     * @return \Longman\TelegramBot\Entities\ServerResponse
531
     * @throws \Longman\TelegramBot\Exception\TelegramException
532
     */
533
    public static function sendSticker(array $data, $file = null)
534
    {
535
        self::assignEncodedFile($data, 'sticker', $file);
536
537
        return self::send('sendSticker', $data);
538
    }
539
540
    /**
541
     * Use this method to send video files. On success, the sent Message is returned.
542
     *
543
     * Telegram clients support mp4 videos (other formats may be sent as Document).
544
     * Bots can currently send video files of up to 50 MB in size, this limit may be changed in the future.
545
     *
546
     * @link https://core.telegram.org/bots/api#sendvideo
547
     *
548
     * @param array  $data
549
     * @param string $file
550
     *
551
     * @return \Longman\TelegramBot\Entities\ServerResponse
552
     * @throws \Longman\TelegramBot\Exception\TelegramException
553
     */
554
    public static function sendVideo(array $data, $file = null)
555
    {
556
        self::assignEncodedFile($data, 'video', $file);
557
558
        return self::send('sendVideo', $data);
559
    }
560
561
    /**
562
     * Use this method to send audio files. On success, the sent Message is returned.
563
     *
564
     * Telegram clients will display the file as a playable voice message.
565
     * For this to work, your audio must be in an .ogg file encoded with OPUS (other formats may be sent as Audio or Document).
566
     * Bots can currently send voice messages of up to 50 MB in size, this limit may be changed in the future.
567
     *
568
     * @link https://core.telegram.org/bots/api#sendvoice
569
     *
570
     * @param array  $data
571
     * @param string $file
572
     *
573
     * @return \Longman\TelegramBot\Entities\ServerResponse
574
     * @throws \Longman\TelegramBot\Exception\TelegramException
575
     */
576
    public static function sendVoice(array $data, $file = null)
577
    {
578
        self::assignEncodedFile($data, 'voice', $file);
579
580
        return self::send('sendVoice', $data);
581
    }
582
583
    /**
584
     * Use this method to send point on the map. On success, the sent Message is returned.
585
     *
586
     * @link https://core.telegram.org/bots/api#sendlocation
587
     *
588
     * @param array $data
589
     *
590
     * @return \Longman\TelegramBot\Entities\ServerResponse
591
     * @throws \Longman\TelegramBot\Exception\TelegramException
592
     */
593
    public static function sendLocation(array $data)
594
    {
595
        return self::send('sendLocation', $data);
596
    }
597
598
    /**
599
     * Use this method to send information about a venue. On success, the sent Message is returned.
600
     *
601
     * @link https://core.telegram.org/bots/api#sendvenue
602
     *
603
     * @param array $data
604
     *
605
     * @return \Longman\TelegramBot\Entities\ServerResponse
606
     * @throws \Longman\TelegramBot\Exception\TelegramException
607
     */
608
    public static function sendVenue(array $data)
609
    {
610
        return self::send('sendVenue', $data);
611
    }
612
613
    /**
614
     * Use this method to send phone contacts. On success, the sent Message is returned.
615
     *
616
     * @link https://core.telegram.org/bots/api#sendcontact
617
     *
618
     * @param array $data
619
     *
620
     * @return \Longman\TelegramBot\Entities\ServerResponse
621
     * @throws \Longman\TelegramBot\Exception\TelegramException
622
     */
623
    public static function sendContact(array $data)
624
    {
625
        return self::send('sendContact', $data);
626
    }
627
628
    /**
629
     * Use this method when you need to tell the user that something is happening on the bot's side.
630
     *
631
     * The status is set for 5 seconds or less.
632
     * (when a message arrives from your bot, Telegram clients clear its typing status)
633
     *
634
     * @link https://core.telegram.org/bots/api#sendchataction
635
     *
636
     * @param array $data
637
     *
638
     * @return \Longman\TelegramBot\Entities\ServerResponse
639
     * @throws \Longman\TelegramBot\Exception\TelegramException
640
     */
641
    public static function sendChatAction(array $data)
642
    {
643
        return self::send('sendChatAction', $data);
644
    }
645
646
    /**
647
     * Use this method to get a list of profile pictures for a user. Returns a UserProfilePhotos object.
648
     *
649
     * @param array $data
650
     *
651
     * @return \Longman\TelegramBot\Entities\ServerResponse
652
     * @throws \Longman\TelegramBot\Exception\TelegramException
653
     */
654
    public static function getUserProfilePhotos(array $data)
655
    {
656
        return self::send('getUserProfilePhotos', $data);
657
    }
658
659
    /**
660
     * Use this method to get basic info about a file and prepare it for downloading. On success, a File object is returned.
661
     *
662
     * For the moment, bots can download files of up to 20MB in size.
663
     * The file can then be downloaded via the link https://api.telegram.org/file/bot<token>/<file_path>,
664
     * where <file_path> is taken from the response.
665
     * It is guaranteed that the link will be valid for at least 1 hour.
666
     * When the link expires, a new one can be requested by calling getFile again.
667
     *
668
     * @link https://core.telegram.org/bots/api#getfile
669
     *
670
     * @param array $data
671
     *
672
     * @return \Longman\TelegramBot\Entities\ServerResponse
673
     * @throws \Longman\TelegramBot\Exception\TelegramException
674
     */
675
    public static function getFile(array $data)
676
    {
677
        return self::send('getFile', $data);
678
    }
679
680
    /**
681
     * Use this method to kick a user from a group or a supergroup. Returns True on success.
682
     *
683
     * In the case of supergroups, the user will not be able to return to the group on their own using invite links, etc., unless unbanned first.
684
     * The bot must be an administrator in the group for this to work.
685
     *
686
     * @link https://core.telegram.org/bots/api#kickchatmember
687
     *
688
     * @param array $data
689
     *
690
     * @return \Longman\TelegramBot\Entities\ServerResponse
691
     * @throws \Longman\TelegramBot\Exception\TelegramException
692
     */
693
    public static function kickChatMember(array $data)
694
    {
695
        return self::send('kickChatMember', $data);
696
    }
697
698
    /**
699
     * Use this method for your bot to leave a group, supergroup or channel. Returns True on success.
700
     *
701
     * @link https://core.telegram.org/bots/api#leavechat
702
     *
703
     * @param array $data
704
     *
705
     * @return \Longman\TelegramBot\Entities\ServerResponse
706
     * @throws \Longman\TelegramBot\Exception\TelegramException
707
     */
708
    public static function leaveChat(array $data)
709
    {
710
        return self::send('leaveChat', $data);
711
    }
712
713
    /**
714
     * Use this method to unban a previously kicked user in a supergroup. Returns True on success.
715
     *
716
     * The user will not return to the group automatically, but will be able to join via link, etc.
717
     * The bot must be an administrator in the group for this to work.
718
     *
719
     * @link https://core.telegram.org/bots/api#unbanchatmember
720
     *
721
     * @param array $data
722
     *
723
     * @return \Longman\TelegramBot\Entities\ServerResponse
724
     * @throws \Longman\TelegramBot\Exception\TelegramException
725
     */
726
    public static function unbanChatMember(array $data)
727
    {
728
        return self::send('unbanChatMember', $data);
729
    }
730
731
    /**
732
     * Use this method to get up to date information about the chat (current name of the user for one-on-one conversations, current username of a user, group or channel, etc.). Returns a Chat object on success.
733
     *
734
     * @todo add get response in ServerResponse.php?
735
     *
736
     * @link https://core.telegram.org/bots/api#getchat
737
     *
738
     * @param array $data
739
     *
740
     * @return \Longman\TelegramBot\Entities\ServerResponse
741
     * @throws \Longman\TelegramBot\Exception\TelegramException
742
     */
743
    public static function getChat(array $data)
744
    {
745
        return self::send('getChat', $data);
746
    }
747
748
    /**
749
     * Use this method to get a list of administrators in a chat.
750
     *
751
     * On success, returns an Array of ChatMember objects that contains information about all chat administrators except other bots.
752
     * If the chat is a group or a supergroup and no administrators were appointed, only the creator will be returned.
753
     *
754
     * @todo add get response in ServerResponse.php?
755
     *
756
     * @link https://core.telegram.org/bots/api#getchatadministrators
757
     *
758
     * @param array $data
759
     *
760
     * @return \Longman\TelegramBot\Entities\ServerResponse
761
     * @throws \Longman\TelegramBot\Exception\TelegramException
762
     */
763
    public static function getChatAdministrators(array $data)
764
    {
765
        return self::send('getChatAdministrators', $data);
766
    }
767
768
    /**
769
     * Use this method to get the number of members in a chat. Returns Int on success.
770
     *
771
     * @todo add get response in ServerResponse.php?
772
     *
773
     * @link https://core.telegram.org/bots/api#getchatmemberscount
774
     *
775
     * @param array $data
776
     *
777
     * @return \Longman\TelegramBot\Entities\ServerResponse
778
     * @throws \Longman\TelegramBot\Exception\TelegramException
779
     */
780
    public static function getChatMembersCount(array $data)
781
    {
782
        return self::send('getChatMembersCount', $data);
783
    }
784
785
    /**
786
     * Use this method to get information about a member of a chat. Returns a ChatMember object on success.
787
     *
788
     * @todo add get response in ServerResponse.php?
789
     *
790
     * @link https://core.telegram.org/bots/api#getchatmember
791
     *
792
     * @param array $data
793
     *
794
     * @return \Longman\TelegramBot\Entities\ServerResponse
795
     * @throws \Longman\TelegramBot\Exception\TelegramException
796
     */
797
    public static function getChatMember(array $data)
798
    {
799
        return self::send('getChatMember', $data);
800
    }
801
802
    /**
803
     * Use this method to send answers to callback queries sent from inline keyboards. On success, True is returned.
804
     *
805
     * The answer will be displayed to the user as a notification at the top of the chat screen or as an alert.
806
     *
807
     * @link https://core.telegram.org/bots/api#answercallbackquery
808
     *
809
     * @param array $data
810
     *
811
     * @return \Longman\TelegramBot\Entities\ServerResponse
812
     * @throws \Longman\TelegramBot\Exception\TelegramException
813
     */
814
    public static function answerCallbackQuery(array $data)
815
    {
816
        return self::send('answerCallbackQuery', $data);
817
    }
818
819
    /**
820
     * Get updates
821
     *
822
     * @link https://core.telegram.org/bots/api#getupdates
823
     *
824
     * @param array $data
825
     *
826
     * @return \Longman\TelegramBot\Entities\ServerResponse
827
     * @throws \Longman\TelegramBot\Exception\TelegramException
828
     */
829
    public static function getUpdates(array $data)
830
    {
831
        return self::send('getUpdates', $data);
832
    }
833
834
    /**
835
     * Set webhook
836
     *
837
     * @link https://core.telegram.org/bots/api#setwebhook
838
     *
839
     * @param string $url
840
     * @param array  $data Optional parameters.
841
     *
842
     * @return \Longman\TelegramBot\Entities\ServerResponse
843
     * @throws \Longman\TelegramBot\Exception\TelegramException
844
     */
845
    public static function setWebhook($url = '', array $data = [])
846
    {
847
        $data        = array_intersect_key($data, array_flip([
848
            'certificate',
849
            'max_connections',
850
            'allowed_updates',
851
        ]));
852
        $data['url'] = $url;
853
854
        if (isset($data['certificate'])) {
855
            self::assignEncodedFile($data, 'certificate', $data['certificate']);
856
        }
857
858
        return self::send('setWebhook', $data);
859
    }
860
861
    /**
862
     * Delete webhook
863
     *
864
     * @link https://core.telegram.org/bots/api#deletewebhook
865
     *
866
     * @return \Longman\TelegramBot\Entities\ServerResponse
867
     * @throws \Longman\TelegramBot\Exception\TelegramException
868
     */
869
    public static function deleteWebhook()
870
    {
871
        // Must send some arbitrary data for this to work for now...
872
        return self::send('deleteWebhook', ['delete']);
873
    }
874
875
    /**
876
     * Use this method to edit text and game messages sent by the bot or via the bot (for inline bots).
877
     *
878
     * On success, if edited message is sent by the bot, the edited Message is returned, otherwise True is returned.
879
     *
880
     * @link https://core.telegram.org/bots/api#editmessagetext
881
     *
882
     * @param array $data
883
     *
884
     * @return \Longman\TelegramBot\Entities\ServerResponse
885
     * @throws \Longman\TelegramBot\Exception\TelegramException
886
     */
887
    public static function editMessageText(array $data)
888
    {
889
        return self::send('editMessageText', $data);
890
    }
891
892
    /**
893
     * Use this method to edit captions of messages sent by the bot or via the bot (for inline bots).
894
     *
895
     * On success, if edited message is sent by the bot, the edited Message is returned, otherwise True is returned.
896
     *
897
     * @link https://core.telegram.org/bots/api#editmessagecaption
898
     *
899
     * @param array $data
900
     *
901
     * @return \Longman\TelegramBot\Entities\ServerResponse
902
     * @throws \Longman\TelegramBot\Exception\TelegramException
903
     */
904
    public static function editMessageCaption(array $data)
905
    {
906
        return self::send('editMessageCaption', $data);
907
    }
908
909
    /**
910
     * Use this method to edit only the reply markup of messages sent by the bot or via the bot (for inline bots).
911
     *
912
     * On success, if edited message is sent by the bot, the edited Message is returned, otherwise True is returned.
913
     *
914
     * @link https://core.telegram.org/bots/api#editmessagereplymarkup
915
     *
916
     * @param array $data
917
     *
918
     * @return \Longman\TelegramBot\Entities\ServerResponse
919
     * @throws \Longman\TelegramBot\Exception\TelegramException
920
     */
921
    public static function editMessageReplyMarkup(array $data)
922
    {
923
        return self::send('editMessageReplyMarkup', $data);
924
    }
925
926
    /**
927
     * Use this method to send answers to an inline query. On success, True is returned.
928
     *
929
     * No more than 50 results per query are allowed.
930
     *
931
     * @link https://core.telegram.org/bots/api#answerinlinequery
932
     *
933
     * @param array $data
934
     *
935
     * @return \Longman\TelegramBot\Entities\ServerResponse
936
     * @throws \Longman\TelegramBot\Exception\TelegramException
937
     */
938
    public static function answerInlineQuery(array $data)
939
    {
940
        return self::send('answerInlineQuery', $data);
941
    }
942
943
    /**
944
     * Return an empty Server Response
945
     *
946
     * No request to telegram are sent, this function is used in commands that
947
     * don't need to fire a message after execution
948
     *
949
     * @return \Longman\TelegramBot\Entities\ServerResponse
950
     * @throws \Longman\TelegramBot\Exception\TelegramException
951
     */
952
    public static function emptyResponse()
953
    {
954
        return new ServerResponse(['ok' => true, 'result' => true], null);
955
    }
956
957
    /**
958
     * Send message to all active chats
959
     *
960
     * @param string  $callback_function
961
     * @param array   $data
962
     * @param boolean $send_groups
963
     * @param boolean $send_super_groups
964
     * @param boolean $send_users
965
     * @param string  $date_from
966
     * @param string  $date_to
967
     *
968
     * @return array
969
     * @throws \Longman\TelegramBot\Exception\TelegramException
970
     */
971
    public static function sendToActiveChats(
972
        $callback_function,
973
        array $data,
974
        $send_groups = true,
975
        $send_super_groups = true,
976
        $send_users = true,
977
        $date_from = null,
978
        $date_to = null
979
    ) {
980
        $callback_path = __NAMESPACE__ . '\Request';
981
        if (!method_exists($callback_path, $callback_function)) {
982
            throw new TelegramException('Method "' . $callback_function . '" not found in class Request.');
983
        }
984
985
        $chats = DB::selectChats($send_groups, $send_super_groups, $send_users, $date_from, $date_to);
986
987
        $results = [];
988
        if (is_array($chats)) {
989
            foreach ($chats as $row) {
990
                $data['chat_id'] = $row['chat_id'];
991
                $results[]       = call_user_func_array($callback_path . '::' . $callback_function, [$data]);
992
            }
993
        }
994
995
        return $results;
996
    }
997
998
    /**
999
     * Use this method to get current webhook status.
1000
     *
1001
     * @link https://core.telegram.org/bots/api#getwebhookinfo
1002
     *
1003
     * @return Entities\ServerResponse
1004
     * @throws \Longman\TelegramBot\Exception\TelegramException
1005
     */
1006
    public static function getWebhookInfo()
1007
    {
1008
        // Must send some arbitrary data for this to work for now...
1009
        return self::send('getWebhookInfo', ['info']);
1010
    }
1011
1012
    /**
1013
     * Enable request limiter
1014
     *
1015
     * @param boolean $value
1016
     * @param array   $options
1017
     *
1018
     * @throws \Longman\TelegramBot\Exception\TelegramException
1019
     */
1020
    public static function setLimiter($value = true, array $options = [])
1021
    {
1022
        if (DB::isDbConnected()) {
1023
            $options_default = [
1024
                'interval' => 1,
1025
            ];
1026
1027
            $options = array_merge($options_default, $options);
1028
1029
            if (!is_numeric($options['interval']) || $options['interval'] <= 0) {
1030
                throw new TelegramException('Interval must be a number and must be greater than zero!');
1031
            }
1032
1033
            self::$limiter_interval = $options['interval'];
0 ignored issues
show
Documentation Bug introduced by
It seems like $options['interval'] of type integer or double or string is incompatible with the declared type boolean of property $limiter_interval.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
1034
            self::$limiter_enabled = $value;
1035
        }
1036
    }
1037
1038
    /**
1039
     * This functions delays API requests to prevent reaching Telegram API limits
1040
     *  Can be disabled while in execution by 'Request::setLimiter(false)'
1041
     *
1042
     * @link https://core.telegram.org/bots/faq#my-bot-is-hitting-limits-how-do-i-avoid-this
1043
     *
1044
     * @param string $action
1045
     * @param array  $data
1046
     *
1047
     * @throws \Longman\TelegramBot\Exception\TelegramException
1048
     */
1049
    private static function limitTelegramRequests($action, array $data = [])
1050
    {
1051
        if (self::$limiter_enabled) {
1052
            $limited_methods = [
1053
                'sendMessage',
1054
                'forwardMessage',
1055
                'sendPhoto',
1056
                'sendAudio',
1057
                'sendDocument',
1058
                'sendSticker',
1059
                'sendVideo',
1060
                'sendVoice',
1061
                'sendLocation',
1062
                'sendVenue',
1063
                'sendContact',
1064
                'editMessageText',
1065
                'editMessageCaption',
1066
                'editMessageReplyMarkup',
1067
            ];
1068
1069
            $chat_id = isset($data['chat_id']) ? $data['chat_id'] : null;
1070
            $inline_message_id = isset($data['inline_message_id']) ? $data['inline_message_id'] : null;
1071
1072
            if (($chat_id || $inline_message_id) && in_array($action, $limited_methods)) {
1073
                $timeout = 60;
1074
1075
                while (true) {
1076
                    if ($timeout <= 0) {
1077
                        throw new TelegramException('Timed out while waiting for a request spot!');
1078
                    }
1079
1080
                    $requests = DB::getTelegramRequestCount($chat_id, $inline_message_id);
1081
1082
                    if ($requests['LIMIT_PER_SEC'] == 0     // No more than one message per second inside a particular chat
1083
                        && ((($chat_id > 0 || $inline_message_id) && $requests['LIMIT_PER_SEC_ALL'] < 30)       // No more than 30 messages per second globally
1084
                        || ($chat_id < 0 && $requests['LIMIT_PER_MINUTE'] < 20))        // No more than 20 messages per minute in groups and channels
1085
                    ) {
1086
                        break;
1087
                    }
1088
1089
                    $timeout--;
1090
                    usleep(self::$limiter_interval * 1000000);
1091
                }
1092
1093
                DB::insertTelegramRequest($action, $data);
1094
            }
1095
        }
1096
    }
1097
}
1098