Website development

We are Makklays. We help to realize the idea.

BOT Telegram in PHP


Makklays - Articles image

eye 39


Now many people write about the practicality, modernity and usefulness of using bots to obtain various kinds of statistics or data, easing the load on the site and call centers. Yes, BOT in a messenger, in this case Telegram, is very convenient on a mobile phone. It is also very fast - the exchange of data between the phone and the site in json format is only a few bytes.

You can only imagine how convenient it is to use the bot, for example, on your online store or corporate website. For example, when a user needs to know the status of his order or the cost of a particular service or product. The user no longer needs to call and annoy you with his questions. Using modern production automation, he can log into Telegram and your bot, using the specified commands (and the user's order number), will give him the necessary answers 24 hours a day without attracting your attention (or variable costs for answers from your staff). This is only a small part of the advantages of using a bot, but it is already quite tangible and noticeable in modern conditions of reducing the time for routine work and business development.

The bot is convenient to use when polling or testing users. Since the messenger allows you to get quick answers from the user who uses it and save this data in the database for later use (summarizing statistics, obtaining data, building graphs based on the results of user responses).

Let's figure out how to make a BOT for Telegram. Believe me, it's very simple (I personally figured it out in the evening) in a simple interpretation. But, it is difficult if you connect the processing of statistical data on the site and return the result of this data to sql queries, etc. back to the phone (I mean some kind of extraordinary development of yours). To develop a Telegram Bot, you need to take a few simple steps:

✔ Bot registration
✔ Receiving incoming messages
✔ Photos
✔ Document
✔ Developing bot responses

According to the official Telegram documentation, all requests are sent via the HTTPS protocol. "Let's Encrypt" - a free certificate is fine too. Since Telegram is blocked in the Russian Federation, you will need to use a proxy (if you are from the Russian Federation).



BOT REGISTRATION



To register a new bot, you need to write to the bot with the name @BotFather "dad of bots" (find a bot with this name in Telegram) and execute the command /newbot

In the next message, indicate the name of your bot, at the end there must be "bot" or "_bot" (the name can be edited later). In the response message, we will receive the token of our bot. We copy the token, it will still be useful to us when we start making WebHook. As you can see from the list of commands

/setname - Name
/setdescription - Short description
/setabouttext - Bot description
/setuserpic - Userpic

we can make additional settings for our bot using @BotFather.
Next, set up WebHook is when all messages from Тelegram come to PHP file/script (https://somesite.com/bot.php) on your website. To do this, you need to follow the link in which the token and the correct address to your file on the site are inserted.

https://api.telegram.org/bot<token>/setWebhook?url=https://somesite.com/bot.php

where token is your token, and url - your address to the script on the site (with https)

In response, we get the following:
{"ok":true,"result":true,"description":"Webhook was set"} 

Please note that when changing the token, the WebHooka installation must be repeated.
Otherwise, how does Telegram know that you have a new url to the message processing script from Telegram?



GETTING INCOMING MESSAGES



All messages come as a POST request, with the data type application / json. You can get messages in PHP like this:


$data = file_get_contents('php://input');
$data = json_decode($data, true);

To view incoming messages, they need to be written to a file:

ob_start();
print_r($data);
$out = ob_get_clean();
file_put_contents(__DIR__ . '/message.txt', $out);

It looks like this:

Array (
[update_id] => 17584194
[message] => Array (
[message_id] => 26
[from] => Array (
[id] => 123456789
[is_bot] =>
[first_name] => UserName
[language_code] => ru-US
)
[chat] => Array (
[id] => 123456789
[first_name] => UserName
[type] => private
)
[date] => 1541888068
[text] => Hello bot!
)
)

We get the message text:

if (!empty($data['message']['text'])) {
$text = $data['message']['text'];
echo $text;
}


PHOTOS



When sending a photo to a bot, an array of thumbnails is sent to the script file, the last element will be the original photo. The maximum file size is 20MB.

Request from Telegram:


Array (
[update_id] => 17584194
[message] => Array (
[message_id] => 38
[from] => Array (
[id] => 123456789
[is_bot] =>
[first_name] => UserName
[language_code] => ru-US
)
[chat] => Array (
[id] => 123456789
[first_name] => UserName
[type] => private
)
[date] => 1541924962
[photo] => Array (
[0] => Array (
[file_id] => AgADAgADUqexG7u8OEudBvlhgMzKC1agOQ8ABC6Bx26USA7Mw3gAAgI
[file_size] => 1196
[width] => 51
[height] => 90
)
[1] => Array (
[file_id] => AgttAgADUqoxG7u8OEudBvlhgMzKC1agOQ8ABKwp_3jDPrIlxHgAAgI
[file_size] => 21146
[width] => 180
[height] => 320
)
[2] => Array (
[file_id] => AgADAgADUqyxG7u8OEudBvlhgMzKC1agOQ8ABAN8gJWpUT1MxXgAAgI
[file_size] => 90940
[width] => 449
[height] => 800
)
[3] => Array (
[file_id] => AgADAgADUqouu7u8OEudBvlhgMzKC1agOQ8ABIqVC1nEpbLDwngAAgI
[file_size] => 114363
[width] => 719
[height] => 1280
)
)
)
)

To download a file, you need to send a POST or GET request to receive an image with the file_id parameter by the URL:
https://api.telegram.org/botbot<token>/getFile

In response, you will receive information about the file:

Array (
[ok] => 1
[result] => Array (
[file_id] => AgADAgADUqoxG5u88E0dBvlhgMzKC1agOQ8ABIqVC1nEpbLDwngAAgI
[file_size] => 114363
[file_path] => photos/file_1.jpg
)
)

Further it can be downloaded from the link:
https://api.telegram.org/file/botbot<token>/bot<file_path>

And in PHP, saving a file to the server can be implemented as follows:
$token = '123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11';

if (!empty($data['message']['photo'])) {
$photo = array_pop($data['message']['photo']);

$ch = curl_init('https://api.telegram.org/bot' . $token . '/getFile');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, array('file_id' => $photo['file_id']));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, false);
$res = curl_exec($ch);
curl_close($ch);

$res = json_decode($res, true);
if ($res['ok']) {
$src = 'https://api.telegram.org/file/bot' . $token . '/' . $res['result']['file_path'];
$dest = __DIR__ . '/' . time() . '-' . basename($src);
copy($src, $dest);
}
}


