Completed
Push — master ( a56e0e...d75616 )
by Danilo
02:09
created

CoreBot   B

Complexity

Total Complexity 41

Size/Duplication

Total Lines 658
Duplicated Lines 16.26 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 0
Metric Value
wmc 41
c 0
b 0
f 0
lcom 1
cbo 1
dl 107
loc 658
rs 8.1264

26 Methods

Rating   Name   Duplication   Size   Complexity  
B __construct() 0 24 3
A __destruct() 0 6 1
A getChatID() 0 5 1
A setChatID() 0 5 1
A getBotID() 0 17 3
A getMe() 0 5 1
A getUpdates() 0 11 1
B setUpdateReturned() 0 41 3
A sendMessage() 0 15 1
A forwardMessage() 0 12 1
A sendPhoto() 0 13 1
A sendAudio() 0 17 1
A sendDocument() 0 14 1
A sendSticker() 0 13 1
A sendVoice() 15 15 1
A sendChatAction() 10 10 1
A getChat() 9 9 1
A answerCallbackQuery() 0 18 2
A editMessageText() 14 14 1
A editInlineMessageText() 0 13 1
A editMessageReplyMarkup() 11 11 1
A answerInlineQuerySwitchPM() 20 20 2
A answerEmptyInlineQuerySwitchPM() 19 19 2
A apiRequest() 0 5 1
C exec_curl_request() 0 37 7
A getChatAdministrators() 9 9 1

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like CoreBot often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use CoreBot, and based on these observations, apply Extract Interface, too.

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