Completed
Pull Request — master (#18)
by
unknown
06:47
created

CoreBot::editMessageText()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 14
Code Lines 9

Duplication

Lines 14
Ratio 100 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 14
loc 14
rs 9.4285
cc 1
eloc 9
nc 1
nop 5
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 Implements interface for execute HTTP requests. */
262
    protected $http;
263
264
    /** \brief Store id of the callback query received. */
265
    protected $_callback_query_id;
266
267
    /** \brief Store id of the inline query received. */
268
    protected $_inline_query_id;
269
270
    /**
271
     * \brief Contrusct an empty bot.
272
     * \details Construct a bot passing the token.
273
     * @param $token Token given by @botfather.
274
     */
275
    public function __construct(string $token) {
276
277
        // Check token is valid
278
        if (is_numeric($token) || $token === '') {
279
280
            throw new BotException('Token is not valid or empty');
281
282
        }
283
284
        // Init variables
285
        $this->token = $token;
286
        $this->_api_url = 'https://api.telegram.org/bot' . $token . '/';
287
288
        // Init connection and config it
289
        $this->http = new \GuzzleHttp\Client([
290
            'base_uri' => $this->_api_url,
291
            'connect_timeout' => 5,
292
            'verify' => false,
293
            'timeout' => 60
294
        ]);
295
296
        return;
297
    }
298
299
    /** @} */
300
301
    /**
302
     * \addtogroup Bot Bot
303
     * @{
304
     */
305
306
    /**
307
     * \brief Get chat id of the current user.
308
     * @return Chat id of the user.
309
     */
310
    public function getChatID() {
311
312
        return $this->_chat_id;
313
314
    }
315
316
    /**
317
     * \brief Set current chat id.
318
     * \details Change the chat id which the bot execute api methods.
319
     * @param $_chat_id The new chat id to set.
320
     */
321
    public function setChatID($_chat_id) {
322
323
        $this->_chat_id = $_chat_id;
324
325
    }
326
327
    /**
328
     * \brief Get bot ID using getMe API method.
329
     */
330
    public function getBotID() : int {
331
332
        // Get the id of the bot
333
        static $bot_id;
334
        $bot_id = ($this->getMe())['id'];
335
336
        // If it is not valid
337
        if (!isset($bot_id) || $bot_id == 0) {
338
339
            // get it again
340
            $bot_id = ($this->getMe())['id'];
341
342
        }
343
344
        return $bot_id ?? 0;
345
346
    }
347
348
    /** @} */
349
350
    /**
351
     * \addtogroup Api Api Methods
352
     * \brief All api methods to interface the bot with Telegram.
353
     * @{
354
     */
355
356
    /**
357
     * \brief A simple method for testing your bot's auth token.
358
     * \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)
359
     */
360
    public function getMe() {
361
362
        return $this->exec_curl_request('getMe?');
363
364
    }
365
366
367
    /**
368
     * \brief Request bot updates.
369
     * \details Request updates received by the bot using method getUpdates of Telegram API. [Api reference](https://core.telegram.org/bots/api#getupdates)
370
     * @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.
371
     * @param $limit <i>Optional</i>. Limits the number of updates to be retrieved. Values between 1—100 are accepted.
372
     * @param $timeout <i>Optional</i>. Timeout in seconds for long polling.
373
     * @return Array of updates (can be empty).
374
     */
375
    public function getUpdates(int $offset = 0, int $limit = 100, int $timeout = 60) {
376
377
        $parameters = [
378
            'offset' => $offset,
379
            'limit' => $limit,
380
            'timeout' => $timeout,
381
        ];
382
383
        return $this->exec_curl_request('getUpdates?' . http_build_query($parameters));
384
385
    }
386
387
    /**
388
     * \brief Get information about bot's webhook.
389
     * \details Returns an hash which contains information about bot's webhook.
390
     */
391
    public function getWebhookInfo() {
392
393
        return $this->exec_curl_request('getWebhookInfo');
394
395
    }
396
397
    /**
398
     * \brief Delete bot's webhook.
399
     * \details Delete bot's webhook if it exists.
400
     */
401
    public function deleteWebhook() {
402
403
        return $this->exec_curl_request('deleteWebhook');
404
405
    }
406
407
    /**
408
     * \brief Set bot's webhook.
409
     * \details Set a webhook for the current bot in order to receive incoming
410
     * updates via an outgoing webhook.
411
     * @param $params See [Telegram API](https://core.telegram.org/bots/api#setwebhook)
412
     * for more information about the available parameters.
413
     */
414
    public function setWebhook(array $params) {
415
416
        return $this->exec_curl_request('setWebhook?' . http_build_query($params));
417
418
    }
419
420
    /**
421
     * \brief Set updates received by the bot for getUpdates handling.
422
     * \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.
423
     * Set it one time and it won't change until next setUpdateReturned call.
424
     * @param $allowed_updates <i>Optional</i>. List of updates allowed.
425
     */
426
    public function setUpdateReturned(array $allowed_updates = []) {
427
428
        // Parameter for getUpdates
429
        $parameters = [
430
            'offset' => 0,
431
            'limit' => 1,
432
            'timeout' => 0,
433
        ];
434
435
        // Start the list
436
        $updates_string = '[';
437
438
        // Flag to skip adding ", " to the string
439
        $first_string = true;
440
441
        // Iterate over the list
442
        foreach ($allowed_updates as $index => $update) {
443
444
            // Is it the first update added?
445
            if (!$first_string) {
446
447
                $updates_string .= ', "' . $update . '"';
448
449
            } else {
450
451
                $updates_string .= '"' . $update . '"';
452
453
                // Set the flag to false cause we added an item
454
                $first_string = false;
455
456
            }
457
458
        }
459
460
        // Close string with the marker
461
        $updates_string .= ']';
462
463
        // Exec getUpdates
464
        $this->exec_curl_request('getUpdates?' . http_build_query($parameters)
465
                                               . '&allowed_updates=' . $updates_string);
466
467
    }
468
469
    /**
470
     * \brief Send a text message.
471
     * \details Use this method to send text messages. [Api reference](https://core.telegram.org/bots/api#sendmessage)
472
     * @param $text Text of the message.
473
     * @param $reply_markup <i>Optional</i>. Reply_markup of the message.
474
     * @param $parse_mode <i>Optional</i>. Parse mode of the message.
475
     * @param $disable_web_preview <i>Optional</i>. Disables link previews for links in this message.
476
     * @param $disable_notification <i>Optional</i>. Sends the message silently.
477
     * @return On success,  the sent message.
478
     */
479
    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) {
480
481
        $parameters = [
482
            'chat_id' => $this->_chat_id,
483
            'text' => $text,
484
            'parse_mode' => $parse_mode,
485
            'disable_web_page_preview' => $disable_web_preview,
486
            'reply_markup' => $reply_markup,
487
            'reply_to_message_id' => $reply_to,
488
            'disable_notification' => $disable_notification
489
        ];
490
491
        return $this->exec_curl_request('sendMessage?' . http_build_query($parameters));
492
493
    }
