Shukurov Zaur, developer
@KinomanBot and
@GaidarForum_bot , wrote a guide to creating a simple chat bot in
PHP .
On June 24, 2015, Telegram developers
opened a platform for creating bots (programs that perform certain actions according to a given algorithm).
Over the year and a half of the platform’s work, a lot of interesting chat bots have accumulated that solve many problems and allow to spend time in the messenger.
')

Step 1: register the bot with @BotFather
Before you begin to write code, you need to register a new bot with the “dad of all bots” -
@BotFather , in order to get the token (key) to work with the Telegram API.
Registration takes place in 5 simple steps:
1) Open the chat with
@BotFather ;
2) Enter or select from the list the command
/ newbot ;
3) Send the desired name for the bot;
4) Write the bot's username, which will be used to find it through a search. Be sure to at the end of your username should be the word "bot" or "_bot". For example,
NetologyRSSbot ;
5) Optionally, you can immediately set up a full or short description, a list of commands and avatar.
According to the registration results, we get our token -
375466075: AAEARK0r2nXjB67JiB35JCXXhKEyT42Px8s .
Be careful: never show anyone a token, otherwise your bot may be compromised. If by bad luck someone bad still recognized your token, then you can replace it all in the same
@BotFather by clicking on the “Revoke current token” button in the “API Token” section.
Step 2: choose the way of processing requests
Based on the official documentation, the Telegram API is based on simple HTTP requests. There are only two different ways to handle requests that users will send to the bot:
1) check "manually" using "Long Polling";
2) to entrust all Telegram, putting "Webhook". In this case, any request from the Telegram user will send to the server himself.
We will focus on the second option, but it has a limitation: you need to have an SSL certificate installed on your website so that all requests go through the secure HTTPS protocol. Self-signed and free “Let's Encrypt” certificates, which are supported by most hosting sites, are also suitable.
An example of setting up a self-signed certificate from the official Telegram documentation.
Step 3: write the code
We will write the bot code in PHP, but in order not to reinvent the wheel, we will use a ready-made and very convenient
library .
First of all, we bind via the SetWebhook bot method to our file handler. This can be done with the help of the library, but there is an option faster and easier - to build such a link:
https: // api. telegram. org / bot 375466075: AAEARK0r2nXjB67JiB35JCXXhKEyT42Px8s / setWebhook? url = https: // yoursitehere .ru / directory / bot.php ,
Where
375466075: AAEARK0r2nXjB67JiB35JCXXhKEyT42Px8s is our token,
https: // yousitehere. ru / directory / bot.php - link to the file handler on our site.
Having opened this link in the browser, a JSON-response with the value
“Webhook was set” should come, which will mean that the webhost has been installed, and now all requests from users will be sent to the file handler address.
We turn to the most important thing - the processing of these very requests and the writing of the bot functionality.
Below is a complete listing of the handler file:
<?php include('vendor/autoload.php');
Let's sort everything in order.
1. First, we connect the downloaded library by specifying the path (preferably full) to the autoloader file.
include('vendor/autoload.php');
2. Create an instance of the class in the
$ telegram variable and pass our token to it.
In the
$ result variable, we get information about the message that Telegram will send us.
$telegram = new Api('375466075:AAEARK0r2nXjB67JiB35JCXXhKEyT42Px8s');
3. Then we define the main variables: the text message, the unique identifier of the user and his user name. If you have to work with the database, do not forget about filtering (or better use PDO).
$text = $result["message"]["text"];
4. Create our keyboard, consisting of three buttons.
$keyboard = [[" "],[""],[""]];
5. Now that we have identified all the variables, we can proceed to processing the received message. To do this, you can use the
switch-case or
if-else construction . Since there is no fundamental difference between them, let us dwell on the second variant, as the most usual one.
At the very beginning, we check whether the
$ text variable is filled in and whether the user's message is textual.
if($text){ …
If not, then send a message to the user using the sendMessage method asking to enter a text message.
6. Consider the option when the user sent a message with the commands
/ start or
/ help if ($text == "/start") { $reply = " !"; $reply_markup = $telegram->replyKeyboardMarkup([ 'keyboard' => $keyboard, 'resize_keyboard' => true, 'one_time_keyboard' => false ]); $telegram->sendMessage([ 'chat_id' => $chat_id, 'text' => $reply, 'reply_markup' => $reply_markup ]); }elseif ($text == "/help") { $reply = " ."; $reply_markup = $telegram->replyKeyboardMarkup([ 'keyboard' => $keyboard, 'resize_keyboard' => true, 'one_time_keyboard' => false ]); $telegram->sendMessage([ 'chat_id' => $chat_id, 'text' => $reply, 'reply_markup' => $reply_markup ]); }
In this case, in addition to the text from the
$ reply variable, a keyboard consisting of three buttons will be loaded: "Recent Articles", "Picture" and "Gif".
This is implemented using the
replyKeyboardMarkup method, the parameters of which are:
- 'keyboard' => $ keyboard , pass our keyboard
- 'resize_keyboard' => true , the keyboard will be compressed in size.
- 'one_time_keyboard' => false , the keyboard will not disappear after pressing a button.
7. After the appearance of the keyboard, the user obviously wants to try to poke on the buttons located on it, and this is what is “under the hood” in this case:
}elseif ($text == "") { $url = "https://68.media.tumblr.com/6d830b4f2c455f9cb6cd4ebe5011d2b8/tumblr_oj49kevkUz1v4bb1no1_500.jpg"; $telegram->sendPhoto([ 'chat_id' => $chat_id, 'photo' => $url, 'caption' => "." ]); }elseif ($text == "") { $url = "https://68.media.tumblr.com/bd08f2aa85a6eb8b7a9f4b07c0807d71/tumblr_ofrc94sG1e1sjmm5ao1_400.gif"; $telegram->sendDocument([ 'chat_id' => $chat_id, 'document' => $url, 'caption' => "." ]); }elseif ($text == " ") { $html=simplexml_load_file('http://netology.ru/blog/rss.xml'); foreach ($html->channel->item as $item) { $reply .= "\xE2\x9E\xA1 ".$item->title." (<a href='".$item->link."'></a>)\n"; } $telegram->sendMessage([ 'chat_id' => $chat_id, 'parse_mode' => 'HTML', 'disable_web_page_preview' => true, 'text' => $reply ]); }
8. To send a picture, use the
sendPhoto method, and to send a
gif ,
sendDocument . In both cases, Telegram allows you to send a direct link to a file, which is certainly very convenient, but not as fast as if we were transferring a
file_id of a picture already sent to the Telegram server or gifs.
9. For getting the latest articles, a simple Netting
RSS feed parsing is used with the built-in PHP function
simplexml_load_file .
In the parameters of the
sendMessage method,
you can notice two new values:
1)
'parse_mode' => 'HTML'
so that HTML tags can be inserted into the message
<b>, <a>, <i>, <code>
or
<pre>
2)
'disable_web_page_preview' => true
so that the message with the link does not load previews.
10. The
\ xE2 \ x9E \ xA1 characters are used as the smiley (right arrow). A list of all smiles in this form can be found on a special
site .
11. After you test the bot and are confident in its performance, you can send it to the public.
Thanks to a convenient API, Telegram bots can be a good platform for automating routine actions, setting up notifications, conveniently and quickly retrieving information and creating games.
Catalogs of bots
Telegram Bot Store ,
TeleChappy or
50bots can serve as free platforms for promotion.
And you can analyze user activity using the free bot analytics tool from Yandex -
Botan .
From the Editor
PHP is one of the most popular programming languages. He is easy to learn, easy to work with, he has a powerful community. On May 5th, Netology launches the course
PHP / SQL: back-end development and databases , where leading programmers will talk about control constructs, cycles, functions, strings and arrays. You will learn everything about relational databases and SQL query language, learn how to install and configure the nginx web server and php, manage databases of varying complexity. Waiting for you!