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:
To create a bot, follow these steps:
/newbot
to initialize the creation of a new bot.bot
... For example, examplebot
or example_bot
.There are several ways to install Webhook:
https://api.telegram.org/bottoken/setWebhook?url=https://domain.com/path/to/file.php
Substitute your values for the following parameters:
token
- specify the token received when creating the bot. Note, change before token
word bot
not necessary.domain.com
- correctly specify the domain name 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 that will process bot 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.
To install Webhook in the script, it is enough at its beginning, after declaring variables with the data of the token and the bot name, specify the following code:
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');}
For an example of a simple bot, there are many implementation options. But this article will consider two of the simplest.
/start
looks something like this:<?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]); } }