Completed
Push — master ( 19f88b...b81226 )
by Gusev
03:12
created

BotApi::getFileUrl()   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 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 4
ccs 0
cts 2
cp 0
rs 10
cc 1
eloc 2
nc 1
nop 0
crap 2
1
<?php
2
3
namespace TelegramBot\Api;
4
5
use TelegramBot\Api\Types\ArrayOfUpdates;
6
use TelegramBot\Api\Types\File;
7
use TelegramBot\Api\Types\Message;
8
use TelegramBot\Api\Types\Update;
9
use TelegramBot\Api\Types\User;
10
use TelegramBot\Api\Types\UserProfilePhotos;
11
12
/**
13
 * Class BotApi
14
 *
15
 * @package TelegramBot\Api
16
 */
17
class BotApi
18
{
19
    /**
20
     * HTTP codes
21
     *
22
     * @var array
23
     */
24
    public static $codes = [
25
        // Informational 1xx
26
        100 => 'Continue',
27
        101 => 'Switching Protocols',
28
        102 => 'Processing',            // RFC2518
29
        // Success 2xx
30
        200 => 'OK',
31
        201 => 'Created',
32
        202 => 'Accepted',
33
        203 => 'Non-Authoritative Information',
34
        204 => 'No Content',
35
        205 => 'Reset Content',
36
        206 => 'Partial Content',
37
        207 => 'Multi-Status',          // RFC4918
38
        208 => 'Already Reported',      // RFC5842
39
        226 => 'IM Used',               // RFC3229
40
        // Redirection 3xx
41
        300 => 'Multiple Choices',
42
        301 => 'Moved Permanently',
43
        302 => 'Found', // 1.1
44
        303 => 'See Other',
45
        304 => 'Not Modified',
46
        305 => 'Use Proxy',
47
        // 306 is deprecated but reserved
48
        307 => 'Temporary Redirect',
49
        308 => 'Permanent Redirect',    // RFC7238
50
        // Client Error 4xx
51
        400 => 'Bad Request',
52
        401 => 'Unauthorized',
53
        402 => 'Payment Required',
54
        403 => 'Forbidden',
55
        404 => 'Not Found',
56
        405 => 'Method Not Allowed',
57
        406 => 'Not Acceptable',
58
        407 => 'Proxy Authentication Required',
59
        408 => 'Request Timeout',
60
        409 => 'Conflict',
61
        410 => 'Gone',
62
        411 => 'Length Required',
63
        412 => 'Precondition Failed',
64
        413 => 'Payload Too Large',
65
        414 => 'URI Too Long',
66
        415 => 'Unsupported Media Type',
67
        416 => 'Range Not Satisfiable',
68
        417 => 'Expectation Failed',
69
        422 => 'Unprocessable Entity',                                        // RFC4918
70
        423 => 'Locked',                                                      // RFC4918
71
        424 => 'Failed Dependency',                                           // RFC4918
72
        425 => 'Reserved for WebDAV advanced collections expired proposal',   // RFC2817
73
        426 => 'Upgrade Required',                                            // RFC2817
74
        428 => 'Precondition Required',                                       // RFC6585
75
        429 => 'Too Many Requests',                                           // RFC6585
76
        431 => 'Request Header Fields Too Large',                             // RFC6585
77
        // Server Error 5xx
78
        500 => 'Internal Server Error',
79
        501 => 'Not Implemented',
80
        502 => 'Bad Gateway',
81
        503 => 'Service Unavailable',
82
        504 => 'Gateway Timeout',
83
        505 => 'HTTP Version Not Supported',
84
        506 => 'Variant Also Negotiates (Experimental)',                      // RFC2295
85
        507 => 'Insufficient Storage',                                        // RFC4918
86
        508 => 'Loop Detected',                                               // RFC5842
87
        510 => 'Not Extended',                                                // RFC2774
88
        511 => 'Network Authentication Required',                             // RFC6585
89
    ];
90
91
92
    /**
93
     * Default http status code
94
     */
95
    const DEFAULT_STATUS_CODE = 200;
96
97
    /**
98
     * Not Modified http status code
99
     */
100
    const NOT_MODIFIED_STATUS_CODE = 304;
101
102
    /**
103
     * Limits for tracked ids
104
     */
105
    const MAX_TRACKED_EVENTS = 200;
106
107
    /**
108
     * Url prefixes
109
     */
110
    const URL_PREFIX = 'https://api.telegram.org/bot';
111
    const FILE_URL_PREFIX = 'https://api.telegram.org/file/bot';
112
113
    /**
114
     * CURL object
115
     *
116
     * @var
117
     */
118
    protected $curl;
119
120
    /**
121
     * Bot token
122
     *
123
     * @var string
124
     */
125
    protected $token;
126
127
    /**
128
     * Botan tracker
129
     *
130
     * @var \TelegramBot\Api\Botan
131
     */
132
    protected $tracker;
133
134
    /**
135
     * list of event ids
136
     *
137
     * @var array
138
     */
139
    protected $trackedEvents = [];
140
141
    /**
142
     * Check whether return associative array
143
     *
144
     * @var bool
145
     */
146
    protected $returnArray = true;
147
148
149
    /**
150
     * Constructor
151
     *
152
     * @param string $token Telegram Bot API token
153
     * @param string|null $trackerToken Yandex AppMetrica application api_key
154
     */
155 9
    public function __construct($token, $trackerToken = null)
156
    {
157 9
        $this->curl = curl_init();
158 9
        $this->token = $token;
159
160 9
        if ($trackerToken) {
161
            $this->tracker = new Botan($trackerToken);
162
        }
163 9
    }
164
165
    /**
166
     * Set return array
167
     *
168
     * @param bool $mode
169
     *
170
     * @return $this
171
     */
172
    public function setModeObject($mode = true)
173
    {
174
        $this->returnArray = !$mode;
175
176
        return $this;
177
    }
178
179
180
    /**
181
     * Call method
182
     *
183
     * @param string $method
184
     * @param array|null $data
185
     *
186
     * @return mixed
187
     * @throws \TelegramBot\Api\Exception
188
     * @throws \TelegramBot\Api\HttpException
189
     * @throws \TelegramBot\Api\InvalidJsonException
190
     */
191
    public function call($method, array $data = null)
192
    {
193
        $options = [
194
            CURLOPT_URL => $this->getUrl() . '/' . $method,
195
            CURLOPT_RETURNTRANSFER => true,
196
            CURLOPT_POST => null,
197
            CURLOPT_POSTFIELDS => null
198
        ];
199
200
        if ($data) {
201
            $options[CURLOPT_POST] = true;
202
            $options[CURLOPT_POSTFIELDS] = $data;
203
        }
204
205
        $response = self::jsonValidate($this->executeCurl($options), $this->returnArray);
206
207
        if ($this->returnArray) {
208
            if (!isset($response['ok'])) {
209
                throw new Exception($response['description'], $response['error_code']);
210
            }
211
212
            return $response['result'];
213
        }
214
215
        if (!$response->ok) {
216
            throw new Exception($response->description, $response->error_code);
217
        }
218
219
        return $response->result;
220
    }
221
222
    /**
223
     * curl_exec wrapper for response validation
224
     *
225
     * @param array $options
226
     *
227
     * @return string
228
     *
229
     * @throws \TelegramBot\Api\HttpException
230
     */
231
    protected function executeCurl(array $options)
232
    {
233
        curl_setopt_array($this->curl, $options);
234
235
        $result = curl_exec($this->curl);
236
        self::curlValidate($this->curl);
237
238
        return $result;
239
    }
240
241
    /**
242
     * Response validation
243
     *
244
     * @param resource $curl
245
     *
246
     * @throws \TelegramBot\Api\HttpException
247
     */
248
    public static function curlValidate($curl)
249
    {
250
        if (($httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE))
251
            && !in_array($httpCode, [self::DEFAULT_STATUS_CODE, self::NOT_MODIFIED_STATUS_CODE])
252
        ) {
253
            throw new HttpException(self::$codes[$httpCode], $httpCode);
254
        }
255
    }
256
257
    /**
258
     * JSON validation
259
     *
260
     * @param string $jsonString
261
     * @param boolean $asArray
262
     *
263
     * @return object|array
264
     * @throws \TelegramBot\Api\InvalidJsonException
265
     */
266
    public static function jsonValidate($jsonString, $asArray)
267
    {
268
        $json = json_decode($jsonString, $asArray);
269
270
        if (json_last_error() != JSON_ERROR_NONE) {
271
            throw new InvalidJsonException(json_last_error_msg(), json_last_error());
272
        }
273
274
        return $json;
275
    }
276
277
    /**
278
     * Use this method to send text messages. On success, the sent \TelegramBot\Api\Types\Message is returned.
279
     *
280
     * @param int|string $chatId
281
     * @param string $text
282
     * @param string|null $parseMode
283
     * @param bool $disablePreview
284
     * @param int|null $replyToMessageId
285
     * @param Types\ReplyKeyboardMarkup|Types\ReplyKeyboardHide|Types\ForceReply|null $replyMarkup
286
     * @param bool $disableNotification
287
     *
288
     * @return \TelegramBot\Api\Types\Message
289
     * @throws \TelegramBot\Api\InvalidArgumentException
290
     * @throws \TelegramBot\Api\Exception
291
     */
292
    public function sendMessage(
293
        $chatId,
294
        $text,
295
        $parseMode = null,
296
        $disablePreview = false,
297
        $replyToMessageId = null,
298
        $replyMarkup = null,
299
        $disableNotification = false
300
    ) {
301
        return Message::fromResponse($this->call('sendMessage', [
302
            'chat_id' => $chatId,
303
            'text' => $text,
304
            'parse_mode' => $parseMode,
305
            'disable_web_page_preview' => $disablePreview,
306
            'reply_to_message_id' => (int) $replyToMessageId,
307
            'reply_markup' => is_null($replyMarkup) ? $replyMarkup : $replyMarkup->toJson(),
308
            'disable_notification' => (bool) $disableNotification,
309
        ]));
310
    }
