Friday, August 5, 2016

How to Start a Telegram Bot With PHP_part2 (end)

Create a Stopwatch Class

Finally we are ready to start coding. Let's create a class to work with the database in a file called stopwatch.php and start with a constructor that will set two private variables, where we will store the chat ID and the current MySQL connection:
  1. class Stopwatch
  2. {
  3.     /** @var mysqli */
  4.     private $mysqli;
  5.     /** @var int */
  6.     private $stopwatch_id;
  7.     /**
  8.      * Stopwatch constructor
  9.      * @param mysqli $mysqli
  10.      * @param $stopwatch_id
  11.      */
  12.     public function __construct(\mysqli $mysqli, $stopwatch_id)
  13.     {
  14.         $this->mysqli = $mysqli;
  15.         $this->stopwatch_id = intval($stopwatch_id);
  16.     }
  17. }
When the user starts the timer, we will get the current Unix time and save it in a row with the chat ID, so here is the start() method:
  1. public function start()
  2. {
  3.     $timestamp = time();
  4.     $query = "
  5.         INSERT INTO  `stopwatch` (`chat_id`, `timestamp`)
  6.         VALUES ('$this->stopwatch_id', '$timestamp')
  7.         ON DUPLICATE KEY UPDATE timestamp = '$timestamp'       
  8.     ";
  9.     return $this->mysqli->query($query);
  10. }
If the timer stops, we need to delete a row from the database:
  1. /**
  2.  * Delete row with stopwatch id
  3.  * @return bool|mysqli_result
  4.  */
  5. public function stop()
  6. {
  7. $query = "
  8.     DELETE FROM `stopwatch`
  9.     WHERE `chat_id` = $this->stopwatch_id
  10.     ";
  11.     return $this->mysqli->query($query);
  12. }
And now for the main part of the class. When the user requests the status of the timer, we need to find the row with the stopwatch from the current conversation and calculate the difference in seconds between the saved Unix time and the current time. Fortunately, Unix time is an integer, so we can just subtract one value from another. To format the resulting value as a time, we will use the gmdate  function.
  1. /**
  2.  * Find row with stopwatch id and return difference in seconds from saved Unix time and current time
  3.  * @return string
  4.  */
  5. public function status()
  6. {
  7.     $query = "
  8.         SELECT `timestamp` FROM  `stopwatch`
  9.         WHERE `chat_id` = $this->stopwatch_id        
  10.     ";
  11.     $timestamp = $this->mysqli->query($query)->fetch_row();
  12.     if (!empty($timestamp)) {
  13.         return gmdate("H:i:s", time() - reset($timestamp));
  14.     }
  15. }
As you can see, if there is no value in the database, the method status() will return nothing, and we will process a null value like a stopped timer.

Choosing a PHP Library

There are many PHP libraries that exist to work with the Telegram API, but, at least at the moment of writing this article, there's only one that supports both the Telegram Bot API wrapper and Botan tracking. And it's called PHP Telegram Bot API.

Use Composer to install this library:
  1. composer require telegram-bot/api
If you're not interested in using analytics, try Telegram Bot API PHP SDK with Lavarel integration or PHP Telegram Bot.

Start the Webhook Script
And now the main part begins—we will create a script to process callbacks from the Telegram Bot API. Start a file called index.php and include Composer autoload and a new Stopwatch class. Open a MySQL connection, create a new Telegram API client, and run it:
  1. require_once 'vendor/autoload.php';
  2. require_once 'stopwatch.php';
  3.  
  4. // connect to database
  5. $mysqli = new mysqli('database_host', 'database_user', 'database_password', 'database_name');
  6. if (!empty($mysqli->connect_errno)) {
  7.     throw new \Exception($mysqli->connect_error, $mysqli->connect_errno);
  8. }
  9.  
  10. // create a bot
  11. $bot = new \TelegramBot\Api\Client('bot_token', 'botanio_token');
  12. // run, bot, run!
  13. $bot->run();