494
495
    /**
496
     * \brief Forward a message.
497
     * \details Use this method to forward messages of any kind. [Api reference](https://core.telegram.org/bots/api#forwardmessage)
498
     * @param $from_chat_id The chat where the original message was sent.
499
     * @param $message_id Message identifier (id).
500
     * @param $disable_notification <i>Optional</i>. Sends the message silently.
501
     * @return On success,  the sent message.
502
     */
503
    public function forwardMessage($from_chat_id, int $message_id, bool $disable_notification = false) {
504
505
        $parameters = [
506
            'chat_id' => $this->_chat_id,
507
            'message_id' => $message_id,
508
            'from_chat_id' => $from_chat_id,
509
            'disable_notification' => $disable_notification
510
        ];
511
512
        return $this->exec_curl_request('forwardMessage?' . http_build_query($parameters));
513
514
    }
515
516
    /**
517
     * \brief Send a photo.
518
     * \details Use this method to send photos. [Api reference](https://core.telegram.org/bots/api#sendphoto)
519
     * @param $photo Photo to send, can be a file_id or a string referencing the location of that image.
520
     * @param $reply_markup <i>Optional</i>. Reply markup of the message.
521
     * @param $caption <i>Optional</i>. Photo caption (may also be used when resending photos by file_id), 0-200 characters.
522
     * @param $disable_notification <i>Optional<i>. Sends the message silently.
523
     * @return On success,  the sent message.
524
     */
525
    public function sendPhoto($photo, string $reply_markup = null, string $caption = '', bool $disable_notification = false) {
526
527
        $parameters = [
528
            'chat_id' => $this->_chat_id,
529
            'photo' => $photo,
530
            'caption' => $caption,
531
            'reply_markup' => $reply_markup,
532
            'disable_notification' => $disable_notification,
533
        ];
534
535
        return $this->exec_curl_request('sendPhoto?' . http_build_query($parameters));
536
537
    }