311
312
    /**
313
     * Use this method when you need to tell the user that something is happening on the bot's side.
314
     * The status is set for 5 seconds or less (when a message arrives from your bot,
315
     * Telegram clients clear its typing status).
316
     *
317
     * We only recommend using this method when a response from the bot will take a noticeable amount of time to arrive.
318
     *
319
     * Type of action to broadcast. Choose one, depending on what the user is about to receive:
320
     * `typing` for text messages, `upload_photo` for photos, `record_video` or `upload_video` for videos,
321
     * `record_audio` or upload_audio for audio files, `upload_document` for general files,
322
     * `find_location` for location data.
323
     *
324
     * @param int $chatId
325
     * @param string $action
326
     *
327
     * @return bool
328
     * @throws \TelegramBot\Api\Exception
329
     */
330
    public function sendChatAction($chatId, $action)
331
    {
332
        return $this->call('sendChatAction', [
333
            'chat_id' => $chatId,
334
            'action' => $action
335
        ]);
336
    }
337
338
    /**
339
     * Use this method to get a list of profile pictures for a user.
340
     *
341
     * @param int $userId
342
     * @param int $offset
343
     * @param int $limit
344
     *
345
     * @return \TelegramBot\Api\Types\UserProfilePhotos
346
     * @throws \TelegramBot\Api\Exception
347
     */
348
    public function getUserProfilePhotos($userId, $offset = 0, $limit = 100)
349
    {
350
        return UserProfilePhotos::fromResponse($this->call('getUserProfilePhotos', [
351
            'user_id' => (int) $userId,
352
            'offset' => (int) $offset,
353
            'limit' => (int) $limit,
354
        ]));
355
    }
356
357
    /**
358
     * Use this method to specify a url and receive incoming updates via an outgoing webhook.
359
     * Whenever there is an update for the bot, we will send an HTTPS POST request to the specified url,
360
     * containing a JSON-serialized Update.
361
     * In case of an unsuccessful request, we will give up after a reasonable amount of attempts.
362
     *
363
     * @param string $url HTTPS url to send updates to. Use an empty string to remove webhook integration
364
     * @param \CURLFile|string $certificate Upload your public key certificate
365
     *                                      so that the root certificate in use can be checked
366
     *
367
     * @return string
368
     *
369
     * @throws \TelegramBot\Api\Exception
370
     */
371
    public function setWebhook($url = '', $certificate = null)
372
    {
373
        return $this->call('setWebhook', ['url' => $url, 'certificate' => $certificate]);
374
    }