Create Commands
Now we need to set up a bot to answer on command /start. This command is used to start all Telegram bots, and users will be shown our welcome message when the first chat begins.
  1. $bot->command('start', function ($message) use ($bot) {
  2.     $answer = 'Howdy! Welcome to the stopwatch. Use bot commands or keyboard to control your time.';
  3.     $bot->sendMessage($message->getChat()->getId(), $answer);
  4. });
Here, in the command() method, we defined a closure for receiving a command. This closure gets the ID of the current chat and sends a welcome message. Also, all registered commands are automatically tracked as the command name.

To start the stopwatch, we will define the /go command:
  1. $bot->command('go', function ($message) use ($bot, $mysqli) {
  2.     $stopwatch = new Stopwatch($mysqli, $message->getChat()->getId());
  3.     $stopwatch->start();
  4.     $bot->sendMessage($message->getChat()->getId(), 'Stopwatch started. Go!');
  5. });
This will create an instance of the Stopwatch class and start a timer calling the start() method that we have defined already.

To define the /status command, we need to do the same thing. Just call the status() method and return the result. If the method returned null, tell the user that the timer is not started.
  1. $bot->command('status', function ($message) use ($bot, $mysqli) {
  2.     $stopwatch = new Stopwatch($mysqli, $message->getChat()->getId());
  3.     $answer = $stopwatch->status();
  4.     if (empty($answer)) {
  5.         $answer = 'Timer is not started.';
  6.     }
  7.     $bot->sendMessage($message->getChat()->getId(), $answer);
  8. });
And if the user stops the timer, we need to get the status first, show the resulting time, and stop the timer using the stop() method.
  1. $bot->command('stop', function ($message) use ($bot, $mysqli) {
  2.     $stopwatch = new Stopwatch($mysqli, $message->getChat()->getId());
  3.     $answer = $stopwatch->status();
  4.     if (!empty($answer)) {
  5.         $answer = 'Your time is ' . $answer . PHP_EOL;
  6.     }
  7.     $stopwatch->stop();
  8.     $bot->sendMessage($message->getChat()->getId(), $answer . 'Stopwatch stopped. Enjoy your time!');
  9. });
That's it! Now you can upload all the files to the webhook directory and test your bot.

Adding a Keyboard
To suggest to the user which commands he or she can run, we can add a keyboard to a message. Our stopwatch can be running or stopped, and there will be two ones for each state. To show a keyboard to the user, we just need to extend the sendMessage() method:
  1. $keyboard = new \TelegramBot\Api\Types\ReplyKeyboardMarkup([['/go', '/status']], null, true);
  2. $bot->sendMessage($message->getChat()->getId(), $answer, false, null, null, $keyboards);
  3. });
Now you can add keyboards to every command of your bot. I will not include a full example here, but you can see it in the repository pages.

Adding Your Bot to a Store

Okay, so now we have working bot, and we want to show it to the world. The best way is to register the bot in a bot catalogue. For now, Telegram doesn't have an official catalogue like this, but there are a few unofficial ones, and the biggest is Storebot.me, where thousands of bots are already registered.

And there is a... bot to register your bot in a bot store! Add @storebot to your contact list, type the /add command, and follow the instructions. You will be asked to enter the bot's username, name, and description, choose one of the standard categories, and confirm the bot's ownership by sending its token.

After a while, your bot will pass the submission process and appear in the Storebot charts. Now you and your users can vote, find and rate your bot in the bot store to help it rise to the top of the chart.

Conclusion
We've come a long way, from creating a baby bot to registering it in a store to be available to real users. As you can see, there are many tools that exist to make your life easier with creating and spreading your bot, and you don't need much code to start an easy bot. Now you are ready to make your own!
Written by Anton Bagaiev

If you found this post interesting, please follow and support us.
Suggest for you:

Learning PHP 7: From the Basics to Application Development

The Complete PHP 7 Guide for Web Developers

Up to Speed with PHP 7

Learn PHP 7 This Way to Rise Above & Beyond Competion!

The Complete PHP with MySQL Developer Course (New)


No comments:

Post a Comment