Completed
Push — master ( b0a42f...2d9ddd )
by Danilo
01:59
created

CoreBot::forwardMessage()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 12
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 12
rs 9.4285
cc 1
eloc 7
nc 1
nop 3
1
<?php
2
3
namespace DanySpin97\PhpBotFramework;
4
5
6
/**
7
 * \mainpage
8
 * \section Description
9
 * PhpBotFramework a lightweight framework for Telegram Bot API.
10
 * Designed to be fast and easy to use, it provides all the features a user need.
11
 * Take control of your bot using the command-handler system or the update type based function.
12
 *
13
 * \subsection Example
14
 * A quick example, the bot will send "Hello" every time the user click "/start":
15
 *
16
 *     <?php
17
 *
18
 *     // Include the framework
19
 *     require './vendor/autoload.php';
20
 *
21
 *     // Create the bot
22
 *     $bot = new DanySpin97\PhpBotFramework\Bot("token");
23
 *
24
 *     // Add a command that will be triggered every time the user click /start
25
 *     $bot->addMessageCommand("start",
26
 *         function($bot, $message) {
27
 *             $bot->sendMessage("Hello");
28
 *         }
29
 *     );
30
 *
31
 *     // Receive update from telegram using getUpdates
32
 *     $bot->getUpdatesLocal();
33
 *
34
 * \section Features
35
 * - Designed to be the fast and easy to use
36
 * - Support for getUpdates and webhooks
37
 * - Support for the most important API methods
38
 * - Command-handle system for messages and callback queries
39
 * - Update type based processing
40
 * - Easy inline keyboard creation
41
 * - Inline query results handler
42
 * - Sql database support
43
 * - Redis support
44
 * - Support for multilanguage bot
45
 * - Support for bot state
46
 * - Highly documented
47
 *
48
 * \section Requirements
49
 * - Php 7.0 or greater
50
 * - php-mbstring
51
 * - Composer (to install the framework)
52
 * - SSL certificate (<i>required by webhook</i>)
53
 * - Web server (<i>required by webhook</i>)
54
 *
55
 * \section Installation
56
 * In your project folder:
57
 *
58
 *     composer require danyspin97/php-bot-framework
59
 *     composer install --no-dev
60
 *
61
 * \subsection Web-server
62
 * To use webhook for the bot, a web server and a SSL certificate are required.
63
 * Install one using your package manager (nginx or caddy reccomended).
64
 * To get a SSL certificate you can user [Let's Encrypt](https://letsencrypt.org/).
65
 *
66
 * \section Usage
67
 * Add the scripting by adding command (Bot::addMessageCommand()) or by creating a class that inherits Bot.
68
 * Each api call will have <code>$chat_id</code> set to the current user, use CoreBot::setChatID() to change it.
69
 *
70
 * \subsection getUpdates
71
 * The bot ask for updates to telegram server.
72
 * If you want to use getUpdates method to receive updates from telegram, add one of these function at the end of your bot:
73
 * - Bot::getUpdatesLocal()
74
 * - Bot::getUpdatesDatabase()
75
 * - Bot::getUpdatesRedis()
76
 *
77
 * The bot will process updates in a row, and will call Bot::processUpdate() for each.
78
 * getUpdates handling is single-threaded so there will be only one object that will process updates. The connection will be opened at the creation and used for the entire life of the bot.
79
 *
80
 * \subsection Webhook
81
 * A web server will create an instance of the bot for every update received.
82
 * If you want to use webhook call Bot::processWebhookUpdate() at the end of your bot. The bot will get data from <code>php://input</code> and process it using Bot::processUpdate().
83
 * Each instance of the bot will open its connection.
84
 *
85
 * \subsection Message-commands Message commands
86
 * Script how the bot will answer to messages containing commands (like <code>/start</code>).
87
 *
88
 *     $bot->addMessageCommand("start", function($bot, $message) {
89
 *             $bot->sendMessage("I am your personal bot, try /help command");
90
 *     });
91
 *
92
 *     $help_function = function($bot, $message) {
93
 *         $bot->sendMessage("This is the help message")
94
 *     };
95
 *
96
 *     $bot->addMessageCommand("/help", $help_function);
97
 *
98
 * Check Bot::addMessageCommand() for more.
99
 *
100
 * You can also use regex to check commands.
101
 *
102
 * The closure will be called if the commands if the expression evaluates to true. Here is an example:
103
 *
104
 *     $bot->addMessageCommandRegex("number\d",
105
 *         $help_function);
106
 *
107
 * The closure will be called when the user send a command that match the regex like, in this example, both <code>/number1</code> or <code>/number135</code>.
108
 *
109
 * \subsection Callback-commands Callback commands
110
 * Script how the bot will answer to callback query containing a particular string as data.
111
 *
112
 *     $bot->addCallbackCommand("back", function($bot, $callback_query) {
113
 *             $bot->editMessageText($callback_query['message']['message_id'], "You pressed back");
114
 *     });
115
 *
116
 * Check Bot::addCallbackCommand() for more.
117
 *
118
 * \subsection Bot-Intherited Inherit Bot Class
119
 * Create a new class that inherits Bot to handle all updates.
120
 *
121
 * <code>EchoBot.php</code>
122
 *
123
 *     // Create the class that will extends Bot class
124
 *     class EchoBot extends DanySpin97\PhpBotFramework\Bot {
125
 *
126
 *         // Add the function for processing messages
127
 *         protected function processMessage($message) {
128
 *
129
 *             // Answer each message with the text received
130
 *             $this->sendMessage($message['text']);
131
 *
132
 *         }
133
 *
134
 *     }
135
 *
136
 *     // Create an object of type EchoBot
137
 *     $bot = new EchoBot("token");
138
 *
139
 *     // Process updates using webhook
140
 *     $bot->processWebhookUpdate();
141
 *
142
 * Override these method to make your bot handle each update type:
143
 * - Bot::processMessage($message)
144
 * - Bot::processCallbackQuery($callback_query)
145
 * - Bot::processInlineQuery($inline_query)
146
 * - Bot::processChosenInlineResult($chosen_inline_result)
147
 * - Bot::processEditedMessage($edited_message)
148
 * - Bot::processChannelPost($post)
149
 * - Bot::processEditedChannelPost($edited_post)
150
 *
151
 * \subsection InlineKeyboard-Usage InlineKeyboard Usage
152
 *
153
 * How to use the InlineKeyboard class:
154
 *
155
 *     // Create the bot
156
 *     $bot = new DanySpin97\PhpBotFramework\Bot("token");
157
 *
158
 *     $command_function = function($bot, $message) {
159
 *             // Add a button to the inline keyboard
160
 *             $bot->inline_keyboard->addLevelButtons([
161
 *                  // with written "Click me!"
162
 *                  'text' => 'Click me!',
163
 *                  // and that open the telegram site, if pressed
164
 *                  'url' => 'telegram.me'
165
 *                  ]);
166
 *             // Then send a message, with our keyboard in the parameter $reply_markup of sendMessage
167
 *             $bot->sendMessage("This is a test message", $bot->inline_keyboard->get());
168
 *             }
169
 *
170
 *     // Add the command
171
 *     $bot->addMessageCommand("start", $command_function);
172
 *
173
 * \subsection Sql-Database Sql Database
174
 * The sql database is used to save offset from getUpdates and to save user language.
175
 *
176
 * To connect a sql database to the bot, a pdo connection is required.
177
 *
178
 * Here is a simple pdo connection that is passed to the bot:
179
 *
180
 *     $bot->pdo = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
181
 *
182
 * \subsection Redis-database Redis Database
183
 * Redis is used to save offset from getUpdates, to store language (both as cache and persistent) and to save bot state.
184
 *
185
 * To connect redis with the bot, create a redis object.
186
 *
187
 *     $bot->redis = new Redis();
188
 *
189
 * \subsection Multilanguage-section Multilanguage Bot
190
 * This framework offers method to develop a multi language bot.
191
 *
192
 * Here's an example:
193
 *
194
 * <code>en.json</code>:
195
 *
196
 *     {"Greetings_Msg": "Hello"}
197
 *
198
 * <code>it.json</code>:
199
 *
200
 *     {"Greetings_Msg": "Ciao"}
201
 *
202
 * <code>Greetings.php</code>:
203
 *
204
 *     $bot->loadLocalization();
205
 *     $start_function = function($bot, $message) {
206
 *             $bot->sendMessage($this->localization[
207
 *                     $bot->getLanguageDatabase()]['Greetings_Msg'])
208
 *     };
209
 *
210
 *     $bot->addMessageCommand("start", $start_function);
211
 *
212
 * The bot will get the language from the database, then the bot will send the message localizated for the user.
213
 *
214
 * \ref Multilanguage [See here for more]
215
 *
216
 * \section Source
217
 * The source is hosted on github and can be found [here](https://github.com/DanySpin97/PhpBotFramework).
218
 *
219
 * \section Bot-created Bot using this framework
220
 * - [\@MyAddressBookBot](https://telegram.me/myaddressbookbot) ([Source](https://github.com/DanySpin97/MyAddressBookBot))
221
 * - [\@Giveaways_bot](https://telegram.me/giveaways_bot) ([Source](https://github.com/DanySpin97/GiveawaysBot))
222
 *
223
 * \section Authors
224
 * This framework is developed and manteined by Danilo Spinella.
225
 *
226
 * \section License
227
 * PhpBotFramework is released under GNU Lesser General Public License.
228
 * You may copy, distribute and modify the software provided that modifications are described and licensed for free under LGPL-3. Derivatives works (including modifications) can only be redistributed under LGPL-3, but applications that use the wrapper don't have to be.
229
 *
230
 */