375
376
    /**
377
     * A simple method for testing your bot's auth token.Requires no parameters.
378
     * Returns basic information about the bot in form of a User object.
379
     *
380
     * @return \TelegramBot\Api\Types\User
381
     * @throws \TelegramBot\Api\Exception
382
     * @throws \TelegramBot\Api\InvalidArgumentException
383
     */
384
    public function getMe()
385
    {
386
        return User::fromResponse($this->call('getMe'));
387
    }
388
389
    /**
390
     * Use this method to receive incoming updates using long polling.
391
     * An Array of Update objects is returned.
392
     *
393
     * Notes
394
     * 1. This method will not work if an outgoing webhook is set up.
395
     * 2. In order to avoid getting duplicate updates, recalculate offset after each server response.
396
     *
397
     * @param int $offset
398
     * @param int $limit
399
     * @param int $timeout
400
     *
401
     * @return Update[]
402
     * @throws \TelegramBot\Api\Exception
403
     * @throws \TelegramBot\Api\InvalidArgumentException
404
     */
405 2
    public function getUpdates($offset = 0, $limit = 100, $timeout = 0)
406
    {
407 2
        $updates = ArrayOfUpdates::fromResponse($this->call('getUpdates', [
408 2
            'offset' => $offset,
409 2
            'limit' => $limit,
410
            'timeout' => $timeout
411 2
        ]));
412
413 2
        if ($this->tracker instanceof Botan) {
414
            foreach ($updates as $update) {
415
                $this->trackUpdate($update);
416
            }
417
        }
418
419 2
        return $updates;
420
    }
421
422
    /**
423
     * Use this method to send point on the map. On success, the sent Message is returned.
424
     *
425
     * @param int $chatId
426
     * @param float $latitude
427
     * @param float $longitude
428
     * @param int|null $replyToMessageId
429
     * @param Types\ReplyKeyboardMarkup|Types\ReplyKeyboardHide|Types\ForceReply|null $replyMarkup
430
     * @param bool $disableNotification
431
     *
432
     * @return \TelegramBot\Api\Types\Message
433
     * @throws \TelegramBot\Api\Exception
434
     */
435 View Code Duplication
    public function sendLocation($chatId, $latitude, $longitude, $replyToMessageId = null, $replyMarkup = null, $disableNotification = false)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
436
    {
437
        return Message::fromResponse($this->call('sendLocation', [
438
            'chat_id' => $chatId,
439
            'latitude' => $latitude,
440
            'longitude' => $longitude,
441
            'reply_to_message_id' => $replyToMessageId,
442
            'reply_markup' => is_null($replyMarkup) ? $replyMarkup : $replyMarkup->toJson(),
443
            'disable_notification' => (bool) $disableNotification
444
        ]));
445
    }
446
447
    /**
448
     * Use this method to send .webp stickers. On success, the sent Message is returned.
449
     *
450
     * @param int $chatId
451
     * @param \CURLFile|string $sticker
452
     * @param int|null $replyToMessageId
453
     * @param Types\ReplyKeyboardMarkup|Types\ReplyKeyboardHide|Types\ForceReply|null $replyMarkup
454
     * @param bool $disableNotification
455
     *
456
     * @return \TelegramBot\Api\Types\Message
457
     * @throws \TelegramBot\Api\InvalidArgumentException
458
     * @throws \TelegramBot\Api\Exception
459
     */
460 View Code Duplication
    public function sendSticker($chatId, $sticker, $replyToMessageId = null, $replyMarkup = null, $disableNotification = false)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
461
    {
462
        return Message::fromResponse($this->call('sendSticker', [
463
            'chat_id' => $chatId,
464
            'sticker' => $sticker,
465
            'reply_to_message_id' => $replyToMessageId,
466
            'reply_markup' => is_null($replyMarkup) ? $replyMarkup : $replyMarkup->toJson(),
467
            'disable_notification' => (bool) $disableNotification
468
        ]));
469
    }
