2.27.1. Telegram bot
Warning!
The bot can send messages only to those users who sent him any message and did not stop or block it.To work with a Telegram bot, it is recommended to use the information update method Webhook... This method is preferable to Long Polling, due to several factors:
- A script launched with Webhook is slightly faster than one that refreshes information at a specific interval.
- Within the framework of virtual and business hosting services, there is a limitation on the execution time of the process, and therefore the script cannot be constantly running and will be automatically terminated by the system. This limitation cannot be bypassed, so the use of a constantly running script can lead to data loss if this script terminates during the processing of an event.
Bot creation
- Write to Telegram bot @BotFather message
/newbot
to initialize the creation of a new bot. - The bot will ask you to specify the name of the new bot — you just need to send a message, which will be accepted as the name of the bot.
- The next step is to specify the name of the bot. The name differs from the name in that it will be a unique identifier with which you can use invitations, create links to it, etc. The word must be indicated at the end of the name
bot
... For example,examplebot
orexample_bot
. - The new message will indicate the token that will need to be used for the bot to work. Save this token.
Installing Webhook
Warning!
To work Webhook site necessarily must have a valid SSL certificate (Let's Ecnrypt certificate is also suitable).There are several ways to install Webhook:
https://api.telegram.org/bottoken/setWebhook?url=https://domain.com/path/to/file.php
In the link:
token
— specify the token received when creating the bot. Warning! Wordbot
change beforetoken
not necessary.domain.com
— correctly specify the domain that will work in the future. It is not recommended to specify an address with www or without www if a redirect to the return address is set.path/to/file.php
— indicate correct URL-address of the file itself, which will process the bot's requests.
After opening such an address in the browser, a message should appear on the open page like "Webhook was set"... If such a message appears, then the Webhook is installed correctly, otherwise double-check the used URL-address and SSL certificate operation.
Warning!
The script must have a condition that will limit the number of launches of installing / checking Webhook, since frequent calls to Telegram will give an error and stop the script.Add the following code at the beginning of your script, after declaring variables with token and bot name data:
if(!json_decode(file_get_contents("https://api.telegram.org/name:token/setWebhook?url=https://domain.com/path/to/file.php"))->ok){die('webhook is not set');}
An example of a simple bot
For an example of the simplest bot, there are many options for implementation. But this article will consider two of the simplest.
/start
:<?php define('token','XXXXXXXXXXXXXXXXXXXXXXXXX'); // вместо ''XXXXXXXXXXXXXXXXXXXXXXXXX'' specify your token $result = json_decode(file_get_contents('php://input'), true); // передаём в переменную $result full information about the user's message if ($result['message']['text'] == '/start') { file_get_contents("https://api.telegram.org/bot" . token . "/sendMessage?chat_id=" . $result['message']['chat']['id'] . "&text=" . urlencode('Hi')); // отправляем ответ пользователю, используя его уникальный идентификатор $result['message']['chat']['id'] as recipient }
<?php include('vendor/autoload.php'); // подключаем библиотеку use Telegram\Bot\Api; $telegram = new Api('XXXXXXXXXXXXXXXXXXXXXXXXX'); // вместо ''XXXXXXXXXXXXXXXXXXXXXXXXX'' specify your token $result = $telegram -> getWebhookUpdates(); // передаём в переменную $result full information about the user's message $text = $result["message"]["text"]; // текст сообщения $chat_id = $result["message"]["chat"]["id"]; // уникальный идентификатор пользователя $name = $result["message"]["from"]["username"]; // имя пользователя if ($text) { if ($text == "/start") { $reply = "Hi!"; $telegram->sendMessage(['chat_id' => $chat_id, 'text' => $reply]); } }