538
539
    /**
540
     * \brief Send an audio.
541
     * \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)
542
     * Bots can currently send audio files of up to 50 MB in size, this limit may be changed in the future.
543
     * @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.
544
     * @param $caption <i>Optional</i>. Audio caption, 0-200 characters.
545
     * @param $reply_markup <i>Optional</i>. Reply markup of the message.
546
     * @param $duration <i>Optional</i>. Duration of the audio in seconds.
547
     * @param $performer <i>Optional</i>. Performer.
548
     * @param $title <i>Optional</i>. Track name.
549
     * @param $disable_notification <i>Optional</i>. Sends the message silently.
550
     * @param $reply_to_message_id <i>Optional</i>. If the message is a reply, ID of the original message.
551
     * @return On success, the sent message.
552
     */
553
    public function sendAudio($audio, string $caption = null, string $reply_markup = null, int $duration = null, string $performer, string $title = null, bool $disable_notification = false, int $reply_to_message_id = null) {
554
555
        $parameters = [
556
            'chat_id' => $this->_chat_id,
557
            'audio' => $audio,
558
            'caption' => $caption,
559
            'duration' => $duration,
560
            'performer' => $performer,
561
            'title' => $title,
562
            'reply_to_message_id' => $reply_to_message_id,
563
            'reply_markup' => $reply_markup,
564
            'disable_notification' => $disable_notification,
565
        ];
566
567
        return $this->exec_curl_request('sendAudio?' . http_build_query($parameters));
568
569
    }
570
571
    /**
572
     * \brief Send a document.
573
     * \details Use this method to send general files. [Api reference](https://core.telegram.org/bots/api/#senddocument)
574
     * @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.
575
     * @param <i>Optional</i>. Document caption (may also be used when resending documents by file_id), 0-200 characters.
576
     *
577
     * @param $reply_markup <i>Optional</i>. Reply markup of the message.
578
     * @param <i>Optional</i>. Sends the message silently.
579
     * @param <i>Optional</i>. If the message is a reply, ID of the original message.
580
     */
581
    public function sendDocument($document, string $caption = '', string $reply_markup = null, bool $disable_notification = false, int $reply_to_message_id = null) {
582
583
        $parameters = [
584
            'chat_id' => $this->_chat_id,
585
            'document' => $document,
586
            'caption' => $caption,
587
            'reply_to_message_id' => $reply_to_message_id,
588
            'reply_markup' => $reply_markup,
589
            'disable_notification' => $disable_notification,
590
        ];
591
592
        return $this->exec_curl_request('sendAudio?' . http_build_query($parameters));
593
594
    }
595
596
597
    /**
598
     * \brief Send a sticker
599
     * \details Use this method to send .webp stickers. [Api reference](https://core.telegram.org/bots/api/#sendsticker)
600
     * @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.
601
     * @param $reply_markup <i>Optional</i>. Reply markup of the message.
602
     * @param $disable_notification Sends the message silently.
603
     * @param <i>Optional</i>. If the message is a reply, ID of the original message.
604
     * @param On success, the sent message.
605
     */
606
    public function sendSticker($sticker, string $reply_markup = null, bool $disable_notification = false, int $reply_to_message_id = null) {
607
608
        $parameters = [
609
            'chat_id' => $this->_chat_id,
610
            'sticker' => $sticker,
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('sendSticker?' . http_build_query($parameters));
617
618
    }
619
620
    /**
621
     * \brief Send audio files.
622
     * \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
623
     * Bots can currently send voice messages of up to 50 MB in size, this limit may be changed in the future.
624
     * @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.
625
     * @param $caption <i>Optional</i>. Voice message caption, 0-200 characters
626
     * @param $duration <i>Optional</i>. Duration of the voice message in seconds
627
     * @param $reply_markup <i>Optional</i>. Reply markup of the message.
628
     * @param $disable_notification <i>Optional</i>. Sends the message silently.
629
     * @param $reply_to_message_id <i>Optional</i>. If the message is a reply, ID of the original message.
630
     * @return On success, the sent message is returned.
631
     */
632 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...
633
634
        $parameters = [
635
            'chat_id' => $this->_chat_id,
636
            'voice' => $voice,
637
            'caption' => $caption,
638
            'duration' => $duration,
639
            'disable_notification', $disable_notification,
640
            'reply_to_message_id' => $reply_to_message_id,
641
            'reply_markup' => $reply_markup
642
        ];
643
644
        return $this->exec_curl_request('sendVoice?' . http_build_query($parameters));
645
646
    }