DOCUMENT


Request from Telegram:


Array (
[update_id] => 17474201
[message] => Array (
[message_id] => 44
[from] => Array (
[id] => 123456789
[is_bot] =>
[first_name] => UserName
[language_code] => ru-US
)
[chat] => Array (
[id] => 123456789
[first_name] => UserName
[type] => private
)
[date] => 1541925844
[document] => Array (
[file_name] => IMG_7947.JPG
[mime_type] => image/jpeg
[thumb] => Array (
[file_id] => AAQCABMNv_QOAATwQugveIZBldZ3AAIC
[file_size] => 2644
[width] => 67
[height] => 90
)
[file_id] => BQADAgADtQEAAqu9OEhzn2cEz8LpkgI
[file_size] => 1976218
)
)
)

Files are downloaded in the same way as for photos.

if (!empty($data['message']['document'])) {
$file_id = $data['message']['document']['file_id'];

$ch = curl_init('https://api.telegram.org/bot' . $token . '/getFile');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, array('file_id' => $file_id));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, false);
$res = curl_exec($ch);
curl_close($ch);

$res = json_decode($res, true);
if ($res['ok']) {
$src = 'https://api.telegram.org/file/bot' . $token . '/' . $res['result']['file_path'];
$dest = __DIR__ . '/' . time() . '-' . basename($src);
copy($src, $dest);
}
}


DEVELOPMENT OF BOT ANSWERS


Sending text

$response = array(
'chat_id' => $data['message']['chat']['id'],
'text' => 'Hey!'
);

$ch = curl_init('https://api.telegram.org/bot' . $token . '/sendMessage');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $response);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_exec($ch);
curl_close($ch);

Sending a picture

$response = array(
'chat_id' => $data['message']['chat']['id'],
'photo' => curl_file_create(__DIR__ . '/image.png')
);

$ch = curl_init('https://api.telegram.org/bot' . $token . '/sendPhoto');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $response);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_exec($ch);
curl_close($ch);

File upload

$response = array(
'chat_id' => $data['message']['chat']['id'],
'document' => curl_file_create(__DIR__ . '/file.xls')
);

$ch = curl_init('https://api.telegram.org/bot' . $token . '/sendDocument');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $response);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_exec($ch);
curl_close($ch);