231
232
/**
233
 * \class CoreBot
234
 * \brief Core of the framework
235
 * \details Contains data used by the bot to works, curl request handling, and all api methods (sendMessage, editMessageText, etc).
236
 */
237
class CoreBot {
238
239
    /**
240
     * \addtogroup Bot Bot
241
     * @{
242
     */
243
244
    /** \brief Chat_id of the user that interacted with the bot */
245
    protected $chat_id;
246
247
    /** @} */
248
249
    /**
250
     * \addtogroup Core Core(Internal)
251
     * \brief Core of the framework.
252
     * @{
253
     */
254
255
    /** \brief The bot token (given by @BotFather). */
256
    private $token;
257
258
    /** \brief Url request (containing $token). */
259
    protected $api_url;
260
261
    /** \brief Curl connection for request. */
262
    public $ch;
263
264
    /** \brief Store id of the callback query received. */
265
    protected $_callback_query_id;
266
267
    /**
268
     * \brief Contrusct an empty bot.
269
     * \details Construct a bot passing the token.
270
     * @param $token Token given by @botfather.
271
     */
272
    public function __construct(string $token) {
273
274
        // Check token is valid
275
        if (is_numeric($token) || $token === '') {
276
            throw new BotException('Token is not valid or empty');
277
            return;
0 ignored issues
show
Unused Code introduced by
return; does not seem to be reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
278
        }
279
280
        // Init variables
281
        $this->token = $token;
282
        $this->api_url = 'https://api.telegram.org/bot' . $token . '/';
283
284
        // Init connection and config it
285
        $this->ch = curl_init();
286
        curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, 1);
287
        curl_setopt($this->ch, CURLOPT_CONNECTTIMEOUT, 5);
288
        curl_setopt($this->ch, CURLOPT_SSL_VERIFYPEER, false);
289
        curl_setopt($this->ch, CURLOPT_TIMEOUT, 60);
290
        curl_setopt($this->ch, CURLOPT_HEADER, 0);
291
        curl_setopt($this->ch, CURLOPT_ENCODING, '');
292
        // DEBUG
293
        //curl_setopt($this->ch, CURLOPT_VERBOSE, true);
0 ignored issues
show
Unused Code Comprehensibility introduced by
62% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
294
295
    }