647
648
    /**
649
     * \brief Say the user what action is the bot doing.
650
     * \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)
651
     * @param $action Type of action to broadcast. Choose one, depending on what the user is about to receive:
652
     * - <code>typing</code> for text messages
653
     * - <code>upload_photo</code> for photos
654
     * - <code>record_video</code> or <code>upload_video</code> for videos
655
     * - <code>record_audio</code> or <code>upload_audio</code> for audio files
656
     * - <code>upload_document</code> for general files
657
     * - <code>find_location</code> for location data
658
     * @return True on success.
659
     */
660
    public function sendChatAction(string $action) : bool {
661
662
        $parameters = [
663
            'chat_id' => $this->_chat_id,
664
            'action' => $action
665
        ];
666
667
        return $this->exec_curl_request('sendChatAction?' . http_build_query($parameters));
668
669
    }
670
671
    /**
672
     * \brief Get info about a chat.
673
     * \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)
674
     * @param Unique identifier for the target chat or username of the target supergroup or channel (in the format <code>@channelusername</code>)
675
     */
676
    public function getChat($_chat_id) {
677
678
        $parameters = [
679
            'chat_id' => $_chat_id,
680
        ];
681
682
        return $this->exec_curl_request('getChat?' . http_build_query($parameters));
683
684
    }
685
686
    /**
687
     * \brief Use this method to get a list of administrators in a chat.
688
     * @param Unique identifier for the target chat or username of the target supergroup or channel (in the format <code>@channelusername</code>)
689
     * @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.
690
     */
691
    public function getChatAdministrators($_chat_id) {
692
693
        $parameters = [
694
            'chat_id' => $_chat_id,
695
        ];
696
697
        return $this->exec_curl_request('getChatAdministrators?' . http_build_query($parameters));
698
699
    }
700
701
702
    /* \brief Answer a callback query
703
     * \details Remove the updating cirle on an inline keyboard button and showing a message/alert to the user.
704
     * It will always answer the current callback query.
705
     * @param $text <i>Optional</i>. Text of the notification. If not specified, nothing will be shown to the user, 0-200 characters.
706
     * @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.
707
     * @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.
708
     * Otherwise, you may use links like telegram.me/your_bot?start=XXXX that open your bot with a parameter.
709
     * @return True on success.
710
     */
711
    public function answerCallbackQuery($text = '', $show_alert = false, string $url = '') : bool {
712
713
        if (!isset($this->_callback_query_id)) {
714
715
            throw new BotException("Callback query id not set, wrong update");
716
717
        }
718
719
        $parameters = [
720
            'callback_query_id' => $this->_callback_query_id,
721
            'text' => $text,
722
            'show_alert' => $show_alert,
723
            'url' => $url
724
        ];
725
726
        return $this->exec_curl_request('answerCallbackQuery?' . http_build_query($parameters));
727
728
    }
729
730
    /**
731
     * \brief Edit text of a message sent by the bot.
732
     * \details Use this method to edit text and game messages sent by the bot. [Api reference](https://core.telegram.org/bots/api#editmessagetext)
733
     * @param $message_id Unique identifier of the sent message.
734
     * @param $text New text of the message.
735
     * @param $reply_markup Reply markup of the message will have (will be removed if this is null).
736
     * @param $parse_mode <i>Optional</i>. Send Markdown or HTML.
737
     * @param $disable_web_preview <i>Optional</i>. Disables link previews for links in this message.
738
     */
739 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...
740
741
        $parameters = [
742
            'chat_id' => $this->_chat_id,
743
            'message_id' => $message_id,
744
            'text' => $text,
745
            'reply_markup' => $reply_markup,
746
            'parse_mode' => $parse_mode,
747
            'disable_web_page_preview' => $disable_web_preview,
748
        ];
749
750
        return $this->exec_curl_request('editMessageText?' . http_build_query($parameters));
751
752
    }
753
754
    /**
755
     * \brief Edit text of a message sent via the bot.
756
     * \details Use this method to edit text messages sent via the bot (for inline queries). [Api reference](https://core.telegram.org/bots/api#editmessagetext)
757
     * @param $inline_message_id  Identifier of the inline message.
758
     * @param $text New text of the message.
759
     * @param $reply_markup Reply markup of the message will have (will be removed if this is null).
760
     * @param $parse_mode <i>Optional</i>. Send Markdown or HTML.
761
     * @param $disable_web_preview <i>Optional</i>. Disables link previews for links in this message.
762
     */
