Completed
Push — master ( e52205...6d1075 )
by Armando
04:05 queued 02:25
created

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