296
297
    /** \brief Destroy the object. */
298
    public function __destruct() {
299
300
        // Close connection
301
        curl_close($this->ch);
302
303
    }
304
305
    /** @} */
306
307
    /**
308
     * \addtogroup Bot Bot
309
     * @{
310
     */
311
312
    /**
313
     * \brief Get chat id of the current user.
314
     * @return Chat id of the user.
315
     */
316
    public function getChatID() {
317
318
        return $this->chat_id;
319
320
    }
321
322
    /**
323
     * \brief Set current chat id.
324
     * \details Change the chat id which the bot execute api methods.
325
     * @param $chat_id The new chat id to set.
326
     */
327
    public function setChatID($chat_id) {
328
329
        $this->chat_id = $chat_id;
330
331
    }
332
333
    /**
334
     * \brief Get bot ID using getMe API method.
335
     */
336
    public function getBotID() : int {
337
338
        // Get the id of the bot
339
        static $bot_id;
340
        $bot_id = ($this->getMe())['id'];
341
342
        // If it is not valid
343
        if(!isset($bot_id) || $bot_id == 0) {
344
345
            // get it again
346
            $bot_id = ($this->getMe())['id'];
347
348
        }
349
350
        return $bot_id ?? 0;
351
352
    }
353
354
    /** @} */
355
356
    /**
357
     * \addtogroup Api Api Methods
358
     * \brief All api methods to interface the bot with Telegram.
359
     * @{
360
     */
361
362
    /**
363
     * \brief A simple method for testing your bot's auth token.
364
     * \details Requires no parameters. Returns basic information about the bot in form of a User object. [Api reference](https://core.telegram.org/bots/api#getme)
365
     */
366
    public function getMe() {
367
368
        return $this->exec_curl_request($this->api_url . 'getMe?');
369
370
    }
