Completed
Push — api_3.0_basic_changes ( 9bd403 )
by Armando
03:05
created

Request::sendToActiveChats()   B

Complexity

Conditions 4
Paths 3

Size

Total Lines 26
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

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