470
471
    /**
472
     * Use this method to send video files,
473
     * Telegram clients support mp4 videos (other formats may be sent as Document).
474
     * On success, the sent Message is returned.
475
     *
476
     * @param int $chatId
477
     * @param \CURLFile|string $video
478
     * @param int|null $duration
479
     * @param string|null $caption
480
     * @param int|null $replyToMessageId
481
     * @param Types\ReplyKeyboardMarkup|Types\ReplyKeyboardHide|Types\ForceReply|null $replyMarkup
482
     * @param bool $disableNotification
483
     *
484
     * @return \TelegramBot\Api\Types\Message
485
     * @throws \TelegramBot\Api\InvalidArgumentException
486
     * @throws \TelegramBot\Api\Exception
487
     */
488
    public function sendVideo(
489
        $chatId,
490
        $video,
491
        $duration = null,
492
        $caption = null,
493
        $replyToMessageId = null,
494
        $replyMarkup = null,
495
        $disableNotification = false
496
    ) {
497
        return Message::fromResponse($this->call('sendVideo', [
498
            'chat_id' => $chatId,
499
            'video' => $video,
500
            'duration' => $duration,
501
            'caption' => $caption,
502
            'reply_to_message_id' => $replyToMessageId,
503
            'reply_markup' => is_null($replyMarkup) ? $replyMarkup : $replyMarkup->toJson(),
504
            'disable_notification' => (bool) $disableNotification
505
        ]));
506
    }
507
508
    /**
509
     * Use this method to send audio files,
510
     * if you want Telegram clients to display the file as a playable voice message.
511
     * For this to work, your audio must be in an .ogg file encoded with OPUS
512
     * (other formats may be sent as Audio or Document).
513
     * On success, the sent Message is returned.
514
     * Bots can currently send voice messages of up to 50 MB in size, this limit may be changed in the future.
515
     *
516
     * @param int $chatId
517
     * @param \CURLFile|string $voice
518
     * @param int|null $duration
519
     * @param int|null $replyToMessageId
520
     * @param Types\ReplyKeyboardMarkup|Types\ReplyKeyboardHide|Types\ForceReply|null $replyMarkup
521
     * @param bool $disableNotification
522
     *
523
     * @return \TelegramBot\Api\Types\Message
524
     * @throws \TelegramBot\Api\InvalidArgumentException
525
     * @throws \TelegramBot\Api\Exception
526
     */
527 View Code Duplication
    public function sendVoice($chatId, $voice, $duration = null, $replyToMessageId = null, $replyMarkup = null, $disableNotification = false)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
528
    {
529
        return Message::fromResponse($this->call('sendVoice', [
530
            'chat_id' => $chatId,
531
            'voice' => $voice,
532
            'duration' => $duration,
533
            'reply_to_message_id' => $replyToMessageId,
534
            'reply_markup' => is_null($replyMarkup) ? $replyMarkup : $replyMarkup->toJson(),
535
            'disable_notification' => (bool) $disableNotification
536
        ]));
537
    }
538
539
    /**
540
     * Use this method to forward messages of any kind. On success, the sent Message is returned.
541
     *
542
     * @param int $chatId
543
     * @param int $fromChatId
544
     * @param int $messageId
545
     * @param bool $disableNotification
546
     *
547
     * @return \TelegramBot\Api\Types\Message
548
     * @throws \TelegramBot\Api\InvalidArgumentException
549
     * @throws \TelegramBot\Api\Exception
550
     */
551
    public function forwardMessage($chatId, $fromChatId, $messageId, $disableNotification = false)
552
    {
553
        return Message::fromResponse($this->call('forwardMessage', [
554
            'chat_id' => $chatId,
555
            'from_chat_id' => $fromChatId,
556
            'message_id' => (int) $messageId,
557
            'disable_notification' => (bool) $disableNotification
558
        ]));
559
    }