371
372
373
    /**
374
     * \brief Request bot updates.
375
     * \details Request updates received by the bot using method getUpdates of Telegram API. [Api reference](https://core.telegram.org/bots/api#getupdates)
376
     * @param $offset <i>Optional</i>. Identifier of the first update to be returned. Must be greater by one than the highest among the identifiers of previously received updates. By default, updates starting with the earliest unconfirmed update are returned. An update is considered confirmed as soon as getUpdates is called with an offset higher than its update_id. The negative offset can be specified to retrieve updates starting from -offset update from the end of the updates queue. All previous updates will forgotten.
377
     * @param $limit <i>Optional</i>. Limits the number of updates to be retrieved. Values between 1—100 are accepted.
378
     * @param $timeout <i>Optional</i>. Timeout in seconds for long polling.
379
     * @return Array of updates (can be empty).
380
     */
381
    public function getUpdates(int $offset = 0, int $limit = 100, int $timeout = 60) {
382
383
        $parameters = [
384
            'offset' => $offset,
385
            'limit' => $limit,
386
            'timeout' => $timeout,
387
        ];
388
389
        return $this->exec_curl_request($this->api_url . 'getUpdates?' . http_build_query($parameters));
390
391
    }
392
393
    /**
394
     * \brief Set updates received by the bot for getUpdates handling.
395
     * \details List the types of updates you want your bot to receive. For example, specify [“message”, “edited_channel_post”, “callback_query”] to only receive updates of these types. Specify an empty list to receive all updates regardless of type.
396
     * Set it one time and it won't change until next setUpdateReturned call.
397
     * @param $allowed_updates <i>Optional</i>. List of updates allowed.
398
     */
399
    public function setUpdateReturned(array $allowed_updates = []) {
400
401
        // Parameter for getUpdates
402
        $parameters = [
403
            'offset' => 0,
404
            'limit' => 1,
405
            'timeout' => 0,
406
        ];
407
408
        // Start the list
409
        $updates_string = '[';
410
411
        // Flag to skip adding ", " to the string
412
        $first_string = true;
413
414
        // Iterate over the list
415
        foreach ($allowed_updates as $index => $update) {
416
417
            // Is it the first update added?
418
            if (!$first_string) {
419
420
                $updates_string .= ', "' . $update . '"';
421
422
            } else {
423
424
                $updates_string .= '"' . $update . '"';
425
426
                // Set the flag to false cause we added an item
427
                $first_string = false;
428
429
            }
430
431
        }
432
433
        // Close string with the marker
434
        $updates_string .= ']';
435
436
        // Exec getUpdates
437
        $this->exec_curl_request($this->api_url . 'getUpdates?' . http_build_query($parameters) . '&allowed_updates=' . $updates_string);
438
439
    }
440
441
    /**
442
     * \brief Send a text message.
443
     * \details Use this method to send text messages. [Api reference](https://core.telegram.org/bots/api#sendmessage)
444
     * @param $text Text of the message.
445
     * @param $reply_markup <i>Optional</i>. Reply_markup of the message.
446
     * @param $parse_mode <i>Optional</i>. Parse mode of the message.
447
     * @param $disable_web_preview <i>Optional</i>. Disables link previews for links in this message.
448
     * @param $disable_notification <i>Optional</i>. Sends the message silently.
449
     * @return On success,  the sent message.
450
     */
451
    public function sendMessage($text, string $reply_markup = null, int $reply_to = null, string $parse_mode = 'HTML', bool $disable_web_preview = true, bool $disable_notification = false) {
452
453
        $parameters = [
454
            'chat_id' => $this->chat_id,
455
            'text' => $text,
456
            'parse_mode' => $parse_mode,
457
            'disable_web_page_preview' => $disable_web_preview,
458
            'reply_markup' => $reply_markup,
459
            'reply_to_message_id' => $reply_to,
460
            'disable_notification' => $disable_notification
461
        ];
462
463
        return $this->exec_curl_request($this->api_url . 'sendMessage?' . http_build_query($parameters));
464
465
    }
466
467
    /**
468
     * \brief Forward a message.
469
     * \details Use this method to forward messages of any kind. [Api reference](https://core.telegram.org/bots/api#forwardmessage)
470
     * @param $from_chat_id The chat where the original message was sent.
471
     * @param $message_id Message identifier (id).
472
     * @param $disable_notification <i>Optional</i>. Sends the message silently.
473
     * @return On success,  the sent message.
474
     */
475
    public function forwardMessage($from_chat_id, int $message_id, bool $disable_notification = false) {
476
477
        $parameters = [
478
            'chat_id' => $this->chat_id,
479
            'message_id' => $message_id,
480
            'from_chat_id' => $from_chat_id,
481
            'disable_notification' => $disable_notification
482
        ];
483
484
        return $this->exec_curl_request($this->api_url . 'forwardMessage?' . http_build_query($parameters));
485
486
    }
