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:
- class Stopwatch
- {
- /** @var mysqli */
- private $mysqli;
- /** @var int */
- private $stopwatch_id;
- /**
- * Stopwatch constructor
- * @param mysqli $mysqli
- * @param $stopwatch_id
- */
- public function __construct(\mysqli $mysqli, $stopwatch_id)
- {
- $this->mysqli = $mysqli;
- $this->stopwatch_id = intval($stopwatch_id);
- }
- }
- public function start()
- {
- $timestamp = time();
- $query = "
- INSERT INTO `stopwatch` (`chat_id`, `timestamp`)
- VALUES ('$this->stopwatch_id', '$timestamp')
- ON DUPLICATE KEY UPDATE timestamp = '$timestamp'
- ";
- return $this->mysqli->query($query);
- }
- /**
- * Delete row with stopwatch id
- * @return bool|mysqli_result
- */
- public function stop()
- {
- $query = "
- DELETE FROM `stopwatch`
- WHERE `chat_id` = $this->stopwatch_id
- ";
- return $this->mysqli->query($query);
- }
- /**
- * Find row with stopwatch id and return difference in seconds from saved Unix time and current time
- * @return string
- */
- public function status()
- {
- $query = "
- SELECT `timestamp` FROM `stopwatch`
- WHERE `chat_id` = $this->stopwatch_id
- ";
- $timestamp = $this->mysqli->query($query)->fetch_row();
- if (!empty($timestamp)) {
- return gmdate("H:i:s", time() - reset($timestamp));
- }
- }
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:
- composer require telegram-bot/api
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:
- require_once 'vendor/autoload.php';
- require_once 'stopwatch.php';
- // connect to database
- $mysqli = new mysqli('database_host', 'database_user', 'database_password', 'database_name');
- if (!empty($mysqli->connect_errno)) {
- throw new \Exception($mysqli->connect_error, $mysqli->connect_errno);
- }
- // create a bot
- $bot = new \TelegramBot\Api\Client('bot_token', 'botanio_token');
- // run, bot, run!
- $bot->run();
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.
- $bot->command('start', function ($message) use ($bot) {
- $answer = 'Howdy! Welcome to the stopwatch. Use bot commands or keyboard to control your time.';
- $bot->sendMessage($message->getChat()->getId(), $answer);
- });
To start the stopwatch, we will define the /go command:
- $bot->command('go', function ($message) use ($bot, $mysqli) {
- $stopwatch = new Stopwatch($mysqli, $message->getChat()->getId());
- $stopwatch->start();
- $bot->sendMessage($message->getChat()->getId(), 'Stopwatch started. Go!');
- });
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.
- $bot->command('status', function ($message) use ($bot, $mysqli) {
- $stopwatch = new Stopwatch($mysqli, $message->getChat()->getId());
- $answer = $stopwatch->status();
- if (empty($answer)) {
- $answer = 'Timer is not started.';
- }
- $bot->sendMessage($message->getChat()->getId(), $answer);
- });
- $bot->command('stop', function ($message) use ($bot, $mysqli) {
- $stopwatch = new Stopwatch($mysqli, $message->getChat()->getId());
- $answer = $stopwatch->status();
- if (!empty($answer)) {
- $answer = 'Your time is ' . $answer . PHP_EOL;
- }
- $stopwatch->stop();
- $bot->sendMessage($message->getChat()->getId(), $answer . 'Stopwatch stopped. Enjoy your time!');
- });
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:
- $keyboard = new \TelegramBot\Api\Types\ReplyKeyboardMarkup([['/go', '/status']], null, true);
- $bot->sendMessage($message->getChat()->getId(), $answer, false, null, null, $keyboards);
- });
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.
![]() |
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