Completed
Push — master ( 1c54e2...48ad84 )
by Armando
02:22
created

Request::deleteWebhook()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

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