487
488
    /**
489
     * \brief Send a photo.
490
     * \details Use this method to send photos. [Api reference](https://core.telegram.org/bots/api#sendphoto)
491
     * @param $photo Photo to send, can be a file_id or a string referencing the location of that image.
492
     * @param $reply_markup <i>Optional</i>. Reply markup of the message.
493
     * @param $caption <i>Optional</i>. Photo caption (may also be used when resending photos by file_id), 0-200 characters.
494
     * @param $disable_notification <i>Optional<i>. Sends the message silently.
495
     * @return On success,  the sent message.
496
     */
497
    public function sendPhoto($photo, string $reply_markup = null, string $caption = '', bool $disable_notification = false) {
498
499
        $parameters = [
500
            'chat_id' => $this->chat_id,
501
            'photo' => $photo,
502
            'caption' => $caption,
503
            'reply_markup' => $reply_markup,
504
            'disable_notification' => $disable_notification,
505
        ];
506
507
        return $this->exec_curl_request($this->api_url . 'sendPhoto?' . http_build_query($parameters));
508
509
    }
510
511
    /**
512
     * \brief Send an audio.
513
     * \details Use this method to send audio files, if you want Telegram clients to display them in the music player. Your audio must be in the .mp3 format. [Api reference](https://core.telegram.org/bots/api/#sendaudio)
514
     * Bots can currently send audio files of up to 50 MB in size, this limit may be changed in the future.
515
     * @param $audio Audio file to send. Pass a file_id as String to send an audio file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get an audio file from the Internet, or upload a new one using multipart/form-data.
516
     * @param $caption <i>Optional</i>. Audio caption, 0-200 characters.
517
     * @param $reply_markup <i>Optional</i>. Reply markup of the message.
518
     * @param $duration <i>Optional</i>. Duration of the audio in seconds.
519
     * @param $performer <i>Optional</i>. Performer.
520
     * @param $title <i>Optional</i>. Track name.
521
     * @param $disable_notification <i>Optional</i>. Sends the message silently.
522
     * @param $reply_to_message_id <i>Optional</i>. If the message is a reply, ID of the original message.
523
     * @return On success, the sent message.
524
     */
525
    public function sendAudio($audio, string $caption = null, string $reply_markup = null, int $duration = null, string $title = null, bool $disable_notification = false, int $reply_to_message_id = null) {
0 ignored issues
show
Unused Code introduced by
The parameter $audio is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
526
527
        $parameters = [
528
            'chat_id' => $this->chat_id,
529
            'audio' => $photo,
0 ignored issues
show
Bug introduced by
The variable $photo does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
530
            'caption' => $caption,
531
            'duration' => $duration,
532
            'performer' => $performer,
0 ignored issues
show
Bug introduced by
The variable $performer does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
533
            'title' => $title,
534
            'reply_to_message_id' => $reply_to_message_id,
535
            'reply_markup' => $reply_markup,
536
            'disable_notification' => $disable_notification,
537
        ];
538
539
        return $this->exec_curl_request($this->api_url . 'sendAudio?' . http_build_query($parameters));
540
541
    }
542
543
    /**
544
     * \brief Send a document.
545
     * \details Use this method to send general files. [Api reference](https://core.telegram.org/bots/api/#senddocument)
546
     * @param $document File to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data.
547
     * @param <i>Optional</i>. Document caption (may also be used when resending documents by file_id), 0-200 characters.
548
     *
549
     * @param $reply_markup <i>Optional</i>. Reply markup of the message.
550
     * @param <i>Optional</i>. Sends the message silently.
551
     * @param <i>Optional</i>. If the message is a reply, ID of the original message.
552
     */
553
    public function sendDocument($document, string $caption = '', string $reply_markup = null, bool $disable_notification = false, int $reply_to_message_id = null) {
0 ignored issues
show
Unused Code introduced by
The parameter $document is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
554
555
        $parameters = [
556
            'chat_id' => $this->chat_id,
557
            'document' => $photo,
0 ignored issues
show
Bug introduced by
The variable $photo does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
558
            'caption' => $caption,
559
            'reply_to_message_id' => $reply_to_message_id,
560
            'reply_markup' => $reply_markup,
561
            'disable_notification' => $disable_notification,
562
        ];
563
564
        return $this->exec_curl_request($this->api_url . 'sendAudio?' . http_build_query($parameters));
565
566
    }
567
568
569
    /**
570
     * \brief Send a sticker
571
     * \details Use this method to send .webp stickers. [Api reference](https://core.telegram.org/bots/api/#sendsticker)
572
     * @param $sticker Sticker to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a .webp file from the Internet, or upload a new one using multipart/form-data.
573
     * @param $reply_markup <i>Optional</i>. Reply markup of the message.
574
     * @param $disable_notification Sends the message silently.
575
     * @param <i>Optional</i>. If the message is a reply, ID of the original message.
576
     * @param On success, the sent message.
577
     */
