Completed
Pull Request — master (#49)
by
unknown
02:55
created

BotApi::sendVenue()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 23
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 23
ccs 0
cts 12
cp 0
rs 9.0856
c 0
b 0
f 0
cc 1
eloc 20
nc 1
nop 9
crap 2

How to fix   Many Parameters   

Many Parameters

Methods with many parameters are not only hard to understand, but their parameters also often become inconsistent when you need more, or different data.

There are several approaches to avoid long parameter lists:

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\Inline\QueryResult\AbstractInlineQueryResult;
8
use TelegramBot\Api\Types\Message;
9
use TelegramBot\Api\Types\Update;
10
use TelegramBot\Api\Types\User;
11
use TelegramBot\Api\Types\UserProfilePhotos;
12
13
/**
14
 * Class BotApi
15
 *
16
 * @package TelegramBot\Api
17
 */
18
class BotApi
19
{
20
    /**
21
     * HTTP codes
22
     *
23
     * @var array
24
     */
25
    public static $codes = [
26
        // Informational 1xx
27
        100 => 'Continue',
28
        101 => 'Switching Protocols',
29
        102 => 'Processing',            // RFC2518
30
        // Success 2xx
31
        200 => 'OK',
32
        201 => 'Created',
33
        202 => 'Accepted',
34
        203 => 'Non-Authoritative Information',
35
        204 => 'No Content',
36
        205 => 'Reset Content',
37
        206 => 'Partial Content',
38
        207 => 'Multi-Status',          // RFC4918
39
        208 => 'Already Reported',      // RFC5842
40
        226 => 'IM Used',               // RFC3229
41
        // Redirection 3xx
42
        300 => 'Multiple Choices',
43
        301 => 'Moved Permanently',
44
        302 => 'Found', // 1.1
45
        303 => 'See Other',
46
        304 => 'Not Modified',
47
        305 => 'Use Proxy',
48
        // 306 is deprecated but reserved
49
        307 => 'Temporary Redirect',
50
        308 => 'Permanent Redirect',    // RFC7238
51
        // Client Error 4xx
52
        400 => 'Bad Request',
53
        401 => 'Unauthorized',
54
        402 => 'Payment Required',
55
        403 => 'Forbidden',
56
        404 => 'Not Found',
57
        405 => 'Method Not Allowed',
58
        406 => 'Not Acceptable',
59
        407 => 'Proxy Authentication Required',
60
        408 => 'Request Timeout',
61
        409 => 'Conflict',
62
        410 => 'Gone',
63
        411 => 'Length Required',
64
        412 => 'Precondition Failed',
65
        413 => 'Payload Too Large',
66
        414 => 'URI Too Long',
67
        415 => 'Unsupported Media Type',
68
        416 => 'Range Not Satisfiable',
69
        417 => 'Expectation Failed',
70
        422 => 'Unprocessable Entity',                                        // RFC4918
71
        423 => 'Locked',                                                      // RFC4918
72
        424 => 'Failed Dependency',                                           // RFC4918
73
        425 => 'Reserved for WebDAV advanced collections expired proposal',   // RFC2817
74
        426 => 'Upgrade Required',                                            // RFC2817
75
        428 => 'Precondition Required',                                       // RFC6585
76
        429 => 'Too Many Requests',                                           // RFC6585
77
        431 => 'Request Header Fields Too Large',                             // RFC6585
78
        // Server Error 5xx
79
        500 => 'Internal Server Error',
80
        501 => 'Not Implemented',
81
        502 => 'Bad Gateway',
82
        503 => 'Service Unavailable',
83
        504 => 'Gateway Timeout',
84
        505 => 'HTTP Version Not Supported',
85
        506 => 'Variant Also Negotiates (Experimental)',                      // RFC2295
86
        507 => 'Insufficient Storage',                                        // RFC4918
87
        508 => 'Loop Detected',                                               // RFC5842
88
        510 => 'Not Extended',                                                // RFC2774
89
        511 => 'Network Authentication Required',                             // RFC6585
90
    ];
91
92
93
    /**
94
     * Default http status code
95
     */
96
    const DEFAULT_STATUS_CODE = 200;
97
98
    /**
99
     * Not Modified http status code
100
     */
101
    const NOT_MODIFIED_STATUS_CODE = 304;
102
103
    /**
104
     * Limits for tracked ids
105
     */
106
    const MAX_TRACKED_EVENTS = 200;
107
108
    /**
109
     * Url prefixes
110
     */
111
    const URL_PREFIX = 'https://api.telegram.org/bot';
112
113
    /**
114
     * Url prefix for files
115
     */
116
    const FILE_URL_PREFIX = 'https://api.telegram.org/file/bot';
117
118
    /**
119
     * CURL object
120
     *
121
     * @var
122
     */
123
    protected $curl;
124
125
    /**
126
     * Bot token
127
     *
128
     * @var string
129
     */
130
    protected $token;
131
132
    /**
133
     * Botan tracker
134
     *
135
     * @var \TelegramBot\Api\Botan
136
     */
137
    protected $tracker;
138
139
    /**
140
     * list of event ids
141
     *
142
     * @var array
143
     */
144
    protected $trackedEvents = [];
145
146
    /**
147
     * Check whether return associative array
148
     *
149
     * @var bool
150
     */
151
    protected $returnArray = true;
152
153
154
    /**
155
     * Constructor
156
     *
157
     * @param string $token Telegram Bot API token
158
     * @param string|null $trackerToken Yandex AppMetrica application api_key
159
     */
160 9
    public function __construct($token, $trackerToken = null)
161
    {
162 9
        $this->curl = curl_init();
163 9
        $this->token = $token;
164
165 9
        if ($trackerToken) {
166
            $this->tracker = new Botan($trackerToken);
167
        }
168 9
    }
169
170
    /**
171
     * Set return array
172
     *
173
     * @param bool $mode
174
     *
175
     * @return $this
176
     */
177
    public function setModeObject($mode = true)
178
    {
179
        $this->returnArray = !$mode;
180
181
        return $this;
182
    }
183
184
185
    /**
186
     * Call method
187
     *
188
     * @param string $method
189
     * @param array|null $data
190
     *
191
     * @return mixed
192
     * @throws \TelegramBot\Api\Exception
193
     * @throws \TelegramBot\Api\HttpException
194
     * @throws \TelegramBot\Api\InvalidJsonException
195
     */
196
    public function call($method, array $data = null)
197
    {
198
        $options = [
199
            CURLOPT_URL => $this->getUrl().'/'.$method,
200
            CURLOPT_RETURNTRANSFER => true,
201
            CURLOPT_POST => null,
202
            CURLOPT_POSTFIELDS => null,
203
        ];
204
205
        if ($data) {
206
            $options[CURLOPT_POST] = true;
207
            $options[CURLOPT_POSTFIELDS] = $data;
208
        }
209
210
        $response = self::jsonValidate($this->executeCurl($options), $this->returnArray);
211
212
        if ($this->returnArray) {
213
            if (!isset($response['ok'])) {
214
                throw new Exception($response['description'], $response['error_code']);
215
            }
216
217
            return $response['result'];
218
        }
219
220
        if (!$response->ok) {
221
            throw new Exception($response->description, $response->error_code);
222
        }
223
224
        return $response->result;
225
    }
226
227
    /**
228
     * curl_exec wrapper for response validation
229
     *
230
     * @param array $options
231
     *
232
     * @return string
233
     *
234
     * @throws \TelegramBot\Api\HttpException
235
     */
236
    protected function executeCurl(array $options)
237
    {
238
        curl_setopt_array($this->curl, $options);
239
240
        $result = curl_exec($this->curl);
241
        self::curlValidate($this->curl);
242
        if ($result === false) {
243
            throw new HttpException(curl_error($this->curl), curl_errno($this->curl));
244
        }
245
246
        return $result;
247
    }
248
249
    /**
250
     * Response validation
251
     *
252
     * @param resource $curl
253
     *
254
     * @throws \TelegramBot\Api\HttpException
255
     */
256
    public static function curlValidate($curl)
257
    {
258
        if (($httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE))
259
            && !in_array($httpCode, [self::DEFAULT_STATUS_CODE, self::NOT_MODIFIED_STATUS_CODE])
260
        ) {
261
            $r = json_decode(curl_exec($curl));
262
            throw new HttpException(self::$codes[$httpCode]." (".$r->description.")", $httpCode);
263
        }
264
    }
265
266
    /**
267
     * JSON validation
268
     *
269
     * @param string $jsonString
270
     * @param boolean $asArray
271
     *
272
     * @return object|array
273
     * @throws \TelegramBot\Api\InvalidJsonException
274
     */
275
    public static function jsonValidate($jsonString, $asArray)
276
    {
277
        $json = json_decode($jsonString, $asArray);
278
279
        if (json_last_error() != JSON_ERROR_NONE) {
280
            throw new InvalidJsonException(json_last_error_msg(), json_last_error());
281
        }
282
283
        return $json;
284
    }
285
286
    /**
287
     * Use this method to send text messages. On success, the sent \TelegramBot\Api\Types\Message is returned.
288
     *
289
     * @param int|string $chatId
290
     * @param string $text
291
     * @param string|null $parseMode
292
     * @param bool $disablePreview
293
     * @param int|null $replyToMessageId
294
     * @param Types\ReplyKeyboardMarkup|Types\ReplyKeyboardHide|Types\ForceReply|null $replyMarkup
295
     * @param bool $disableNotification
296
     *
297
     * @return \TelegramBot\Api\Types\Message
298
     * @throws \TelegramBot\Api\InvalidArgumentException
299
     * @throws \TelegramBot\Api\Exception
300
     */
301
    public function sendMessage(
302
        $chatId,
303
        $text,
304
        $parseMode = null,
305
        $disablePreview = false,
306
        $replyToMessageId = null,
307
        $replyMarkup = null,
308
        $disableNotification = false
309
    ) {
310
        return Message::fromResponse($this->call('sendMessage', [
311
            'chat_id' => $chatId,
312
            'text' => $text,
313
            'parse_mode' => $parseMode,
314
            'disable_web_page_preview' => $disablePreview,
315
            'reply_to_message_id' => (int)$replyToMessageId,
316
            'reply_markup' => $replyMarkup,
317
            'disable_notification' => (bool)$disableNotification,
318
        ]));
319
    }
320
321
    /**
322
     * Use this method to send phone contacts
323
     *
324
     * @param int|string $chatId chat_id or @channel_name
325
     * @param string $phoneNumber
326
     * @param string $firstName
327
     * @param string $lastName
328
     * @param int|null $replyToMessageId
329
     * @param Types\ReplyKeyboardMarkup|Types\ReplyKeyboardHide|Types\ForceReply|null $replyMarkup
330
     * @param bool $disableNotification
331
     *
332
     * @return \TelegramBot\Api\Types\Message
333
     * @throws \TelegramBot\Api\Exception
334
     */
335 View Code Duplication
    public function sendContact(
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...
336
        $chatId,
337
        $phoneNumber,
338
        $firstName,
339
        $lastName = null,
340
        $replyToMessageId = null,
341
        $replyMarkup = null,
342
        $disableNotification = false
343
    ) {
344
        return Message::fromResponse($this->call('sendContact', [
345
            'chat_id' => $chatId,
346
            'phone_number' => $phoneNumber,
347
            'first_name' => $firstName,
348
            'last_name' => $lastName,
349
            'reply_to_message_id' => $replyToMessageId,
350
            'reply_markup' => $replyMarkup,
351
            'disable_notification' => (bool)$disableNotification,
352
        ]));
353
    }
354
355
    /**
356
     * Use this method when you need to tell the user that something is happening on the bot's side.
357
     * The status is set for 5 seconds or less (when a message arrives from your bot,
358
     * Telegram clients clear its typing status).
359
     *
360
     * We only recommend using this method when a response from the bot will take a noticeable amount of time to arrive.
361
     *
362
     * Type of action to broadcast. Choose one, depending on what the user is about to receive:
363
     * `typing` for text messages, `upload_photo` for photos, `record_video` or `upload_video` for videos,
364
     * `record_audio` or upload_audio for audio files, `upload_document` for general files,
365
     * `find_location` for location data.
366
     *
367
     * @param int $chatId
368
     * @param string $action
369
     *
370
     * @return bool
371
     * @throws \TelegramBot\Api\Exception
372
     */
373
    public function sendChatAction($chatId, $action)
374
    {
375
        return $this->call('sendChatAction', [
376
            'chat_id' => $chatId,
377
            'action' => $action,
378
        ]);
379
    }
380
381
    /**
382
     * Use this method to get a list of profile pictures for a user.
383
     *
384
     * @param int $userId
385
     * @param int $offset
386
     * @param int $limit
387
     *
388
     * @return \TelegramBot\Api\Types\UserProfilePhotos
389
     * @throws \TelegramBot\Api\Exception
390
     */
391
    public function getUserProfilePhotos($userId, $offset = 0, $limit = 100)
392
    {
393
        return UserProfilePhotos::fromResponse($this->call('getUserProfilePhotos', [
394
            'user_id' => (int)$userId,
395
            'offset' => (int)$offset,
396
            'limit' => (int)$limit,
397
        ]));
398
    }
399
400
    /**
401
     * Use this method to specify a url and receive incoming updates via an outgoing webhook.
402
     * Whenever there is an update for the bot, we will send an HTTPS POST request to the specified url,
403
     * containing a JSON-serialized Update.
404
     * In case of an unsuccessful request, we will give up after a reasonable amount of attempts.
405
     *
406
     * @param string $url HTTPS url to send updates to. Use an empty string to remove webhook integration
407
     * @param \CURLFile|string $certificate Upload your public key certificate
408
     *                                      so that the root certificate in use can be checked
409
     *
410
     * @return string
411
     *
412
     * @throws \TelegramBot\Api\Exception
413
     */
414
    public function setWebhook($url = '', $certificate = null)
415
    {
416
        return $this->call('setWebhook', ['url' => $url, 'certificate' => $certificate]);
417
    }
418
419
    /**
420
     * A simple method for testing your bot's auth token.Requires no parameters.
421
     * Returns basic information about the bot in form of a User object.
422
     *
423
     * @return \TelegramBot\Api\Types\User
424
     * @throws \TelegramBot\Api\Exception
425
     * @throws \TelegramBot\Api\InvalidArgumentException
426
     */
427
    public function getMe()
428
    {
429
        return User::fromResponse($this->call('getMe'));
430
    }
431
432
    /**
433
     * Use this method to receive incoming updates using long polling.
434
     * An Array of Update objects is returned.
435
     *
436
     * Notes
437
     * 1. This method will not work if an outgoing webhook is set up.
438
     * 2. In order to avoid getting duplicate updates, recalculate offset after each server response.
439
     *
440
     * @param int $offset
441
     * @param int $limit
442
     * @param int $timeout
443
     *
444
     * @return Update[]
445
     * @throws \TelegramBot\Api\Exception
446
     * @throws \TelegramBot\Api\InvalidArgumentException
447
     */
448 2
    public function getUpdates($offset = 0, $limit = 100, $timeout = 0)
449
    {
450 2
        $updates = ArrayOfUpdates::fromResponse($this->call('getUpdates', [
451 2
            'offset' => $offset,
452 2
            'limit' => $limit,
453 2
            'timeout' => $timeout,
454 2
        ]));
455
456 2
        if ($this->tracker instanceof Botan) {
457
            foreach ($updates as $update) {
458
                $this->trackUpdate($update);
459
            }
460
        }
461
462 2
        return $updates;
463
    }
464
465
    /**
466
     * Use this method to send point on the map. On success, the sent Message is returned.
467
     *
468
     * @param int $chatId
469
     * @param float $latitude
470
     * @param float $longitude
471
     * @param int|null $replyToMessageId
472
     * @param Types\ReplyKeyboardMarkup|Types\ReplyKeyboardHide|Types\ForceReply|null $replyMarkup
473
     * @param bool $disableNotification
474
     *
475
     * @return \TelegramBot\Api\Types\Message
476
     * @throws \TelegramBot\Api\Exception
477
     */
478 View Code Duplication
    public function sendLocation(
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...
479
        $chatId,
480
        $latitude,
481
        $longitude,
482
        $replyToMessageId = null,
483
        $replyMarkup = null,
484
        $disableNotification = false
485
    ) {
486
        return Message::fromResponse($this->call('sendLocation', [
487
            'chat_id' => $chatId,
488
            'latitude' => $latitude,
489
            'longitude' => $longitude,
490
            'reply_to_message_id' => $replyToMessageId,
491
            'reply_markup' => $replyMarkup,
492
            'disable_notification' => (bool)$disableNotification,
493
        ]));
494
    }
495
496
    /**
497
     * Use this method to send information about a venue. On success, the sent Message is returned.
498
     *
499
     * @param int|string $chatId chat_id or @channel_name
500
     * @param float $latitude
501
     * @param float $longitude
502
     * @param string $title
503
     * @param string $address
504
     * @param string|null $foursquareId
505
     * @param int|null $replyToMessageId
506
     * @param Types\ReplyKeyboardMarkup|Types\ReplyKeyboardHide|Types\ForceReply|null $replyMarkup
507
     * @param bool $disableNotification
508
     *
509
     * @return \TelegramBot\Api\Types\Message
510
     * @throws \TelegramBot\Api\Exception
511
     */
512
    public function sendVenue(
513
        $chatId,
514
        $latitude,
515
        $longitude,
516
        $title,
517
        $address,
518
        $foursquareId = null,
519
        $replyToMessageId = null,
520
        $replyMarkup = null,
521
        $disableNotification = false
522
    ) {
523
        return Message::fromResponse($this->call('sendVenue', [
524
            'chat_id' => $chatId,
525
            'latitude' => $latitude,
526
            'longitude' => $longitude,
527
            'title' => $title,
528
            'address' => $address,
529
            'foursquare_id' => $foursquareId,
530
            'reply_to_message_id' => $replyToMessageId,
531
            'reply_markup' => $replyMarkup,
532
            'disable_notification' => (bool)$disableNotification,
533
        ]));
534
    }
535
536
    /**
537
     * Use this method to send .webp stickers. On success, the sent Message is returned.
538
     *
539
     * @param int|string $chatId chat_id or @channel_name
540
     * @param \CURLFile|string $sticker
541
     * @param int|null $replyToMessageId
542
     * @param Types\ReplyKeyboardMarkup|Types\ReplyKeyboardHide|Types\ForceReply|null $replyMarkup
543
     * @param bool $disableNotification
544
     *
545
     * @return \TelegramBot\Api\Types\Message
546
     * @throws \TelegramBot\Api\InvalidArgumentException
547
     * @throws \TelegramBot\Api\Exception
548
     */
549
    public function sendSticker(
550
        $chatId,
551
        $sticker,
552
        $replyToMessageId = null,
553
        $replyMarkup = null,
554
        $disableNotification = false
555
    ) {
556
        return Message::fromResponse($this->call('sendSticker', [
557
            'chat_id' => $chatId,
558
            'sticker' => $sticker,
559
            'reply_to_message_id' => $replyToMessageId,
560
            'reply_markup' => $replyMarkup,
561
            'disable_notification' => (bool)$disableNotification,
562
        ]));
563
    }
564
565
    /**
566
     * Use this method to send video files,
567
     * Telegram clients support mp4 videos (other formats may be sent as Document).
568
     * On success, the sent Message is returned.
569
     *
570
     * @param int|string $chatId chat_id or @channel_name
571
     * @param \CURLFile|string $video
572
     * @param int|null $duration
573
     * @param string|null $caption
574
     * @param int|null $replyToMessageId
575
     * @param Types\ReplyKeyboardMarkup|Types\ReplyKeyboardHide|Types\ForceReply|null $replyMarkup
576
     * @param bool $disableNotification
577
     *
578
     * @return \TelegramBot\Api\Types\Message
579
     * @throws \TelegramBot\Api\InvalidArgumentException
580
     * @throws \TelegramBot\Api\Exception
581
     */
582
    public function sendVideo(
583
        $chatId,
584
        $video,
585
        $duration = null,
586
        $caption = null,
587
        $replyToMessageId = null,
588
        $replyMarkup = null,
589
        $disableNotification = false
590
    ) {
591
        return Message::fromResponse($this->call('sendVideo', [
592
            'chat_id' => $chatId,
593
            'video' => $video,
594
            'duration' => $duration,
595
            'caption' => $caption,
596
            'reply_to_message_id' => $replyToMessageId,
597
            'reply_markup' => $replyMarkup,
598
            'disable_notification' => (bool)$disableNotification,
599
        ]));
600
    }
601
602
    /**
603
     * Use this method to send audio files,
604
     * if you want Telegram clients to display the file as a playable voice message.
605
     * For this to work, your audio must be in an .ogg file encoded with OPUS
606
     * (other formats may be sent as Audio or Document).
607
     * On success, the sent Message is returned.
608
     * Bots can currently send voice messages of up to 50 MB in size, this limit may be changed in the future.
609
     *
610
     * @param int|string $chatId chat_id or @channel_name
611
     * @param \CURLFile|string $voice
612
     * @param int|null $duration
613
     * @param int|null $replyToMessageId
614
     * @param Types\ReplyKeyboardMarkup|Types\ReplyKeyboardHide|Types\ForceReply|null $replyMarkup
615
     * @param bool $disableNotification
616
     *
617
     * @return \TelegramBot\Api\Types\Message
618
     * @throws \TelegramBot\Api\InvalidArgumentException
619
     * @throws \TelegramBot\Api\Exception
620
     */
621 View Code Duplication
    public function sendVoice(
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...
622
        $chatId,
623
        $voice,
624
        $duration = null,
625
        $replyToMessageId = null,
626
        $replyMarkup = null,
627
        $disableNotification = false
628
    ) {
629
        return Message::fromResponse($this->call('sendVoice', [
630
            'chat_id' => $chatId,
631
            'voice' => $voice,
632
            'duration' => $duration,
633
            'reply_to_message_id' => $replyToMessageId,
634
            'reply_markup' => $replyMarkup,
635
            'disable_notification' => (bool)$disableNotification,
636
        ]));
637
    }
638
639
    /**
640
     * Use this method to forward messages of any kind. On success, the sent Message is returned.
641
     *
642
     * @param int|string $chatId chat_id or @channel_name
643
     * @param int $fromChatId
644
     * @param int $messageId
645
     * @param bool $disableNotification
646
     *
647
     * @return \TelegramBot\Api\Types\Message
648
     * @throws \TelegramBot\Api\InvalidArgumentException
649
     * @throws \TelegramBot\Api\Exception
650
     */
651
    public function forwardMessage($chatId, $fromChatId, $messageId, $disableNotification = false)
652
    {
653
        return Message::fromResponse($this->call('forwardMessage', [
654
            'chat_id' => $chatId,
655
            'from_chat_id' => $fromChatId,
656
            'message_id' => (int)$messageId,
657
            'disable_notification' => (bool)$disableNotification,
658
        ]));
659
    }
660
661
    /**
662
     * Use this method to send audio files,
663
     * if you want Telegram clients to display them in the music player.
664
     * Your audio must be in the .mp3 format.
665
     * On success, the sent Message is returned.
666
     * Bots can currently send audio files of up to 50 MB in size, this limit may be changed in the future.
667
     *
668
     * For backward compatibility, when the fields title and performer are both empty
669
     * and the mime-type of the file to be sent is not audio/mpeg, the file will be sent as a playable voice message.
670
     * For this to work, the audio must be in an .ogg file encoded with OPUS.
671
     * This behavior will be phased out in the future. For sending voice messages, use the sendVoice method instead.
672
     *
673
     * @deprecated since 20th February. Removed backward compatibility from the method sendAudio.
674
     * Voice messages now must be sent using the method sendVoice.
675
     * There is no more need to specify a non-empty title or performer while sending the audio by file_id.
676
     *
677
     * @param int|string $chatId chat_id or @channel_name
678
     * @param \CURLFile|string $audio
679
     * @param int|null $duration
680
     * @param string|null $performer
681
     * @param string|null $title
682
     * @param int|null $replyToMessageId
683
     * @param Types\ReplyKeyboardMarkup|Types\ReplyKeyboardHide|Types\ForceReply|null $replyMarkup
684
     * @param bool $disableNotification
685
     *
686
     * @return \TelegramBot\Api\Types\Message
687
     * @throws \TelegramBot\Api\InvalidArgumentException
688
     * @throws \TelegramBot\Api\Exception
689
     */
690
    public function sendAudio(
691
        $chatId,
692
        $audio,
693
        $duration = null,
694
        $performer = null,
695
        $title = null,
696
        $replyToMessageId = null,
697
        $replyMarkup = null,
698
        $disableNotification = false
699
    ) {
700
        return Message::fromResponse($this->call('sendAudio', [
701
            'chat_id' => $chatId,
702
            'audio' => $audio,
703
            'duration' => $duration,
704
            'performer' => $performer,
705
            'title' => $title,
706
            'reply_to_message_id' => $replyToMessageId,
707
            'reply_markup' => $replyMarkup,
708
            'disable_notification' => (bool)$disableNotification,
709
        ]));
710
    }
711
712
    /**
713
     * Use this method to send photos. On success, the sent Message is returned.
714
     *
715
     * @param int|string $chatId chat_id or @channel_name
716
     * @param \CURLFile|string $photo
717
     * @param string|null $caption
718
     * @param int|null $replyToMessageId
719
     * @param Types\ReplyKeyboardMarkup|Types\ReplyKeyboardHide|Types\ForceReply|null $replyMarkup
720
     * @param bool $disableNotification
721
     *
722
     * @return \TelegramBot\Api\Types\Message
723
     * @throws \TelegramBot\Api\InvalidArgumentException
724
     * @throws \TelegramBot\Api\Exception
725
     */
726 View Code Duplication
    public function sendPhoto(
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...
727
        $chatId,
728
        $photo,
729
        $caption = null,
730
        $replyToMessageId = null,
731
        $replyMarkup = null,
732
        $disableNotification = false
733
    ) {
734
        return Message::fromResponse($this->call('sendPhoto', [
735
            'chat_id' => $chatId,
736
            'photo' => $photo,
737
            'caption' => $caption,
738
            'reply_to_message_id' => $replyToMessageId,
739
            'reply_markup' => $replyMarkup,
740
            'disable_notification' => (bool)$disableNotification,
741
        ]));
742
    }
743
744
    /**
745
     * Use this method to send general files. On success, the sent Message is returned.
746
     * Bots can currently send files of any type of up to 50 MB in size, this limit may be changed in the future.
747
     *
748
     * @param int|string $chatId chat_id or @channel_name
749
     * @param \CURLFile|string $document
750
     * @param int|null $replyToMessageId
751
     * @param Types\ReplyKeyboardMarkup|Types\ReplyKeyboardHide|Types\ForceReply|null $replyMarkup
752
     * @param bool $disableNotification
753
     *
754
     * @return \TelegramBot\Api\Types\Message
755
     * @throws \TelegramBot\Api\InvalidArgumentException
756
     * @throws \TelegramBot\Api\Exception
757
     */
758
    public function sendDocument(
759
        $chatId,
760
        $document,
761
        $replyToMessageId = null,
762
        $replyMarkup = null,
763
        $disableNotification = false
764
    ) {
765
        return Message::fromResponse($this->call('sendDocument', [
766
            'chat_id' => $chatId,
767
            'document' => $document,
768
            'reply_to_message_id' => $replyToMessageId,
769
            'reply_markup' => $replyMarkup,
770
            'disable_notification' => (bool)$disableNotification,
771
        ]));
772
    }
773
774
    /**
775
     * Use this method to get basic info about a file and prepare it for downloading.
776
     * For the moment, bots can download files of up to 20MB in size.
777
     * On success, a File object is returned.
778
     * The file can then be downloaded via the link https://api.telegram.org/file/bot<token>/<file_path>,
779
     * where <file_path> is taken from the response.
780
     * It is guaranteed that the link will be valid for at least 1 hour.
781
     * When the link expires, a new one can be requested by calling getFile again.
782
     *
783
     * @param $fileId
784
     *
785
     * @return \TelegramBot\Api\Types\File
786
     * @throws \TelegramBot\Api\InvalidArgumentException
787
     * @throws \TelegramBot\Api\Exception
788
     */
789
    public function getFile($fileId)
790
    {
791
        return File::fromResponse($this->call('getFile', ['file_id' => $fileId]));
792
    }
793
794
    /**
795
     * Get file contents via cURL
796
     *
797
     * @param $fileId
798
     *
799
     * @return string
800
     *
801
     * @throws \TelegramBot\Api\HttpException
802
     */
803
    public function downloadFile($fileId)
804
    {
805
        $file = $this->getFile($fileId);
806
        $options = [
807
            CURLOPT_HEADER => 0,
808
            CURLOPT_HTTPGET => 1,
809
            CURLOPT_RETURNTRANSFER => 1,
810
            CURLOPT_URL => $this->getFileUrl().'/'.$file->getFilePath(),
811
        ];
812
813
        return $this->executeCurl($options);
814
    }
815
816
    /**
817
     * Use this method to send answers to an inline query. On success, True is returned.
818
     * No more than 50 results per query are allowed.
819
     *
820
     * @param string $inlineQueryId
821
     * @param AbstractInlineQueryResult[] $results
822
     * @param int $cacheTime
823
     * @param bool $isPersonal
824
     * @param string $nextOffset
825
     *
826
     * @return mixed
827
     * @throws Exception
828
     */
829
    public function answerInlineQuery($inlineQueryId, $results, $cacheTime = 300, $isPersonal = false, $nextOffset = '')
830
    {
831
        $results = array_map(function ($item) {
832
            /* @var AbstractInlineQueryResult $item */
833
834
            return json_decode($item->toJson(), true);
835
        }, $results);
836
837
        return $this->call('answerInlineQuery', [
838
            'inline_query_id' => $inlineQueryId,
839
            'results' => json_encode($results),
840
            'cache_time' => $cacheTime,
841
            'is_personal' => $isPersonal,
842
            'next_offset' => $nextOffset,
843
        ]);
844
    }
845
846
    /**
847
     * Use this method to kick a user from a group or a supergroup.
848
     * In the case of supergroups, the user will not be able to return to the group
849
     * on their own using invite links, etc., unless unbanned first.
850
     * The bot must be an administrator in the group for this to work. Returns True on success.
851
     *
852
     * @param int|string $chatId Unique identifier for the target group
853
     * or username of the target supergroup (in the format @supergroupusername)
854
     * @param int $userId Unique identifier of the target user
855
     *
856
     * @return bool
857
     */
858
    public function kickChatMember($chatId, $userId)
859
    {
860
        return $this->call('kickChatMember', [
861
            'chat_id' => $chatId,
862
            'user_id' => $userId,
863
        ]);
864
    }
865
866
    /**
867
     * Use this method to unban a previously kicked user in a supergroup.
868
     * The user will not return to the group automatically, but will be able to join via link, etc.
869
     * The bot must be an administrator in the group for this to work. Returns True on success.
870
     *
871
     * @param int|string $chatId Unique identifier for the target group
872
     * or username of the target supergroup (in the format @supergroupusername)
873
     * @param int $userId Unique identifier of the target user
874
     *
875
     * @return bool
876
     */
877
    public function unbanChatMember($chatId, $userId)
878
    {
879
        return $this->call('unbanChatMember', [
880
            'chat_id' => $chatId,
881
            'user_id' => $userId,
882
        ]);
883
    }
884
885
    /**
886
     * Use this method to send answers to callback queries sent from inline keyboards.
887
     * The answer will be displayed to the user as a notification at the top of the chat screen or as an alert.
888
     *
889
     * @param $callbackQueryId
890
     * @param null $text
891
     * @param bool $showAlert
892
     *
893
     * @return bool
894
     */
895
    public function answerCallbackQuery($callbackQueryId, $text = null, $showAlert = false)
896
    {
897
        return $this->call('answerCallbackQuery', [
898
            'callback_query_id' => $callbackQueryId,
899
            'text' => $text,
900
            'show_alert' => (bool)$showAlert,
901
        ]);
902
    }
903
904
905
    /**
906
     * Use this method to edit text messages sent by the bot or via the bot
907
     *
908
     * @param int|string $chatId
909
     * @param int $messageId
910
     * @param string $text
911
     * @param string|null $parseMode
912
     * @param bool $disablePreview
913
     * @param Types\ReplyKeyboardMarkup|Types\ReplyKeyboardHide|Types\ForceReply|null $replyMarkup
914
     *
915
     * @return \TelegramBot\Api\Types\Message
916
     * @throws \TelegramBot\Api\InvalidArgumentException
917
     * @throws \TelegramBot\Api\Exception
918
     */
919 View Code Duplication
    public function editMessageText(
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...
920
        $chatId,
921
        $messageId,
922
        $text,
923
        $parseMode = null,
924
        $disablePreview = false,
925
        $replyMarkup = null
926
    ) {
927
        return Message::fromResponse($this->call('editMessageText', [
928
            'chat_id' => $chatId,
929
            'message_id' => $messageId,
930
            'text' => $text,
931
            'parse_mode' => $parseMode,
932
            'disable_web_page_preview' => $disablePreview,
933
            'reply_markup' => $replyMarkup,
934
        ]));
935
    }
936
937
    /**
938
     * Use this method to edit text messages sent by the bot or via the bot
939
     *
940
     * @param int|string $chatId
941
     * @param int $messageId
942
     * @param string|null $caption
943
     * @param Types\ReplyKeyboardMarkup|Types\ReplyKeyboardHide|Types\ForceReply|null $replyMarkup
944
     *
945
     * @return \TelegramBot\Api\Types\Message
946
     * @throws \TelegramBot\Api\InvalidArgumentException
947
     * @throws \TelegramBot\Api\Exception
948
     */
949
    public function editMessageCaption(
950
        $chatId,
951
        $messageId,
952
        $caption = null,
953
        $replyMarkup = null
954
    ) {
955
        return Message::fromResponse($this->call('editMessageCaption', [
956
            'chat_id' => $chatId,
957
            'message_id' => $messageId,
958
            'caption' => $caption,
959
            'reply_markup' => $replyMarkup,
960
        ]));
961
    }
962
963
    /**
964
     * Use this method to edit only the reply markup of messages sent by the bot or via the bot
965
     *
966
     * @param int|string $chatId
967
     * @param int $messageId
968
     * @param Types\ReplyKeyboardMarkup|Types\ReplyKeyboardHide|Types\ForceReply|null $replyMarkup
969
     *
970
     * @return \TelegramBot\Api\Types\Message
971
     * @throws \TelegramBot\Api\InvalidArgumentException
972
     * @throws \TelegramBot\Api\Exception
973
     */
974
    public function editMessageReplyMarkup(
975
        $chatId,
976
        $messageId,
977
        $replyMarkup = null
978
    ) {
979
        return Message::fromResponse($this->call('editMessageText', [
980
            'chat_id' => $chatId,
981
            'message_id' => $messageId,
982
            'reply_markup' => $replyMarkup,
983
        ]));
984
    }
985
986
    /**
987
     * Close curl
988
     */
989 9
    public function __destruct()
990
    {
991 9
        $this->curl && curl_close($this->curl);
992 9
    }
993
994
    /**
995
     * @return string
996
     */
997
    public function getUrl()
998
    {
999
        return self::URL_PREFIX.$this->token;
1000
    }
1001
1002
    /**
1003
     * @return string
1004
     */
1005
    public function getFileUrl()
1006
    {
1007
        return self::FILE_URL_PREFIX.$this->token;
1008
    }
1009
1010
    /**
1011
     * @param \TelegramBot\Api\Types\Update $update
1012
     * @param string $eventName
1013
     *
1014
     * @throws \TelegramBot\Api\Exception
1015
     */
1016
    public function trackUpdate(Update $update, $eventName = 'Message')
1017
    {
1018
        if (!in_array($update->getUpdateId(), $this->trackedEvents)) {
1019
            $this->trackedEvents[] = $update->getUpdateId();
1020
1021
            $this->track($update->getMessage(), $eventName);
1022
1023
            if (count($this->trackedEvents) > self::MAX_TRACKED_EVENTS) {
1024
                $this->trackedEvents = array_slice($this->trackedEvents, round(self::MAX_TRACKED_EVENTS / 4));
1025
            }
1026
        }
1027
    }
1028
1029
    /**
1030
     * Wrapper for tracker
1031
     *
1032
     * @param \TelegramBot\Api\Types\Message $message
1033
     * @param string $eventName
1034
     *
1035
     * @throws \TelegramBot\Api\Exception
1036
     */
1037
    public function track(Message $message, $eventName = 'Message')
1038
    {
1039
        if ($this->tracker instanceof Botan) {
1040
            $this->tracker->track($message, $eventName);
1041
        }
1042
    }
1043
}
1044