560
561
    /**
562
     * Use this method to send audio files,
563
     * if you want Telegram clients to display them in the music player.
564
     * Your audio must be in the .mp3 format.
565
     * On success, the sent Message is returned.
566
     * Bots can currently send audio files of up to 50 MB in size, this limit may be changed in the future.
567
     *
568
     * For backward compatibility, when the fields title and performer are both empty
569
     * and the mime-type of the file to be sent is not audio/mpeg, the file will be sent as a playable voice message.
570
     * For this to work, the audio must be in an .ogg file encoded with OPUS.
571
     * This behavior will be phased out in the future. For sending voice messages, use the sendVoice method instead.
572
     *
573
     * @deprecated since 20th February. Removed backward compatibility from the method sendAudio.
574
     * Voice messages now must be sent using the method sendVoice.
575
     * There is no more need to specify a non-empty title or performer while sending the audio by file_id.
576
     *
577
     * @param int $chatId
578
     * @param \CURLFile|string $audio
579
     * @param int|null $duration
580
     * @param string|null $performer
581
     * @param string|null $title
582
     * @param int|null $replyToMessageId
583
     * @param Types\ReplyKeyboardMarkup|Types\ReplyKeyboardHide|Types\ForceReply|null $replyMarkup
584
     * @param bool $disableNotification
585
     *
586
     * @return \TelegramBot\Api\Types\Message
587
     * @throws \TelegramBot\Api\InvalidArgumentException
588
     * @throws \TelegramBot\Api\Exception
589
     */
590
    public function sendAudio(
591
        $chatId,
592
        $audio,
593
        $duration = null,
594
        $performer = null,
595
        $title = null,
596
        $replyToMessageId = null,
597
        $replyMarkup = null,
598
        $disableNotification = false
599
    ) {
600
        return Message::fromResponse($this->call('sendAudio', [
601
            'chat_id' => $chatId,
602
            'audio' => $audio,
603
            'duration' => $duration,
604
            'performer' => $performer,
605
            'title' => $title,
606
            'reply_to_message_id' => $replyToMessageId,
607
            'reply_markup' => is_null($replyMarkup) ? $replyMarkup : $replyMarkup->toJson(),
608
            'disable_notification' => (bool) $disableNotification
609
        ]));
610
    }
611
612
    /**
613
     * Use this method to send photos. On success, the sent Message is returned.
614
     *
615
     * @param int $chatId
616
     * @param \CURLFile|string $photo
617
     * @param string|null $caption
618
     * @param int|null $replyToMessageId
619
     * @param Types\ReplyKeyboardMarkup|Types\ReplyKeyboardHide|Types\ForceReply|null $replyMarkup
620
     * @param bool $disableNotification
621
     *
622
     * @return \TelegramBot\Api\Types\Message
623
     * @throws \TelegramBot\Api\InvalidArgumentException
624
     * @throws \TelegramBot\Api\Exception
625
     */
626 View Code Duplication
    public function sendPhoto($chatId, $photo, $caption = null, $replyToMessageId = null, $replyMarkup = null, $disableNotification = false)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
627
    {
628
        return Message::fromResponse($this->call('sendPhoto', [
629
            'chat_id' => $chatId,
630
            'photo' => $photo,
631
            'caption' => $caption,
632
            'reply_to_message_id' => $replyToMessageId,
633
            'reply_markup' => is_null($replyMarkup) ? $replyMarkup : $replyMarkup->toJson(),
634
            'disable_notification' => (bool) $disableNotification
635
        ]));
636
    }
637
638
    /**
639
     * Use this method to send general files. On success, the sent Message is returned.
640
     * Bots can currently send files of any type of up to 50 MB in size, this limit may be changed in the future.
641
     *
642
     * @param int $chatId
643
     * @param \CURLFile|string $document
644
     * @param int|null $replyToMessageId
645
     * @param Types\ReplyKeyboardMarkup|Types\ReplyKeyboardHide|Types\ForceReply|null $replyMarkup
646
     * @param bool $disableNotification
647
     *
648
     * @return \TelegramBot\Api\Types\Message
649
     * @throws \TelegramBot\Api\InvalidArgumentException
650
     * @throws \TelegramBot\Api\Exception
651
     */
652 View Code Duplication
    public function sendDocument($chatId, $document, $replyToMessageId = null, $replyMarkup = null, $disableNotification = false)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
653
    {
654
        return Message::fromResponse($this->call('sendDocument', [
655
            'chat_id' => $chatId,
656
            'document' => $document,
657
            'reply_to_message_id' => $replyToMessageId,
658
            'reply_markup' => is_null($replyMarkup) ? $replyMarkup : $replyMarkup->toJson(),
659
            'disable_notification' => (bool) $disableNotification
660
        ]));
661
    }
