- Webhook & Updates
- Getting Updates
- Via Webhook
- Setting Webhook
- Laravel Route Setup
- Getting Webhook Update
- Long polling — готовые решения?
- How to Create a Telegram Bot With PHP
- What We Are Going to Do
- Get a Telegram Bot Token
- Connect to Botan Analytics
- Create and Register an SSL Webhook
- Build a Database
- Create a Stopwatch Class
Webhook & Updates
Working with Webhook Updates & Manually Fetching Updates (Long-polling).
Getting Updates
There are two mutually exclusive ways of receiving updates for your bot — the getUpdates() method on one hand and Webhooks on the other. Incoming updates are stored on the Telegram server until the bot receives them either way, but they will not be kept longer than 24 hours.
Regardless of which option you choose, you will receive Update objects as a result.
Via Webhook
In order to receive updates via a Webhook, you first need to tell your webhook URL to Telegram. You can use setWebhook($url) method to specify a url and receive incoming updates via an outgoing webhook.
Whenever there is an update for the bot, Telegram will send an HTTPS POST request to the specified url, containing an Update object. In case of an unsuccessful request, Telegram will give up after a reasonable amount of attempts.
If you’d like to make sure that the Webhook request comes from Telegram, we recommend using a secret path in the URL, e.g. https://www.example.com//webhook . Since nobody else knows your bot’s token, you can be pretty sure it’s Telegram who made the request.
See setWebhook docs for a list of supported parameters and other info.
Setting Webhook
$response = $telegram->setWebhook(['url' => 'https://example.com//webhook']); # Or if you are supplying a self-signed-certificate $response = $telegram->setWebhook([ 'url' => 'https://example.com//webhook', 'certificate' => '/path/to/public_key_certificate.pub' ]);
$response = Telegram::setWebhook(['url' => 'https://example.com//webhook']); # Or if you are supplying a self-signed-certificate $response = Telegram::setWebhook([ 'url' => 'https://example.com//webhook', 'certificate' => '/path/to/public_key_certificate.pub' ]);
Laravel Route Setup
Setup a POST route //webhook .
You need to add your route in $except array inside the app/Http/Middleware/VerifyCsrfToken.php file in order to bypass the CSRF Token verification process that takes place whenever a POST route is called.
Here’s an example based on the above case scenario:
protected $except = [ '//webhook' ];
- You will not be able to receive updates using getUpdates() for as long as an outgoing webhook is set up.
- To use a self-signed certificate, you need to upload your public key certificate using certificate parameter. Please pass the absolute path to the certificate when uploading.
- Ports currently supported for Webhooks: 443, 80, 88, 8443.
If you’re having any trouble setting up webhooks, please check out this amazing guide to Webhooks.
Getting Webhook Update
Once you set the webhook, You can then use the below function to retrieve the updates that are sent to your Webhook URL. The function returns an array of Update objects.
$updates = $telegram->getWebhookUpdate();
Long polling — готовые решения?
Здравствуйте, я делаю telegram бота и использую Webhook. Но есть ряд проблем, и решил попробовать Long polling. Есть ли готовые решения с Long polling или хорошие примеры. С Long polling никогда не работал раньше.
1. Ставишь composer, далее переходишь в папку с проектом через командную строку (cd c://bot — пример), выполняешь код:
«composer require guzzlehttp/guzzle».
2. Создаешь init.php, в этой папке, с содержимым:
// Инклуды)
use GuzzleHttp\Client;
include(‘vendor/autoload.php’);
include(‘telegramBot.php’);
//Получаем данные
$telegramApi = new TelegramBot();
// Вычный цикл, обработчик
while (true) sleep(2);
$updates = $telegramApi->getUpdates(); // Получаем обновление, методом getUpdates
foreach ($updates as $update) if (isset($update->message->text)) < // Проверяем Update, на наличие текста
$text = $update->message->text; // Переменная с текстом сообщения
$chat_id = $update->message->chat->id; // Чат ID пользователя
$first_name = $update->message->chat->first_name; //Имя пользователя
$username = $update->message->chat->username; //Юзернейм пользователя
if ($text == ‘/start’) < // Если пользователь подключился в первый раз, ему поступит приветствие
$telegramApi->sendMessage($chat_id, ‘Привет’. ‘ ‘ . $first_name . ‘!’); //Приветствует Пользователя
> else $telegramApi->sendMessage($chat_id, $first_name . ‘! Как дела?’ ); // Спрашивает как дела
3. Создаешь telegramBot.php, в этой папке, вот содержимое:
// Подключение библиотеки
use GuzzleHttp\Client;
use Telegram\Api;
$client = new Client([
‘base_uri’ => $url
]);
// Получаем обновления
public function getUpdates()
$response = $this->query(‘getUpdates’, [
‘offset’ => $this->updateId + 1
]);
if (!empty($response->result)) $this->updateId = $response->result[count($response->result) -1]->update_id;
>
return $response->result;
>
// Отправляем сообщения
public function sendMessage($chat_id, $text)
$response = $this->query(‘sendMessage’,[
‘chat_id’ => $chat_id,
‘text’ => $text
]);
return $response;
>
4. Что бы запустить его, там же в командной строке запускаешь файл:
php init.php
Там же в консоли увидишь Id пользователя и его юзернейм)
Вот такой не много туповаты пример, но работает.
How to Create a Telegram Bot With PHP
Anton Bagaiev Last updated Aug 3, 2016
The bot revolution is not only about artificial intelligence. A bot can be a tool in your messenger with a simple chat interface that can be used to extend the functionality of sites or services or can even be a standalone application. Bots are cheaper to develop and easier to install, and another great feature is that messengers can be used on every type of device—laptops, smartphones, and tablets. That’s why everybody is crazy about bots now.
And the biggest messenger with an open bot API is Telegram.
What We Are Going to Do
In this article you’ll learn how to create a Telegram bot, connect with analytics, write some code, and finally add your bot to a bot store.
By the way, I’ve already prepared a demo, so you can test it just by adding @stopwatchbot to your Telegram contact list.
Get a Telegram Bot Token
The first step to get a Telegram bot token. And there is a bot for that, called the BotFather. Just add it to your contact list and you’ll be able to create and set up Telegram bots, just by typing the /newbot command and following the instructions of BotFather.
After registering your new bot, you will receive a congratulations message with an authorization token. We will use this token soon to authorize a bot and send requests to the Bot API.
Later you can use BotFather to add descriptions or photos to the profiles of your bots, regenerate tokens, set lists of commands to use, delete accounts, and so on. To get a full list of commands, just type /help in a chat to get a list of BotFather’s commands.
Connect to Botan Analytics
There is no built-in analytics in the Telegram Bots API, but it’s important to know how many users you have, how they act, and which commands they trigger more. Of course, we can collect this information using our own engine, but if we want to focus on bot functionality, not metrics, we just need to use an out-of-the-box solution.
And there is a simple tool to connect your bot to analytics, called Botan. It’s based on Yandex AppMetric and completely free. Using Botan, you can segment your audience, get information about user profiles, get the most used command, and get beautiful graphs right in your messenger, like this:
To get started, you need to register your bot in Botan and get a token. And again, you can do it with a bot, BotanioBot:
Just click the “Add bot” key on the dialog keyboard, type the nick of your bot, and you will get your bot track token. Now Botanio is ready to track your bot events, and you can get statistics by users, sessions, retention and events right in your messenger.
Create and Register an SSL Webhook
In Telegram there are two ways to get messages from your users: long polling and webhooks.
Basically, with long polling, you need to request new messages from the API, and with webhooks you are setting a callback that the Telegram API will call if a new message arrives from a user. I prefer to use webhooks because it looks like real-time communication, so in this article we will use this method too. Now we need to choose a callback URL for our webhook, which needs to be reached under the HTTPS protocol, and we need to set it really secure, so hide your script in a secret path, as the manual says:
If you’d like to make sure that the Webhook request comes from Telegram, we recommend using a secret path in the URL, e.g. https://www.example.com/ . Since nobody else knows your bot‘s token, you can be pretty sure it’s us.
If your SSL certificate is trusted, all you need to do is open this URL in your browser:
https://api.telegram.org:443/bot[token]/setwebhook?url=[webhook]
Otherwise you have to generate a self-signed certificate. Here is an example of the command on Linux for it:
openssl req -newkey rsa:2048 -sha256 -nodes -keyout /path/to/certificate.key -x509 -days 365 -out /path/to/certificate.crt -subj "/C=IT/ST=state/L=location/O=description/CN=yourdomain.com"
And don’t forget to open the SSL port:
To get the certificate checked and set your webhook domain to trusted, you need to upload your public key certificate:
-F "url=https://yourdomain.com/path/to/script.php" \
-F "certificate=/path/to/certificate.key" \
"https://api.telegram.org/bot[token]/setwebhook"
Finally you will get a JSON reply like this:
"ok":true,"result":true,"description":"Webhook was set">
It says that the webhook was set and we are ready to start the engine of the bot.
Build a Database
Now we need to build a database for our timers. What do we need to store in it? When a user commands the stopwatch to start, we will take the ID of the chat and save a row with the chat ID and current Unix time, which is the number of seconds between now and the start of Unix Epoch, which is 1 January 1970 at UTC. Consequently, we will save a row with the chat ID and integer timestamp of the current Unix time.
To show the current stopwatch time, we will get the saved timestamp and compare it with the current timestamp. The difference will be the current time in seconds. If the user stops the timer, we will simply delete the row with the current chat ID.
So let’s create a database and table to store the stopwatch information:
CREATE TABLE IF NOT EXISTS `stopwatch` (
`chat_id` int(10) unsigned NOT NULL,
`timestamp` int(10) unsigned NOT NULL,
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Create a Stopwatch Class
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: