Completed
Push — master ( 6d1075...fae82d )
by Armando
20:31 queued 14:28
created

Request   C

Complexity

Total Complexity 66

Size/Duplication

Total Lines 606
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 9

Test Coverage

Coverage 12.74%

Importance

Changes 0
Metric Value
wmc 66
lcom 1
cbo 9
dl 0
loc 606
ccs 20
cts 157
cp 0.1274
rs 5.7089
c 0
b 0
f 0

18 Methods

Rating   Name   Duplication   Size   Complexity  
A initialize() 0 9 2
A setClient() 0 8 2
A getInput() 0 18 3
B generateGeneralFakeServerResponse() 0 30 3
B setUpRequestParams() 0 21 5
B execute() 0 31 5
B downloadFile() 0 32 6
A encodeFile() 0 9 2
B send() 0 25 3
A addDummyParamIfNecessary() 0 7 2
A ensureNonEmptyData() 0 6 2
A ensureValidAction() 0 6 2
A sendMessage() 0 15 2
A __callStatic() 0 7 1
A emptyResponse() 0 4 1
B sendToActiveChats() 0 22 4
A setLimiter() 0 17 4
C limitTelegramRequests() 0 52 17

How to fix   Complexity   

Complex Class

Complex classes like Request often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Request, and based on these observations, apply Extract Interface, too.

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
/**
20
 * Class Request
21
 *
22
 * @method static ServerResponse getUpdates(array $data)             Use this method to receive incoming updates using long polling (wiki). An Array of Update objects is returned.
23
 * @method static ServerResponse setWebhook(array $data)             Use this method to specify a url and receive incoming updates via an outgoing webhook. Whenever there is an update for the bot, we will send an HTTPS POST request to the specified url, containing a JSON-serialized Update. In case of an unsuccessful request, we will give up after a reasonable amount of attempts. Returns true.
24
 * @method static ServerResponse deleteWebhook()                     Use this method to remove webhook integration if you decide to switch back to getUpdates. Returns True on success. Requires no parameters.
25
 * @method static ServerResponse getWebhookInfo()                    Use this method to get current webhook status. Requires no parameters. On success, returns a WebhookInfo object. If the bot is using getUpdates, will return an object with the url field empty.
26
 * @method static ServerResponse getMe()                             A simple method for testing your bot's auth token. Requires no parameters. Returns basic information about the bot in form of a User object.
27
 * @method static ServerResponse forwardMessage(array $data)         Use this method to forward messages of any kind. On success, the sent Message is returned.
28
 * @method static ServerResponse sendPhoto(array $data)              Use this method to send photos. On success, the sent Message is returned.
29
 * @method static ServerResponse sendAudio(array $data)              Use this method to send audio files, if you want Telegram clients to display them in the music player. Your audio must be in the .mp3 format. On success, the sent Message is returned. Bots can currently send audio files of up to 50 MB in size, this limit may be changed in the future.
30
 * @method static ServerResponse sendDocument(array $data)           Use this method to send general files. On success, the sent Message is returned. Bots can currently send files of any type of up to 50 MB in size, this limit may be changed in the future.
31
 * @method static ServerResponse sendSticker(array $data)            Use this method to send .webp stickers. On success, the sent Message is returned.
32
 * @method static ServerResponse sendVideo(array $data)              Use this method to send video files, Telegram clients support mp4 videos (other formats may be sent as Document). On success, the sent Message is returned. Bots can currently send video files of up to 50 MB in size, this limit may be changed in the future.
33
 * @method static ServerResponse sendVoice(array $data)              Use this method to send audio files, if you want Telegram clients to display the file as a playable voice message. For this to work, your audio must be in an .ogg file encoded with OPUS (other formats may be sent as Audio or Document). On success, the sent Message is returned. Bots can currently send voice messages of up to 50 MB in size, this limit may be changed in the future.
34
 * @method static ServerResponse sendVideoNote(array $data)          Use this method to send video messages. On success, the sent Message is returned.
35
 * @method static ServerResponse sendLocation(array $data)           Use this method to send point on the map. On success, the sent Message is returned.
36
 * @method static ServerResponse sendVenue(array $data)              Use this method to send information about a venue. On success, the sent Message is returned.
37
 * @method static ServerResponse sendContact(array $data)            Use this method to send phone contacts. On success, the sent Message is returned.
38
 * @method static ServerResponse sendChatAction(array $data)         Use this method when you need to tell the user that something is happening on the bot's side. The status is set for 5 seconds or less (when a message arrives from your bot, Telegram clients clear its typing status). Returns True on success.
39
 * @method static ServerResponse getUserProfilePhotos(array $data)   Use this method to get a list of profile pictures for a user. Returns a UserProfilePhotos object.
40
 * @method static ServerResponse getFile(array $data)                Use this method to get basic info about a file and prepare it for downloading. For the moment, bots can download files of up to 20MB in size. On success, a File object is returned. The file can then be downloaded via the link https://api.telegram.org/file/bot<token>/<file_path>, where <file_path> is taken from the response. It is guaranteed that the link will be valid for at least 1 hour. When the link expires, a new one can be requested by calling getFile again.
41
 * @method static ServerResponse kickChatMember(array $data)         Use this method to kick a user from a group, a supergroup or a channel. In the case of supergroups and channels, the user will not be able to return to the group on their own using invite links, etc., unless unbanned first. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Returns True on success.
42
 * @method static ServerResponse unbanChatMember(array $data)        Use this method to unban a previously kicked user in a supergroup or channel. The user will not return to the group or channel automatically, but will be able to join via link, etc. The bot must be an administrator for this to work. Returns True on success.
43
 * @method static ServerResponse restrictChatMember(array $data)     Use this method to restrict a user in a supergroup. The bot must be an administrator in the supergroup for this to work and must have the appropriate admin rights. Pass True for all boolean parameters to lift restrictions from a user. Returns True on success.
44
 * @method static ServerResponse promoteChatMember(array $data)      Use this method to promote or demote a user in a supergroup or a channel. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Pass False for all boolean parameters to demote a user. Returns True on success.
45
 * @method static ServerResponse exportChatInviteLink(array $data)   Use this method to export an invite link to a supergroup or a channel. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Returns exported invite link as String on success.
46
 * @method static ServerResponse setChatPhoto(array $data)           Use this method to set a new profile photo for the chat. Photos can't be changed for private chats. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Returns True on success.
47
 * @method static ServerResponse deleteChatPhoto(array $data)        Use this method to delete a chat photo. Photos can't be changed for private chats. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Returns True on success.
48
 * @method static ServerResponse setChatTitle(array $data)           Use this method to change the title of a chat. Titles can't be changed for private chats. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Returns True on success.
49
 * @method static ServerResponse setChatDescription(array $data)     Use this method to change the description of a supergroup or a channel. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Returns True on success.
50
 * @method static ServerResponse pinChatMessage(array $data)         Use this method to pin a message in a supergroup. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Returns True on success.
51
 * @method static ServerResponse unpinChatMessage(array $data)       Use this method to unpin a message in a supergroup chat. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Returns True on success.
52
 * @method static ServerResponse leaveChat(array $data)              Use this method for your bot to leave a group, supergroup or channel. Returns True on success.
53
 * @method static ServerResponse getChat(array $data)                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.
54
 * @method static ServerResponse getChatAdministrators(array $data)  Use this method to get a list of administrators in a chat. On success, returns an Array of ChatMember objects that contains information about all chat administrators except other bots. If the chat is a group or a supergroup and no administrators were appointed, only the creator will be returned.
55
 * @method static ServerResponse getChatMembersCount(array $data)    Use this method to get the number of members in a chat. Returns Int on success.
56
 * @method static ServerResponse getChatMember(array $data)          Use this method to get information about a member of a chat. Returns a ChatMember object on success.
57
 * @method static ServerResponse answerCallbackQuery(array $data)    Use this method to send answers to callback queries sent from inline keyboards. The answer will be displayed to the user as a notification at the top of the chat screen or as an alert. On success, True is returned.
58
 * @method static ServerResponse answerInlineQuery(array $data)      Use this method to send answers to an inline query. On success, True is returned.
59
 * @method static ServerResponse editMessageText(array $data)        Use this method to edit text and game messages sent by the bot or via the bot (for inline bots). On success, if edited message is sent by the bot, the edited Message is returned, otherwise True is returned.
60
 * @method static ServerResponse editMessageCaption(array $data)     Use this method to edit captions of messages sent by the bot or via the bot (for inline bots). On success, if edited message is sent by the bot, the edited Message is returned, otherwise True is returned.
61
 * @method static ServerResponse editMessageReplyMarkup(array $data) Use this method to edit only the reply markup of messages sent by the bot or via the bot (for inline bots). On success, if edited message is sent by the bot, the edited Message is returned, otherwise True is returned.
62
 * @method static ServerResponse deleteMessage(array $data)          Use this method to delete a message, including service messages, with certain limitations. Returns True on success.
63
 */
64
class Request
65
{
66
    /**
67
     * Telegram object
68
     *
69
     * @var \Longman\TelegramBot\Telegram
70
     */
71
    private static $telegram;
72
73
    /**
74
     * URI of the Telegram API
75
     *
76
     * @var string
77
     */
78
    private static $api_base_uri = 'https://api.telegram.org';
79
80
    /**
81
     * Guzzle Client object
82
     *
83
     * @var \GuzzleHttp\Client
84
     */
85
    private static $client;
86
87
    /**
88
     * Input value of the request
89
     *
90
     * @var string
91
     */
92
    private static $input;
93
94
    /**
95
     * Request limiter
96
     *
97
     * @var boolean
98
     */
99
    private static $limiter_enabled;
100
101
    /**
102
     * Request limiter's interval between checks
103
     *
104
     * @var boolean
105
     */
106
    private static $limiter_interval;
107
108
    /**
109
     * Available actions to send
110
     *
111
     * This is basically the list of all methods listed on the official API documentation.
112
     *
113
     * @link https://core.telegram.org/bots/api
114
     *
115
     * @var array
116
     */
117
    private static $actions = [
118
        'getUpdates',
119
        'setWebhook',
120
        'deleteWebhook',
121
        'getWebhookInfo',
122
        'getMe',
123
        'sendMessage',
124
        'forwardMessage',
125
        'sendPhoto',
126
        'sendAudio',
127
        'sendDocument',
128
        'sendSticker',
129
        'sendVideo',
130
        'sendVoice',
131
        'sendVideoNote',
132
        'sendLocation',
133
        'sendVenue',
134
        'sendContact',
135
        'sendChatAction',
136
        'getUserProfilePhotos',
137
        'getFile',
138
        'kickChatMember',
139
        'unbanChatMember',
140
        'restrictChatMember',
141
        'promoteChatMember',
142
        'exportChatInviteLink',
143
        'setChatPhoto',
144
        'deleteChatPhoto',
145
        'setChatTitle',
146
        'setChatDescription',
147
        'pinChatMessage',
148
        'unpinChatMessage',
149
        'leaveChat',
150
        'getChat',
151
        'getChatAdministrators',
152
        'getChatMembersCount',
153
        'getChatMember',
154
        'answerCallbackQuery',
155
        'answerInlineQuery',
156
        'editMessageText',
157
        'editMessageCaption',
158
        'editMessageReplyMarkup',
159
        'deleteMessage',
160
    ];
161
162
    /**
163
     * Some methods need a dummy param due to certain cURL issues.
164
     *
165
     * @see Request::addDummyParamIfNecessary()
166
     *
167
     * @var array
168
     */
169
    private static $actions_need_dummy_param = [
170
        'deleteWebhook',
171
        'getWebhookInfo',
172
        'getMe',
173
    ];
174
175
    /**
176
     * Initialize
177
     *
178
     * @param \Longman\TelegramBot\Telegram $telegram
179
     *
180
     * @throws TelegramException
181
     */
182 30
    public static function initialize(Telegram $telegram)
183
    {
184 30
        if (!($telegram instanceof Telegram)) {
185
            throw new TelegramException('Invalid Telegram pointer!');
186
        }
187
188 30
        self::$telegram = $telegram;
189 30
        self::setClient(new Client(['base_uri' => self::$api_base_uri]));
190 30
    }
191
192
    /**
193
     * Set a custom Guzzle HTTP Client object
194
     *
195
     * @param Client $client
196
     *
197
     * @throws TelegramException
198
     */
199 30
    public static function setClient(Client $client)
200
    {
201 30
        if (!($client instanceof Client)) {
202
            throw new TelegramException('Invalid GuzzleHttp\Client pointer!');
203
        }
204
205 30
        self::$client = $client;
206 30
    }
207
208
    /**
209
     * Set input from custom input or stdin and return it
210
     *
211
     * @return string
212
     * @throws \Longman\TelegramBot\Exception\TelegramException
213
     */
214
    public static function getInput()
215
    {
216
        // First check if a custom input has been set, else get the PHP input.
217
        if (!($input = self::$telegram->getCustomInput())) {
218
            $input = file_get_contents('php://input');
219
        }
220
221
        // Make sure we have a string to work with.
222
        if (!is_string($input)) {
223
            throw new TelegramException('Input must be a string!');
224
        }
225
226
        self::$input = $input;
227
228
        TelegramLog::update(self::$input);
229
230
        return self::$input;
231
    }
232
233
    /**
234
     * Generate general fake server response
235
     *
236
     * @param array $data Data to add to fake response
237
     *
238
     * @return array Fake response data
239
     */
240 1
    public static function generateGeneralFakeServerResponse(array $data = [])
241
    {
242
        //PARAM BINDED IN PHPUNIT TEST FOR TestServerResponse.php
243
        //Maybe this is not the best possible implementation
244
245
        //No value set in $data ie testing setWebhook
246
        //Provided $data['chat_id'] ie testing sendMessage
247
248 1
        $fake_response = ['ok' => true]; // :)
249
250 1
        if ($data === []) {
251 1
            $fake_response['result'] = true;
252
        }
253
254
        //some data to let iniatilize the class method SendMessage
255 1
        if (isset($data['chat_id'])) {
256 1
            $data['message_id'] = '1234';
257 1
            $data['date']       = '1441378360';
258 1
            $data['from']       = [
259
                'id'         => 123456789,
260
                'first_name' => 'botname',
261
                'username'   => 'namebot',
262
            ];
263 1
            $data['chat']       = ['id' => $data['chat_id']];
264
265 1
            $fake_response['result'] = $data;
266
        }
267
268 1
        return $fake_response;
269
    }
270
271
    /**
272
     * Properly set up the request params
273
     *
274
     * If any item of the array is a resource, reformat it to a multipart request.
275
     * Else, just return the passed data as form params.
276
     *
277
     * @param array $data
278
     *
279
     * @return array
280
     */
281
    private static function setUpRequestParams(array $data)
282
    {
283
        $has_resource = false;
284
        $multipart    = [];
285
286
        // Convert any nested arrays into JSON strings.
287
        array_walk($data, function (&$item) {
288
            is_array($item) && $item = json_encode($item);
289
        });
290
291
        //Reformat data array in multipart way if it contains a resource
292
        foreach ($data as $key => $item) {
293
            $has_resource |= (is_resource($item) || $item instanceof \GuzzleHttp\Psr7\Stream);
294
            $multipart[]  = ['name' => $key, 'contents' => $item];
295
        }
296
        if ($has_resource) {
297
            return ['multipart' => $multipart];
298
        }
299
300
        return ['form_params' => $data];
301
    }
302
303
    /**
304
     * Execute HTTP Request
305
     *
306
     * @param string $action Action to execute
307
     * @param array  $data   Data to attach to the execution
308
     *
309
     * @return string Result of the HTTP Request
310
     * @throws \Longman\TelegramBot\Exception\TelegramException
311
     */
312
    public static function execute($action, array $data = [])
313
    {
314
        //Fix so that the keyboard markup is a string, not an object
315
        if (isset($data['reply_markup'])) {
316
            $data['reply_markup'] = json_encode($data['reply_markup']);
317
        }
318
319
        $result                  = null;
320
        $request_params          = self::setUpRequestParams($data);
321
        $request_params['debug'] = TelegramLog::getDebugLogTempStream();
322
323
        try {
324
            $response = self::$client->post(
325
                '/bot' . self::$telegram->getApiKey() . '/' . $action,
326
                $request_params
327
            );
328
            $result   = (string) $response->getBody();
329
330
            //Logging getUpdates Update
331
            if ($action === 'getUpdates') {
332
                TelegramLog::update($result);
333
            }
334
        } catch (RequestException $e) {
335
            $result = ($e->getResponse()) ? (string) $e->getResponse()->getBody() : '';
336
        } finally {
337
            //Logging verbose debug output
338
            TelegramLog::endDebugLogTempStream('Verbose HTTP Request output:' . PHP_EOL . '%s' . PHP_EOL);
339
        }
340
341
        return $result;
342
    }
343
344
    /**
345
     * Download file
346
     *
347
     * @param \Longman\TelegramBot\Entities\File $file
348
     *
349
     * @return boolean
350
     * @throws \Longman\TelegramBot\Exception\TelegramException
351
     */
352
    public static function downloadFile(File $file)
353
    {
354
        if (empty($download_path = self::$telegram->getDownloadPath())) {
355
            throw new TelegramException('Download path not set!');
356
        }
357
358
        $tg_file_path = $file->getFilePath();
359
        $file_path    = $download_path . '/' . $tg_file_path;
360
361
        $file_dir = dirname($file_path);
362
        //For safety reasons, first try to create the directory, then check that it exists.
363
        //This is in case some other process has created the folder in the meantime.
364
        if (!@mkdir($file_dir, 0755, true) && !is_dir($file_dir)) {
365
            throw new TelegramException('Directory ' . $file_dir . ' can\'t be created');
366
        }
367
368
        $debug_handle = TelegramLog::getDebugLogTempStream();
369
370
        try {
371
            self::$client->get(
372
                '/file/bot' . self::$telegram->getApiKey() . '/' . $tg_file_path,
373
                ['debug' => $debug_handle, 'sink' => $file_path]
374
            );
375
376
            return filesize($file_path) > 0;
377
        } catch (RequestException $e) {
378
            return ($e->getResponse()) ? (string) $e->getResponse()->getBody() : '';
379
        } finally {
380
            //Logging verbose debug output
381
            TelegramLog::endDebugLogTempStream('Verbose HTTP File Download Request output:' . PHP_EOL . '%s' . PHP_EOL);
382
        }
383
    }
384
385
    /**
386
     * Encode file
387
     *
388
     * @param string $file
389
     *
390
     * @return resource
391
     * @throws \Longman\TelegramBot\Exception\TelegramException
392
     */
393
    public static function encodeFile($file)
394
    {
395
        $fp = fopen($file, 'rb');
396
        if ($fp === false) {
397
            throw new TelegramException('Cannot open "' . $file . '" for reading');
398
        }
399
400
        return $fp;
401
    }
402
403
    /**
404
     * Send command
405
     *
406
     * @todo Fake response doesn't need json encoding?
407
     * @todo Write debug entry on failure
408
     *
409
     * @param string $action
410
     * @param array  $data
411
     *
412
     * @return \Longman\TelegramBot\Entities\ServerResponse
413
     * @throws \Longman\TelegramBot\Exception\TelegramException
414
     */
415
    public static function send($action, array $data = [])
416
    {
417
        self::ensureValidAction($action);
418
        self::addDummyParamIfNecessary($action, $data);
419
420
        $bot_username = self::$telegram->getBotUsername();
421
422
        if (defined('PHPUNIT_TESTSUITE')) {
423
            $fake_response = self::generateGeneralFakeServerResponse($data);
424
425
            return new ServerResponse($fake_response, $bot_username);
426
        }
427
428
        self::ensureNonEmptyData($data);
429
430
        self::limitTelegramRequests($action, $data);
431
432
        $response = json_decode(self::execute($action, $data), true);
433
434
        if (null === $response) {
435
            throw new TelegramException('Telegram returned an invalid response! Please review your bot name and API key.');
436
        }
437
438
        return new ServerResponse($response, $bot_username);
439
    }
440
441
    /**
442
     * Add a dummy parameter if the passed action requires it.
443
     *
444
     * If a method doesn't require parameters, we need to add a dummy one anyway,
445
     * because of some cURL version failed POST request without parameters.
446
     *
447
     * @link https://github.com/php-telegram-bot/core/pull/228
448
     *
449
     * @todo Would be nice to find a better solution for this!
450
     *
451
     * @param string $action
452
     * @param array  $data
453
     */
454
    protected static function addDummyParamIfNecessary($action, array &$data)
455
    {
456
        if (in_array($action, self::$actions_need_dummy_param, true)) {
457
            // Can be anything, using a single letter to minimise request size.
458
            $data = ['d'];
459
        }
460
    }
461
462
    /**
463
     * Make sure the data isn't empty, else throw an exception
464
     *
465
     * @param array $data
466
     *
467
     * @throws \Longman\TelegramBot\Exception\TelegramException
468
     */
469
    private static function ensureNonEmptyData(array $data)
470
    {
471
        if (count($data) === 0) {
472
            throw new TelegramException('Data is empty!');
473
        }
474
    }
475
476
    /**
477
     * Make sure the action is valid, else throw an exception
478
     *
479
     * @param string $action
480
     *
481
     * @throws \Longman\TelegramBot\Exception\TelegramException
482
     */
483
    private static function ensureValidAction($action)
484
    {
485
        if (!in_array($action, self::$actions, true)) {
486
            throw new TelegramException('The action "' . $action . '" doesn\'t exist!');
487
        }
488
    }
489
490
    /**
491
     * Use this method to send text messages. On success, the sent Message is returned
492
     *
493
     * @link https://core.telegram.org/bots/api#sendmessage
494
     *
495
     * @param array $data
496
     *
497
     * @return \Longman\TelegramBot\Entities\ServerResponse
498
     * @throws \Longman\TelegramBot\Exception\TelegramException
499
     */
500
    public static function sendMessage(array $data)
501
    {
502
        $text = $data['text'];
503
504
        do {
505
            //Chop off and send the first message
506
            $data['text'] = mb_substr($text, 0, 4096);
507
            $response     = self::send('sendMessage', $data);
508
509
            //Prepare the next message
510
            $text = mb_substr($text, 4096);
511
        } while (mb_strlen($text, 'UTF-8') > 0);
512
513
        return $response;
514
    }
515
516
    /**
517
     * Any statically called method should be relayed to the `send` method.
518
     *
519
     * @param string $action
520
     * @param array  $data
521
     *
522
     * @return \Longman\TelegramBot\Entities\ServerResponse
523
     * @throws \Longman\TelegramBot\Exception\TelegramException
524
     */
525
    public static function __callStatic($action, array $data)
526
    {
527
        // Make sure to add the action being called as the first parameter to be passed.
528
        array_unshift($data, $action);
529
530
        return call_user_func_array('static::send', $data);
531
    }
532
533
    /**
534
     * Return an empty Server Response
535
     *
536
     * No request to telegram are sent, this function is used in commands that
537
     * don't need to fire a message after execution
538
     *
539
     * @return \Longman\TelegramBot\Entities\ServerResponse
540
     * @throws \Longman\TelegramBot\Exception\TelegramException
541
     */
542
    public static function emptyResponse()
543
    {
544
        return new ServerResponse(['ok' => true, 'result' => true], null);
545
    }
546
547
    /**
548
     * Send message to all active chats
549
     *
550
     * @param string $callback_function
551
     * @param array  $data
552
     * @param array  $select_chats_params
553
     *
554
     * @return array
555
     * @throws TelegramException
556
     */
557
    public static function sendToActiveChats(
558
        $callback_function,
559
        array $data,
560
        array $select_chats_params
561
    ) {
562
        $callback_path = __NAMESPACE__ . '\Request';
563
        if (!method_exists($callback_path, $callback_function)) {
564
            throw new TelegramException('Method "' . $callback_function . '" not found in class Request.');
565
        }
566
567
        $chats = DB::selectChats($select_chats_params);
568
569
        $results = [];
570
        if (is_array($chats)) {
571
            foreach ($chats as $row) {
572
                $data['chat_id'] = $row['chat_id'];
573
                $results[]       = call_user_func($callback_path . '::' . $callback_function, $data);
574
            }
575
        }
576
577
        return $results;
578
    }
579
580
    /**
581
     * Enable request limiter
582
     *
583
     * @param boolean $value
584
     * @param array   $options
585
     *
586
     * @throws \Longman\TelegramBot\Exception\TelegramException
587
     */
588
    public static function setLimiter($value = true, array $options = [])
589
    {
590
        if (DB::isDbConnected()) {
591
            $options_default = [
592
                'interval' => 1,
593
            ];
594
595
            $options = array_merge($options_default, $options);
596
597
            if (!is_numeric($options['interval']) || $options['interval'] <= 0) {
598
                throw new TelegramException('Interval must be a number and must be greater than zero!');
599
            }
600
601
            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...
602
            self::$limiter_enabled  = $value;
603
        }
604
    }
605
606
    /**
607
     * This functions delays API requests to prevent reaching Telegram API limits
608
     *  Can be disabled while in execution by 'Request::setLimiter(false)'
609
     *
610
     * @link https://core.telegram.org/bots/faq#my-bot-is-hitting-limits-how-do-i-avoid-this
611
     *
612
     * @param string $action
613
     * @param array  $data
614
     *
615
     * @throws \Longman\TelegramBot\Exception\TelegramException
616
     */
617
    private static function limitTelegramRequests($action, array $data = [])
618
    {
619
        if (self::$limiter_enabled) {
620
            $limited_methods = [
621
                'sendMessage',
622
                'forwardMessage',
623
                'sendPhoto',
624
                'sendAudio',
625
                'sendDocument',
626
                'sendSticker',
627
                'sendVideo',
628
                'sendVoice',
629
                'sendVideoNote',
630
                'sendLocation',
631
                'sendVenue',
632
                'sendContact',
633
                'editMessageText',
634
                'editMessageCaption',
635
                'editMessageReplyMarkup',
636
                'setChatTitle',
637
                'setChatDescription',
638
            ];
639
640
            $chat_id           = isset($data['chat_id']) ? $data['chat_id'] : null;
641
            $inline_message_id = isset($data['inline_message_id']) ? $data['inline_message_id'] : null;
642
643
            if (($chat_id || $inline_message_id) && in_array($action, $limited_methods)) {
644
                $timeout = 60;
645
646
                while (true) {
647
                    if ($timeout <= 0) {
648
                        throw new TelegramException('Timed out while waiting for a request spot!');
649
                    }
650
651
                    $requests = DB::getTelegramRequestCount($chat_id, $inline_message_id);
652
653
                    $chat_per_second   = ($requests['LIMIT_PER_SEC'] == 0); // No more than one message per second inside a particular chat
654
                    $global_per_second = ($requests['LIMIT_PER_SEC_ALL'] < 30);    // No more than 30 messages per second to different chats
655
                    $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
656
657
                    if ($chat_per_second && $global_per_second && $groups_per_minute) {
658
                        break;
659
                    }
660
661
                    $timeout--;
662
                    usleep(self::$limiter_interval * 1000000);
663
                }
664
665
                DB::insertTelegramRequest($action, $data);
666
            }
667
        }
668
    }
669
}
670