578
    public function sendSticker($sticker, string $reply_markup = null, bool $disable_notification = false, int $reply_to_message_id = null) {
579
580
        $parameters = [
581
            'chat_id' => $this->chat_id,
582
            'sticker' => $sticker,
583
            'disable_notification' => $disable_notification,
584
            'reply_to_message_id' => $reply_to_message_id,
585
            'reply_markup' => $reply_markup
586
        ];
587
588
        return $this->exec_curl_request($this->api_url . 'sendSticker?' . http_build_query($parameters));
589
590
    }
591
592
    /**
593
     * \brief Send audio files.
594
     * \details Use this method to send audio files, if you want Telegram clients to display the file as a playable voice message. For this to work, your audio must be in an .ogg file encoded with OPUS (other formats may be sent as Audio or Document).o
595
     * Bots can currently send voice messages of up to 50 MB in size, this limit may be changed in the future.
596
     * @param $voice Audio file to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data.
597
     * @param $caption <i>Optional</i>. Voice message caption, 0-200 characters
598
     * @param $duration <i>Optional</i>. Duration of the voice message in seconds
599
     * @param $reply_markup <i>Optional</i>. Reply markup of the message.
600
     * @param $disable_notification <i>Optional</i>. Sends the message silently.
601
     * @param $reply_to_message_id <i>Optional</i>. If the message is a reply, ID of the original message.
602
     * @return On success, the sent message is returned.
603
     */
604 View Code Duplication
    public function sendVoice($voice, string $caption, int $duration, string $reply_markup = null, bool $disable_notification, int $reply_to_message_id = 0) {
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...
605
606
        $parameters = [
607
            'chat_id' => $this->chat_id,
608
            'voice' => $voice,
609
            'caption' => $caption,
610
            'duration' => $duration,
611
            'disable_notification', $disable_notification,
612
            'reply_to_message_id' => $reply_to_message_id,
613
            'reply_markup' => $reply_markup
614
        ];
615
616
        return $this->exec_curl_request($this->api_url . 'sendVoice?' . http_build_query($parameters));
617
618
    }
619
620
    /**
621
     * \brief Say the user what action is the bot doing.
622
     * \details Use this method when you need to tell the user that something is happening on the bot's side. The status is set for 5 seconds or less (when a message arrives from your bot, Telegram clients clear its typing status). [Api reference](https://core.telegram.org/bots/api#sendchataction)
623
     * @param $action Type of action to broadcast. Choose one, depending on what the user is about to receive:
624
     * - <code>typing</code> for text messages
625
     * - <code>upload_photo</code> for photos
626
     * - <code>record_video</code> or <code>upload_video</code> for videos
627
     * - <code>record_audio</code> or <code>upload_audio</code> for audio files
628
     * - <code>upload_document</code> for general files
629
     * - <code>find_location</code> for location data
630
     * @return True on success.
631
     */
632 View Code Duplication
    public function sendChatAction(string $action) : bool {
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...
633
634
        $parameters = [
635
            'chat_id' => $this->chat_id,
636
            'action' => $action
637
        ];
638
639
        return $this->exec_curl_request($this->api_url . 'sendChatAction?' . http_build_query($parameters));
640
641
    }
642
643
    /**
644
     * \brief Get info about a chat.
645
     * \details 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.). [Api reference](https://core.telegram.org/bots/api#getchat)
646
     * @param Unique identifier for the target chat or username of the target supergroup or channel (in the format <code>@channelusername</code>)
647
     */
648 View Code Duplication
    public function getChat($chat_id) {
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...
649
650
        $parameters = [
651
            'chat_id' => $chat_id,
652
        ];
653
654
        return $this->exec_curl_request($this->api_url . 'getChat?' . http_build_query($parameters));
655
656
    }
657
658
    /**
659
     * \brief Use this method to get a list of administrators in a chat.
660
     * @param Unique identifier for the target chat or username of the target supergroup or channel (in the format <code>@channelusername</code>)
661
     * @return On success, returns an Array of ChatMember objects that contains information about all chat administrators except other bots. If the chat is a group or a supergroup and no administrators were appointed, only the creator will be returned.
662
     */
663
    public function getChatAdministrators($chat_id) {
664
665
        $parameters = [
666
            'chat_id' => $chat_id,
667
        ];
668
669
        return $this->exec_curl_request($this->api_url . 'getChatAdministrators?' . http_build_query($parameters));
670
671
    }
672
673
674
    /* \brief Answer a callback query
675
     * \details Remove the updating cirle on an inline keyboard button and showing a message/alert to the user.
676
     * It will always answer the current callback query.
677
     * @param $text <i>Optional</i>. Text of the notification. If not specified, nothing will be shown to the user, 0-200 characters.
678
     * @param $show_alert <i>Optional</i>. If true, an alert will be shown by the client instead of a notification at the top of the chat screen.
679
     * @param $url <i>Optional</i>. URL that will be opened by the user's client. If you have created a Game and accepted the conditions via @Botfather, specify the URL that opens your game – note that this will only work if the query comes from a callback_game button.
680
     * Otherwise, you may use links like telegram.me/your_bot?start=XXXX that open your bot with a parameter.
681
     * @return True on success.
682
     */
683
    public function answerCallbackQuery($text = '', $show_alert = false, string $url = '') : bool {
684
685
        if (!isset($this->_callback_query_id)) {
686
687
            throw new BotException("Callback query id not set, wrong update");
688
689
        }
690
691
        $parameters = [
692
            'callback_query_id' => $this->_callback_query_id,
693
            'text' => $text,
694
            'show_alert' => $show_alert,
695
            'url' => $url
696
        ];
697
698
        return $this->exec_curl_request($this->api_url . 'answerCallbackQuery?' . http_build_query($parameters));
699
700
    }
701
702
    /**
703
     * \brief Edit text of a message sent by the bot.
704
     * \details Use this method to edit text and game messages sent by the bot. [Api reference](https://core.telegram.org/bots/api#editmessagetext)
705
     * @param $message_id Unique identifier of the sent message.
706
     * @param $text New text of the message.
707
     * @param $reply_markup Reply markup of the message will have (will be removed if this is null).
708
     * @param $parse_mode <i>Optional</i>. Send Markdown or HTML.
709
     * @param $disable_web_preview <i>Optional</i>. Disables link previews for links in this message.
710
     */
711 View Code Duplication
    public function editMessageText(int $message_id, $text, $reply_markup = null, string $parse_mode = 'HTML', bool $disable_web_preview = true) {
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...
712
713
        $parameters = [
714
            'chat_id' => $this->chat_id,
715
            'message_id' => $message_id,
716
            'text' => $text,
717
            'reply_markup' => $reply_markup,
718
            'parse_mode' => $parse_mode,
719
            'disable_web_page_preview' => $disable_web_preview,
720
        ];
721
722
        return $this->exec_curl_request($this->api_url . 'editMessageText?' . http_build_query($parameters));
723
724
    }
725
726
    /**
727
     * \brief Edit text of a message sent via the bot.
728
     * \details Use this method to edit text messages sent via the bot (for inline queries). [Api reference](https://core.telegram.org/bots/api#editmessagetext)
729
     * @param $inline_message_id  Identifier of the inline message.
730
     * @param $text New text of the message.
731
     * @param $reply_markup Reply markup of the message will have (will be removed if this is null).
732
     * @param $parse_mode <i>Optional</i>. Send Markdown or HTML.
733
     * @param $disable_web_preview <i>Optional</i>. Disables link previews for links in this message.
734
     */
735
    public function editInlineMessageText(string $inline_message_id, $text, string $reply_markup = null, string $parse_mode = 'HTML', bool $disable_web_preview = false) {
0 ignored issues
show
Unused Code introduced by
The parameter $reply_markup is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
736
737
        $parameters = [
738
           'inline_message_id' => $inline_message_id,
739
           'text' => $text,
740
           'reply_markup' => $inline_keyboard,
0 ignored issues
show
Bug introduced by
The variable $inline_keyboard does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
741
           'parse_mode' => $parse_mode,
742
           'disable_web_page_preview' => $disable_web_preview,
743
        ];
744
745
        return $this->exec_curl_request($this->api_url . 'editMessageText?' . http_build_query($parameters));
746
747
    }
748
749
    /*
750
     * Edit only the inline keyboard of a message (https://core.telegram.org/bots/api#editmessagereplymarkup)ù
751
     * @param
752
     * $message_id Identifier of the message to edit
753
     * $inline_keyboard Inlike keyboard array (https://core.telegram.org/bots/api#inlinekeyboardmarkup)
754
     */
755 View Code Duplication
    public function editMessageReplyMarkup($message_id, $inline_keyboard) {
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...
756
757
        $parameters = [
758
            'chat_id' => $this->chat_id,
759
            'message_id' => $message_id,
760
            'reply_markup' => $inline_keyboard,
761
        ];
762
763
        return $this->exec_curl_request($this->api_url . 'editMessageReplyMarkup?' . http_build_query($parameters));
764
765
    }
766
767
    /*
768
     * Answer a inline query (when the user write @botusername "Query") with a button, that will make user switch to the private chat with the bot, on the top of the results (https://core.telegram.org/bots/api#answerinlinequery)
769
     * @param
770
     * $results Array on InlineQueryResult (https://core.telegram.org/bots/api#inlinequeryresult)
771
     * $switch_pm_text Text to show on the button
772
     */
773 View Code Duplication
    public function answerInlineQuerySwitchPM($results, $switch_pm_text, $switch_pm_parameter = '', $is_personal = true, $cache_time = 300) {
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...
774
775
        $parameters = [
776
            'inline_query_id' => $this->update['inline_query']['id'],
0 ignored issues
show
Bug introduced by
The property update does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
777
            'switch_pm_text' => $switch_pm_text,
778
            'is_personal' => $is_personal,
779
            'switch_pm_parameter' => $switch_pm_parameter,
780
            'results' => $results,
781
            'cache_time' => $cache_time
782
        ];
783
784
        return $this->exec_curl_request($this->api_url . 'answerInlineQuery?' . http_build_query($parameters));
785
786
    }
787
788
    /*
789
     * Answer a inline query (when the user write @botusername "Query") with a button, that will make user switch to the private chat with the bot, on the top of the results (https://core.telegram.org/bots/api#answerinlinequery)
790
     * without showing any results to the user
791
     * @param
792
     * $switch_pm_text Text to show on the button
793
     */
794 View Code Duplication
    public function answerEmptyInlineQuerySwitchPM($switch_pm_text, $switch_pm_parameter = '', $is_personal = true, $cache_time = 300) {
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...
795
        $parameters = [
796
            'inline_query_id' => $this->update['inline_query']['id'],
797
            'switch_pm_text' => $switch_pm_text,
798
            'is_personal' => $is_personal,
799
            'switch_pm_parameter' => $switch_pm_parameter,
800
            'cache_time' => $cache_time
801
        ];
802
803
        return $this->exec_curl_request($this->api_url . 'answerInlineQuery?' . http_build_query($parameters));
804
805
    }
806
807
    /**
808
     * \brief Exec any api request using this method.
809
     * \details Use this method for custom api calls using this syntax:
810
     *
811
     *     $param = [
812
     *             'chat_id' => $chat_id,
813
     *             'text' => 'Hello!'
814
     *     ];
815
     *     apiRequest("sendMessage", $param);
816
     *
817
     * @param $method The method to call.
818
     * @param $parameters Parameters to add.
819
     * @return Depends on api method.
820
     */
821
    public function apiRequest(string $method, array $parameters) {
822
823
        return $this->exec_curl_request($this->api_url . $method . '?' . http_build_query($parameters));
824
825
    }
826
827
    /** @} */
828
829
    /**
830
     * \addtogroup Core Core(internal)
831
     * @{
832
     */
833
834
    /** \brief Core function to execute url request.
835
     * @param $url The url to call using the curl session.
836
     * @return Url response, false on error.
837
     */
838
    protected function exec_curl_request($url) {
839
840
        // Set the url
841
        curl_setopt($this->ch, CURLOPT_URL, $url);
842
843
        $response = curl_exec($this->ch);
844
845
        if ($response === false) {
846
            $errno = curl_errno($this->ch);
847
            $error = curl_error($this->ch);
848
            error_log("Curl returned error $errno: $error\n");
849
            return false;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return false; (false) is incompatible with the return type documented by DanySpin97\PhpBotFramewo...eBot::exec_curl_request of type DanySpin97\PhpBotFramework\Url.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
850
        }
851
852
        $http_code = intval(curl_getinfo($this->ch, CURLINFO_HTTP_CODE));
853
854
        if ($http_code === 200) {
855
            $response = json_decode($response, true);
856
            if (isset($response['desc'])) {
857
                error_log("Request was successfull: {$response['description']}\n");
858
            }
859
            return $response['result'];
860
        } elseif ($http_code >= 500) {
861
            // do not wat to DDOS server if something goes wrong
862
            sleep(10);
863
            return false;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return false; (false) is incompatible with the return type documented by DanySpin97\PhpBotFramewo...eBot::exec_curl_request of type DanySpin97\PhpBotFramework\Url.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
864
        } elseif ($http_code !== 200) {
865
            $response = json_decode($response, true);
866
            error_log("Request has failed with error {$response['error_code']}: {$response['description']}\n");
867
            if ($http_code === 401) {
868
                throw new BotException('Invalid access token provided');
869
            }
870
            return false;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return false; (false) is incompatible with the return type documented by DanySpin97\PhpBotFramewo...eBot::exec_curl_request of type DanySpin97\PhpBotFramework\Url.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
871
        }
872
873
        return $response;
874
    }
875
876
    /** @} */
877
878
}
879
880