662
663
    /**
664
     * Use this method to get basic info about a file and prepare it for downloading.
665
     * For the moment, bots can download files of up to 20MB in size.
666
     * On success, a File object is returned.
667
     * The file can then be downloaded via the link https://api.telegram.org/file/bot<token>/<file_path>,
668
     * where <file_path> is taken from the response.
669
     * It is guaranteed that the link will be valid for at least 1 hour.
670
     * When the link expires, a new one can be requested by calling getFile again.
671
     *
672
     * @param $fileId
673
     *
674
     * @return \TelegramBot\Api\Types\File
675
     * @throws \TelegramBot\Api\InvalidArgumentException
676
     * @throws \TelegramBot\Api\Exception
677
     */
678
    public function getFile($fileId)
679
    {
680
        return File::fromResponse($this->call('getFile', ['file_id' => $fileId]));
681
    }
682
683
    /**
684
     * Get file contents via cURL
685
     *
686
     * @param $fileId
687
     *
688
     * @return string
689
     *
690
     * @throws \TelegramBot\Api\HttpException
691
     */
692
    public function downloadFile($fileId)
693
    {
694
        $file = $this->getFile($fileId);
695
        $options = [
696
            CURLOPT_HEADER => 0,
697
            CURLOPT_HTTPGET => 1,
698
            CURLOPT_RETURNTRANSFER => 1,
699
            CURLOPT_URL => $this->getFileUrl() . '/' . $file->getFilePath()
700
        ];
701
702
        return $this->executeCurl($options);
703
    }
704
705
    /**
706
     * Use this method to send answers to an inline query. On success, True is returned.
707
     * No more than 50 results per query are allowed.
708
     *
709
     * @param string $inlineQueryId
710
     * @param \TelegramBot\Api\Types\Inline\AbstractInlineQueryResult[] $results
711
     * @param int $cacheTime
712
     * @param bool $isPersonal
713
     * @param string $nextOffset
714
     *
715
     * @return mixed
716
     * @throws Exception
717
     */
718
    public function answerInlineQuery($inlineQueryId, $results, $cacheTime = 300, $isPersonal = false, $nextOffset = '')
719
    {
720
        $results = array_map(function ($item) {
721
            /* @var \TelegramBot\Api\Types\Inline\AbstractInlineQueryResult $item */
722
723
            return json_decode($item->toJson(), true);
724
        }, $results);
725
726
        return $this->call('answerInlineQuery', [
727
            'inline_query_id' => $inlineQueryId,
728
            'results' => json_encode($results),
729
            'cache_time' => $cacheTime,
730
            'is_personal' => $isPersonal,
731
            'next_offset' => $nextOffset,
732
        ]);
733
    }
734
735
    /**
736
     * Close curl
737
     */
738 9
    public function __destruct()
739
    {
740 9
        $this->curl && curl_close($this->curl);
741 9
    }
742
743
    /**
744
     * @return string
745
     */
746
    public function getUrl()
747
    {
748
        return self::URL_PREFIX . $this->token;
749
    }
750
751
    /**
752
     * @return string
753
     */
754
    public function getFileUrl()
755
    {
756
        return self::FILE_URL_PREFIX . $this->token;
757
    }
758
759
    /**
760
     * @param \TelegramBot\Api\Types\Update $update
761
     * @param string $eventName
762
     *
763
     * @throws \TelegramBot\Api\Exception
764
     */
765
    public function trackUpdate(Update $update, $eventName = 'Message')
766
    {
767
        if (!in_array($update->getUpdateId(), $this->trackedEvents)) {
768
            $this->trackedEvents[] = $update->getUpdateId();
769
770
            $this->track($update->getMessage(), $eventName);
771
772
            if (count($this->trackedEvents) > self::MAX_TRACKED_EVENTS) {
773
                $this->trackedEvents = array_slice($this->trackedEvents, round(self::MAX_TRACKED_EVENTS / 4));
774
            }
775
        }
776
    }
777
778
    /**
779
     * Wrapper for tracker
780
     *
781
     * @param \TelegramBot\Api\Types\Message $message
782
     * @param string $eventName
783
     *
784
     * @throws \TelegramBot\Api\Exception
785
     */
786
    public function track(Message $message, $eventName = 'Message')
787
    {
788
        if ($this->tracker instanceof Botan) {
789
            $this->tracker->track($message, $eventName);
790
        }
791
    }
792
}
793