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 classes like Bot 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 Bot, and based on these observations, apply Extract Interface, too.
| 1 | <?php |
||
| 13 | class Bot extends CoreBot { |
||
| 14 | |||
| 15 | /** |
||
| 16 | * \addtogroup Bot Bot |
||
| 17 | * \brief Properties and methods to handle the TelegramBot. |
||
| 18 | * \details Here are listed all the properties and methods that will help the developer create the basic bot functions. |
||
| 19 | * @{ |
||
| 20 | */ |
||
| 21 | |||
| 22 | /** \brief Text received in messages */ |
||
| 23 | protected $_text; |
||
| 24 | |||
| 25 | /** \brief Data received in callback query */ |
||
| 26 | protected $_data; |
||
| 27 | |||
| 28 | /** \brief Query sent by the user in the inline query */ |
||
| 29 | protected $_query; |
||
| 30 | |||
| 31 | /** \brief Store the inline keyboard */ |
||
| 32 | public $keyboard; |
||
| 33 | |||
| 34 | /** \brief Pdo reference */ |
||
| 35 | public $pdo; |
||
| 36 | |||
| 37 | /** \brief Redis connection */ |
||
| 38 | public $redis; |
||
| 39 | |||
| 40 | /** @} */ |
||
| 41 | |||
| 42 | /** |
||
| 43 | * \addtogroup Core Core(internal) |
||
| 44 | * @{ |
||
| 45 | */ |
||
| 46 | |||
| 47 | /** \brief Store the command triggered on message. */ |
||
| 48 | private $message_commands; |
||
| 49 | |||
| 50 | /** \brief Does the bot has message commands? Set by initBot. */ |
||
| 51 | private $message_commands_set; |
||
| 52 | |||
| 53 | /** \brief Store the command triggered on callback query. */ |
||
| 54 | private $callback_commands; |
||
| 55 | |||
| 56 | /** \brief Does the bot has message commands? Set by initBot. */ |
||
| 57 | private $callback_commands_set; |
||
| 58 | |||
| 59 | /** @} */ |
||
| 60 | |||
| 61 | /** |
||
| 62 | * \addtogroup Multilanguage Multilanguage |
||
| 63 | * \brief Methods to create a localized bot. |
||
| 64 | * @{ |
||
| 65 | */ |
||
| 66 | |||
| 67 | /** \brief Store the language for a multi-language bot */ |
||
| 68 | public $language; |
||
| 69 | |||
| 70 | /** \brief Store localization data */ |
||
| 71 | public $local; |
||
| 72 | |||
| 73 | /** \brief Table contaning bot users data in the sql database. */ |
||
| 74 | public $user_table = '"User"'; |
||
| 75 | |||
| 76 | /** \brief Name of the column that represents the user id in the sql database */ |
||
| 77 | public $id_column = 'chat_id'; |
||
| 78 | |||
| 79 | /** @} */ |
||
| 80 | |||
| 81 | /** \addtogroup State |
||
| 82 | * @{ |
||
| 83 | */ |
||
| 84 | |||
| 85 | /** \brief Status of the bot to handle data inserting and menu-like bot. */ |
||
| 86 | public $status; |
||
| 87 | |||
| 88 | /** @} */ |
||
| 89 | |||
| 90 | /** |
||
| 91 | * \addtogroup Bot |
||
| 92 | * @{ |
||
| 93 | */ |
||
| 94 | |||
| 95 | /** |
||
| 96 | * \brief Construct an empy bot. |
||
| 97 | * \details Construct a bot with commands, multilanguage and status. |
||
| 98 | */ |
||
| 99 | public function __construct(string $token) { |
||
| 111 | |||
| 112 | /** \brief Descruct the class. */ |
||
| 113 | public function __destruct() { |
||
| 125 | |||
| 126 | /** |
||
| 127 | * \brief Get the text of the message, if set (for updates of type "message"). |
||
| 128 | * @return Text of the message, empty string if not set. |
||
| 129 | */ |
||
| 130 | public function getMessageText() : string { |
||
| 141 | |||
| 142 | /** |
||
| 143 | * \brief Get the data of callback query, if set (for updates of type "callback_query"). |
||
| 144 | * @return Data of the callback query, empty string if not set. |
||
| 145 | */ |
||
| 146 | public function getCallbackData() : string { |
||
| 157 | |||
| 158 | /** |
||
| 159 | * \brief Get the query received from the inline query (for updates of type "inline_query"). |
||
| 160 | * @return The query sent by the user, throw exception if the current update is not an inline query. |
||
| 161 | */ |
||
| 162 | public function getInlineQuery() : string { |
||
| 172 | |||
| 173 | /** |
||
| 174 | * \brief Get update and process it. |
||
| 175 | * \details Call this method if you are using webhook. |
||
| 176 | * It will get update from php::\input, check it and then process it using processUpdate. |
||
| 177 | */ |
||
| 178 | public function processWebhookUpdate() { |
||
| 185 | |||
| 186 | /** @} */ |
||
| 187 | |||
| 188 | /** |
||
| 189 | * \addtogroup Core Core(Internal) |
||
| 190 | * @{ |
||
| 191 | */ |
||
| 192 | |||
| 193 | /** |
||
| 194 | * \brief Init variables to skip parsing commands if there aren't any. |
||
| 195 | * \details Called internnaly by |
||
| 196 | * - <code>getUpdatesLocal</code> |
||
| 197 | * - <code>getUpdatesRedis</code> |
||
| 198 | * - <code>getUpdatesDatabase</code> |
||
| 199 | * - <code>processWebhookUpdate</code> |
||
| 200 | */ |
||
| 201 | private function initBot() { |
||
| 210 | |||
| 211 | /** |
||
| 212 | * \brief Dispatch each update to the right method (processMessage, processCallbackQuery, etc). |
||
| 213 | * \details Set $chat_id for each update, $text, $data and $query are set for each update that contains them. |
||
| 214 | * It also calls commands for each updates, before process methods. |
||
| 215 | * @param $update Reference to the update received. |
||
| 216 | * @return The id of the update processed. |
||
| 217 | */ |
||
| 218 | public function processUpdate(array $update) : int { |
||
| 375 | |||
| 376 | /** @} */ |
||
| 377 | |||
| 378 | /** |
||
| 379 | * \addtogroup Bot Bot |
||
| 380 | * @{ |
||
| 381 | */ |
||
| 382 | |||
| 383 | /** |
||
| 384 | * \brief Called every message received by the bot. |
||
| 385 | * \details Override it to script the bot answer for each message. |
||
| 386 | * <code>$chat_id</code> and <code>$text</code>, if the message contains text(use getMessageText() to access it), set inside of this function. |
||
| 387 | * @param $message Reference to the message received. |
||
| 388 | */ |
||
| 389 | protected function processMessage($message) {} |
||
| 390 | |||
| 391 | /** |
||
| 392 | * \brief Called every callback query received by the bot. |
||
| 393 | * \details Override it to script the bot answer for each callback. |
||
| 394 | * <code>$chat_id</code> and <code>$data</code>, if set in the callback query(use getCallbackData() to access it) set inside of this function. |
||
| 395 | * @param $callback_query Reference to the callback query received. |
||
| 396 | */ |
||
| 397 | protected function processCallbackQuery($callback_query) { |
||
| 400 | |||
| 401 | /** |
||
| 402 | * \brief Called every inline query received by the bot. |
||
| 403 | * \details Override it to script the bot answer for each inline query. |
||
| 404 | * $chat_id and $query(use getInlineQuery() to access it) set inside of this function. |
||
| 405 | * @param $inline_query Reference to the inline query received. |
||
| 406 | */ |
||
| 407 | protected function processInlineQuery($inline_query) { |
||
| 410 | |||
| 411 | /** |
||
| 412 | * \brief Called every chosen inline result received by the bot. |
||
| 413 | * \details Override it to script the bot answer for each chosen inline result. |
||
| 414 | * <code>$chat_id</code> set inside of this function. |
||
| 415 | * @param $chosen_inline_result Reference to the chosen inline result received. |
||
| 416 | */ |
||
| 417 | protected function processChosenInlineResult($chosen_inline_result) { |
||
| 420 | |||
| 421 | /** |
||
| 422 | * \brief Called every chosen edited message received by the bot. |
||
| 423 | * \details Override it to script the bot answer for each edited message. |
||
| 424 | * <code>$chat_id</code> set inside of this function. |
||
| 425 | * @param $edited_message The message edited by the user. |
||
| 426 | */ |
||
| 427 | protected function processEditedMessage($edited_message) { |
||
| 430 | |||
| 431 | /** |
||
| 432 | * \brief Called every new post in the channel where the bot is in. |
||
| 433 | * \details Override it to script the bot answer for each post sent in a channel. |
||
| 434 | * <code>$chat_id</code> set inside of this function. |
||
| 435 | * @param $post The message sent in the channel. |
||
| 436 | */ |
||
| 437 | protected function processChannelPost($post) { |
||
| 440 | |||
| 441 | /** |
||
| 442 | * \brief Called every time a post get edited in the channel where the bot is in. |
||
| 443 | * \details Override it to script the bot answer for each post edited in a channel. |
||
| 444 | * <code>$chat_id</code> set inside of this function. |
||
| 445 | * @param $post The message edited in the channel. |
||
| 446 | */ |
||
| 447 | protected function processEditedChannelPost($edited_post) { |
||
| 450 | |||
| 451 | /** |
||
| 452 | * \brief Get updates received by the bot, using redis to save and get the last offset. |
||
| 453 | * \details It check if an offset exists on redis, then get it, or call getUpdates to set it. |
||
| 454 | * Then it start an infinite loop where it process updates and update the offset on redis. |
||
| 455 | * Each update is surrounded by a try/catch. |
||
| 456 | * @see getUpdates |
||
| 457 | * @param $limit <i>Optional</i>. Limits the number of updates to be retrieved. Values between 1—100 are accepted. |
||
| 458 | * @param $timeout <i>Optional</i>. Timeout in seconds for long polling. |
||
| 459 | * @param $offset_key <i>Optional</i>. Name of the variable where the offset is saved on Redis |
||
| 460 | */ |
||
| 461 | public function getUpdatesRedis(int $limit = 100, int $timeout = 60, string $offset_key = 'offset') { |
||
| 520 | |||
| 521 | /** |
||
| 522 | * \brief Get updates received by the bot, and hold the offset in $offset. |
||
| 523 | * \details Get the update_id of the first update to parse, set it in $offset and |
||
| 524 | * then it start an infinite loop where it processes updates and keep $offset on the update_id of the last update received. |
||
| 525 | * Each processUpdate() method call is surrounded by a try/catch. |
||
| 526 | * @see getUpdates |
||
| 527 | * @param $limit <i>Optional</i>. Limits the number of updates to be retrieved. Values between 1—100 are accepted. |
||
| 528 | * @param $timeout <i>Optional</i>. Timeout in seconds for long polling. |
||
| 529 | */ |
||
| 530 | public function getUpdatesLocal(int $limit = 100, int $timeout = 60) { |
||
| 584 | |||
| 585 | /** |
||
| 586 | * \brief Get updates received by the bot, using the sql database to store and get the last offset. |
||
| 587 | * \details It check if an offset exists on redis, then get it, or call getUpdates to set it. |
||
| 588 | * Then it start an infinite loop where it process updates and update the offset on redis. |
||
| 589 | * Each update is surrounded by a try/catch. |
||
| 590 | * @see getUpdates |
||
| 591 | * @param $limit <i>Optional</i>. Limits the number of updates to be retrieved. Values between 1—100 are accepted. |
||
| 592 | * @param $timeout <i>Optional</i>. Timeout in seconds for long polling. |
||
| 593 | * @param $table_name <i>Optional</i>. Name of the table where offset is saved in the database |
||
| 594 | * @param $column_name <i>Optional</i>. Name of the column where the offset is saved in the database |
||
| 595 | */ |
||
| 596 | public function getUpdatesDatabase(int $limit = 100, int $timeout = 0, string $table_name = 'telegram', string $column_name = 'bot_offset') { |
||
| 663 | |||
| 664 | /** |
||
| 665 | * \brief Add a function that will be executed everytime a message contain the selected command |
||
| 666 | * \details Use this syntax: |
||
| 667 | * |
||
| 668 | * addMessageCommand("start", function($bot, $message) { |
||
| 669 | * $bot->sendMessage("Hi"); }); |
||
| 670 | * @param $command The command that will trigger this function (without slash). Eg: "start", "help", "about" |
||
| 671 | * @param $script The function that will be triggered by a command. Must take an object(the bot) and an array(the message received). |
||
| 672 | */ |
||
| 673 | public function addMessageCommand(string $command, callable $script) { |
||
| 683 | |||
| 684 | /** |
||
| 685 | * \brief Add a function that will be executed everytime a message contain a command that match the regex |
||
| 686 | * \details Use this syntax: |
||
| 687 | * |
||
| 688 | * addMessageCommandRegex("number\d", function($bot, $message, $result) { |
||
| 689 | * $bot->sendMessage("You sent me a number"); }); |
||
| 690 | * @param $regex_rule Regex rule that will called for evalueting the command received. |
||
| 691 | * @param $script The function that will be triggered by a command. Must take an object(the bot) and an array(the message received). |
||
| 692 | */ |
||
| 693 | public function addMessageCommandRegex(string $regex_rule, callable $script) { |
||
| 702 | |||
| 703 | /** |
||
| 704 | * \brief Add a function that will be executed everytime a callback query contains a string as data |
||
| 705 | * \details Use this syntax: |
||
| 706 | * |
||
| 707 | * addMessageCommand("menu", function($bot, $callback_query) { |
||
| 708 | * $bot->editMessageText($callback_query['message']['message_id'], "This is the menu"); }); |
||
| 709 | * @param $data The string that will trigger this function. |
||
| 710 | * @param $script The function that will be triggered by the callback query if it contains the $data string. Must take an object(the bot) and an array(the callback query received). |
||
| 711 | */ |
||
| 712 | public function addCallbackCommand(string $data, callable $script) { |
||
| 720 | |||
| 721 | /** @} */ |
||
| 722 | |||
| 723 | /** |
||
| 724 | * \addtogroup Multilanguage Multilanguage |
||
| 725 | * @{ |
||
| 726 | */ |
||
| 727 | |||
| 728 | /** |
||
| 729 | * \brief Get current user language from the database, and set it in $language. |
||
| 730 | * @param $default_language <i>Optional</i>. Default language to return in case of errors. |
||
| 731 | * @return Language set for the current user, $default_language on errors. |
||
| 732 | */ |
||
| 733 | public function getLanguageDatabase($default_language = 'en') { |
||
| 782 | |||
| 783 | /** |
||
| 784 | * \brief Get current user language from redis, and set it in language. |
||
| 785 | * \details Using redis database we get language stored and the value does not expires. |
||
| 786 | * @param $default_language <i>Optional</i>. Default language to return in case of errors. |
||
| 787 | * @return Language for the current user, $default_language on errors. |
||
| 788 | */ |
||
| 789 | public function getLanguageRedis($default_language = 'en') : string { |
||
| 815 | |||
| 816 | /** |
||
| 817 | * \brief Get current user language from redis, as a cache, and set it in language. |
||
| 818 | * \details Using redis database as cache, seeks the language in it, if there isn't |
||
| 819 | * then get the language from the sql database and store it (with default expiring of one day) in redis. |
||
| 820 | * It also change $language parameter of the bot to the language returned. |
||
| 821 | * @param $default_language <i>Optional</i>. Default language to return in case of errors. |
||
| 822 | * @param $expiring_time <i>Optional</i>. Set the expiring time for the language on redis each time it is took from the sql database. |
||
| 823 | * @return Language for the current user, $default_language on errors. |
||
| 824 | */ |
||
| 825 | public function getLanguageRedisAsCache($default_language = 'en', $expiring_time = '86400') : string { |
||
| 851 | |||
| 852 | /** |
||
| 853 | * \brief Set the current user language in both redis, sql database and $language. |
||
| 854 | * \details Save it on database first, then create the expiring key on redis. |
||
| 855 | * @param $language The new language to set. |
||
| 856 | * @param $expiring_time <i>Optional</i>. Time for the language key in redis to expire. |
||
| 857 | * @return On sucess, return true, throw exception otherwise. |
||
| 858 | */ |
||
| 859 | public function setLanguageRedisAsCache($language, $expiring_time = '86400') { |
||
| 890 | |||
| 891 | /** |
||
| 892 | * \brief Load localization files (JSON-serialized) from a folder and set them in $local variable. |
||
| 893 | * \details Save all localization files, saved as json format, from a directory and put the contents in $local variable. |
||
| 894 | * Each file will be saved into $local with the first two letters of the filename as the index. |
||
| 895 | * Access the english data as $this->local["en"]["Your key"]. |
||
| 896 | * File <code>./localization/en.json</code>: |
||
| 897 | * |
||
| 898 | * {"Hello_Msg": "Hello"} |
||
| 899 | * |
||
| 900 | * File <code>./localization/it.json</code>: |
||
| 901 | * |
||
| 902 | * {"Hello_Msg": "Ciao"} |
||
| 903 | * |
||
| 904 | * Usage in <code>processMessage()</code>: |
||
| 905 | * |
||
| 906 | * $sendMessage($this->local[$this->language]["Hello_Msg"]); |
||
| 907 | * |
||
| 908 | * @param $dir Directory where the localization files are saved. |
||
| 909 | */ |
||
| 910 | public function loadLocalization($dir = './localization') { |
||
| 940 | |||
| 941 | /** @} */ |
||
| 942 | |||
| 943 | /** |
||
| 944 | * \addtogroup State |
||
| 945 | * \brief Create a state based bot using these methods. |
||
| 946 | * \details Bot will answer in different way based on the state. |
||
| 947 | * Here is an example where we use save user credential using bot states: |
||
| 948 | * |
||
| 949 | * <?php |
||
| 950 | * |
||
| 951 | * // Include the framework |
||
| 952 | * require './vendor/autoload.php'; |
||
| 953 | * |
||
| 954 | * // Define bot state |
||
| 955 | * define("SEND_USERNAME", 1); |
||
| 956 | * define("SEND_PASSWORD", 2); |
||
| 957 | * |
||
| 958 | * // Create the class for the bot that will handle login |
||
| 959 | * class LoginBot extends DanySpin97\PhpBotFramework\Bot { |
||
| 960 | * |
||
| 961 | * // Add the function for processing messages |
||
| 962 | * protected function processMessage($message) { |
||
| 963 | * |
||
| 964 | * switch($this->getStatus()) { |
||
| 965 | * |
||
| 966 | * // If we are expecting a username from the user |
||
| 967 | * case SEND_USERNAME: |
||
| 968 | * |
||
| 969 | * // Save the username |
||
| 970 | * |
||
| 971 | * // Say the user to insert the password |
||
| 972 | * $this->sendMessage("Please, send your password."); |
||
| 973 | * |
||
| 974 | * // Update the bot state |
||
| 975 | * $this->setStatus(SEND_PASSWORD); |
||
| 976 | * |
||
| 977 | * break; |
||
| 978 | * |
||
| 979 | * // Or if we are expecting a password from the user |
||
| 980 | * case SEND_PASSWORD: |
||
| 981 | * |
||
| 982 | * // Save the password |
||
| 983 | * |
||
| 984 | * // Say the user he completed the process |
||
| 985 | * $this->sendMessage("The registration is complete"); |
||
| 986 | * |
||
| 987 | * break; |
||
| 988 | * } |
||
| 989 | * |
||
| 990 | * } |
||
| 991 | * |
||
| 992 | * } |
||
| 993 | * |
||
| 994 | * // Create the bot |
||
| 995 | * $bot = new LoginBot("token"); |
||
| 996 | * |
||
| 997 | * // Create redis object |
||
| 998 | * $bot->redis = new Redis(); |
||
| 999 | * |
||
| 1000 | * // Connect to redis database |
||
| 1001 | * $bot->redis->connect('127.0.0.1'); |
||
| 1002 | * |
||
| 1003 | * // Create the awnser to the <code>/start</code> command |
||
| 1004 | * $start_closure = function($bot, $message) { |
||
| 1005 | * |
||
| 1006 | * // saying the user to enter a username |
||
| 1007 | * $bot->sendMessage("Please, send your username."); |
||
| 1008 | * |
||
| 1009 | * // and update the status |
||
| 1010 | * $bot->setStatus(SEND_USERNAME); |
||
| 1011 | * }; |
||
| 1012 | * |
||
| 1013 | * // Add the answer |
||
| 1014 | * $bot->addMessageCommand("start", $start_closure); |
||
| 1015 | * |
||
| 1016 | * $bot->getUpdatesLocal(); |
||
| 1017 | * @{ |
||
| 1018 | */ |
||
| 1019 | |||
| 1020 | /** |
||
| 1021 | * \brief Get current user status from redis and set it in status variable. |
||
| 1022 | * \details Throw exception if redis connection is missing. |
||
| 1023 | * @param $default_status <i>Optional</i>. The default status to return in case there is no status for the current user. |
||
| 1024 | * @return The status for the current user, $default_status if missing. |
||
| 1025 | */ |
||
| 1026 | public function getStatus(int $default_status = -1) : int { |
||
| 1047 | |||
| 1048 | /** \brief Set the status of the bot in both redis and $status. |
||
| 1049 | * \details Throw exception if redis connection is missing. |
||
| 1050 | * @param $status The new status of the bot. |
||
| 1051 | */ |
||
| 1052 | public function setStatus(int $status) { |
||
| 1059 | |||
| 1060 | /** @} */ |
||
| 1061 | |||
| 1062 | /** |
||
| 1063 | * \addtogroup Users-handle Users handling |
||
| 1064 | * \brief Handle bot users on the database. |
||
| 1065 | * @{ |
||
| 1066 | */ |
||
| 1067 | |||
| 1068 | /** \brief Add a user to the database. |
||
| 1069 | * \details Add a user to the database in Bot::$user_table table and Bot::$id_column column using Bot::$pdo connection. |
||
| 1070 | * @param $chat_id chat_id of the user to add. |
||
| 1071 | * @return True on success. |
||
| 1072 | */ |
||
| 1073 | public function addUser($chat_id) : bool { |
||
| 1111 | |||
| 1112 | /** |
||
| 1113 | * \brief Broadcast a message to all user registred on the database. |
||
| 1114 | * \details Send a message to all users subscribed, change Bot::$user_table and Bot::$id_column to match your database structure is. |
||
| 1115 | * This method requires Bot::$pdo connection set. |
||
| 1116 | * All parameters are the same as CoreBot::sendMessage. |
||
| 1117 | * Because a limitation of Telegram Bot API the bot will have a delay after 20 messages sent in different chats. |
||
| 1118 | * @see CoreBot::sendMessage |
||
| 1119 | */ |
||
| 1120 | public function broadcastMessage($text, string $reply_markup = null, string $parse_mode = 'HTML', bool $disable_web_preview = true, bool $disable_notification = false) { |
||
| 1165 | |||
| 1166 | /** @} */ |
||
| 1167 | |||
| 1168 | } |
||
| 1169 |
This check looks from parameters that have been defined for a function or method, but which are not used in the method body.