763
    public function editInlineMessageText(string $inline_message_id, $text, string $reply_markup = null, string $parse_mode = 'HTML', bool $disable_web_preview = false) {
764
765
        $parameters = [
766
            'inline_message_id' => $inline_message_id,
767
            'text' => $text,
768
            'reply_markup' => $reply_markup,
769
            'parse_mode' => $parse_mode,
770
            'disable_web_page_preview' => $disable_web_preview,
771
        ];
772
773
        return $this->exec_curl_request('editMessageText?' . http_build_query($parameters));
774
775
    }
776
777
    /*
778
     * Edit only the inline keyboard of a message (https://core.telegram.org/bots/api#editmessagereplymarkup)ù
779
     * @param
780
     * $message_id Identifier of the message to edit
781
     * $inline_keyboard Inlike keyboard array (https://core.telegram.org/bots/api#inlinekeyboardmarkup)
782
     */
783
    public function editMessageReplyMarkup($message_id, $inline_keyboard) {
784
785
        $parameters = [
786
            'chat_id' => $this->_chat_id,
787
            'message_id' => $message_id,
788
            'reply_markup' => $inline_keyboard,
789
        ];
790
791
        return $this->exec_curl_request('editMessageReplyMarkup?' . http_build_query($parameters));
792
793
    }
794
795
    /*
796
     * 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)
797
     * @param
798
     * $results Array on InlineQueryResult (https://core.telegram.org/bots/api#inlinequeryresult)
799
     * $switch_pm_text Text to show on the button
800
     */
801 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...
802
803
        if (!isset($this->_inline_query_id)) {
804
805
            throw new BotException("Inline query id not set, wrong update");
806
807
        }
808
809
        $parameters = [
810
            'inline_query_id' => $this->_inline_query_id,
811
            'switch_pm_text' => $switch_pm_text,
812
            'is_personal' => $is_personal,
813
            'switch_pm_parameter' => $switch_pm_parameter,
814
            'results' => $results,
815
            'cache_time' => $cache_time
816
        ];
817
818
        return $this->exec_curl_request('answerInlineQuery?' . http_build_query($parameters));
819
820
    }
821
822
    /*
823
     * 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)
824
     * without showing any results to the user
825
     * @param
826
     * $switch_pm_text Text to show on the button
827
     */
828 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...
829
830
        if (!isset($this->_inline_query_id)) {
831
832
            throw new BotException("Inline query id not set, wrong update");
833
834
        }
835
836
        $parameters = [
837
            'inline_query_id' => $this->_inline_query_id,
838
            'switch_pm_text' => $switch_pm_text,
839
            'is_personal' => $is_personal,
840
            'switch_pm_parameter' => $switch_pm_parameter,
841
            'cache_time' => $cache_time
842
        ];
843
844
        return $this->exec_curl_request('answerInlineQuery?' . http_build_query($parameters));
845
846
    }
847
848
    /**
849
     * \brief Exec any api request using this method.
850
     * \details Use this method for custom api calls using this syntax:
851
     *
852
     *     $param = [
853
     *             'chat_id' => $_chat_id,
854
     *             'text' => 'Hello!'
855
     *     ];
856
     *     apiRequest("sendMessage", $param);
857
     *
858
     * @param $method The method to call.
859
     * @param $parameters Parameters to add.
860
     * @return Depends on api method.
861
     */
862
    public function apiRequest(string $method, array $parameters) {
863
864
        return $this->exec_curl_request($method . '?' . http_build_query($parameters));
865
866
    }
867
868
    /** @} */
869
870
    /**
871
     * \addtogroup Core Core(internal)
872
     * @{
873
     */
874
875
    /** \brief Core function to execute url request.
876
     * @param $url The url to call using the curl session.
877
     * @return Url response, false on error.
878
     */
879
    protected function exec_curl_request($url, $method = 'POST') {
880
        $response = $this->http->request($method, $url);
881
        $http_code = $response->getStatusCode();
882
883
        if ($http_code === 200) {
884
            $response = json_decode($response->getBody(), true);
885
886
            if (isset($response['desc'])) {
887
                error_log("Request was successfull: {$response['description']}\n");
888
            }
889
890
            return $response['result'];
891
        } elseif ($http_code >= 500) {
892
            // do not wat to DDOS server if something goes wrong
893
            sleep(10);
894
            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...
895
        } elseif ($http_code !== 200) {
896
            $response = json_decode($response->getBody(), true);
897
            error_log("Request has failed with error {$response['error_code']}: {$response['description']}\n");
898
            if ($http_code === 401) {
899
                throw new BotException('Invalid access token provided');
900
            }
901
            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...
902
        }
903
904
        return $response;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $response; (Psr\Http\Message\ResponseInterface) 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...
905
    }
906
907
    /** @} */
908
909
}
910
911