Telegram bot get Webhook Updates send message

Panjeh
6 min readMay 25, 2019

This tutorial helps you to set telegram bot webhook simply in 5 minutes by following 7 steps.

After you understand what is happening in Telegram Bot, for a better experience, I recommend you use one of these best telegram bot libraries. Here

Setting Telegram Bot WebHook, get updates and then sending a message to a Telegram bot:

Step 1: making a bot

First visit the father of bots in telegram: https://t.me/@BotFather

Then run this command in @BotFather to create a new bot:

/newbot

After this command botFather asks you:

Alright, a new bot. How are we going to call it? Please choose a name for your bot.

So give it a name and then botFather again asks you for the bot username:

Good. Now let’s choose a username for your bot. It must end in `bot`. Like this, for example: TetrisBot or tetris_bot.

As and example, I chose this username: mediumtelegramBot

Then botFather replied me this message which includes what I need: Telegram bot Token:

Use this token to access the HTTP API:70360V526:ADHMSEH1eoPfd3YSCppzYdL7PnKYxtk5k10

Step 2: downloading a prepared telegram bot code example

Now visit this package: https://github.com/Eleirbag89/TelegramBotPHP which is a very simple PHP Telegram Bot API for sending messages.

We are going to use some files of this package in a simple way and not use this package comprehensively.

In local make a directory and then download and put these files in it:

1- Telegram.php from here raw format here

2- TelegramErrorLogger.php from here raw format here

Step 3: Being familiar with getting telegram bot updates via getUpdate or Webhooks

In this step you should know this fact:

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 JSON-serialized Update objects as a result.

Simply, getUpdates method is useful when you are going to get updates manually by calling Telegram server minute by minute to see wheter there is any more updates? while Webhook in the other side is for asking Telegram server to call your bot server as soon as a user send a message or command to the bot and every thing is automatic. It depends to you and your case. But I prefere WebHooks.

Reference : Link1 , More about webhook Link2

Step 4: Testing Telegram bot and getting updates

Now I open the bot that I created already in Telegram app and start it. Then type a message and send it to the bot.

Then in the browser check the following url after putting the correct telegram bot token in it.

https://api.telegram.org/bot{token}/getUpdates

I replaced the token that I got it in step 1. Something like this :

https://api.telegram.org/bot70360V526:ADHMSEH1eoPfd3YSCppzYdL7PnKYxtk5k10/getUpdates

I will see a JSON update like this:

{ok: true,result: [        {             update_id: 11223344,             message: {                  message_id: 2,             from: {                  id: 123456789,                  is_bot: false,                  first_name: "",                  username: "",                  language_code: "en"             },             chat: {                  id: 123456789,                  first_name: "",                  username: "",                  type: "private"             },             date: 1558784616,             text: "My first message to this bot"             }        }        ]}

You have another option to get the updates withoud need to trigger the above url. see the next step.

Step 5: response to the user messages by getUpdates method

Download this file raw format here and put it (getUpdates.php) in the directory you created beside the Telegram.php and TelegramErrorLogger.php files you have got in step 2.

Now you have 3 file in this directory:

Telegram.php, TelegramErrorLogger.php and getUpdates.php

Then install valet. valet by default is set on .test domain. Then via terminal go to the directory of the project you created and do

valet park
valet link telegramproject

After doing “valet link telegramproject” you can reach your project in the browser.

telegramproject.test/

and can response to the messages receieved by telegram bot via triggering this:

telegramproject.test/getUpdates.php

As an example in the bot type this: /git and then trigger this url: telegramproject.test/getUpdates.php and see the automatic response!

If you look at the getUpdates file content you will see:

if ($text == '/git') {
$reply = 'Check me on GitHub: https://github.com/Eleirbag89/TelegramBotPHP';
// Build the reply array
$content = ['chat_id' => $chat_id, 'text' => $reply];
$telegram->sendMessage($content);
}

Step 6: setting Webhook

First of all you need a php file as a Webhook to handle the Telegram server request after calling our bot server.

For this aim I made in my project this file: update.php

and put in it this content:

<?phpinclude 'Telegram.php';$bot_token = '70360V526:ADHMSEH1eoPfd3YSCppzYdL7PnKYxtk5k10';$telegram = new Telegram($bot_token);$text = $telegram->Text();$chat_id = $telegram->ChatID();$content = array('chat_id' => $chat_id, 'text' => 'Hello');$telegram->sendMessage($content);

Then I have to introduce to Telegram server the webhook address of the bot server. Telegram server needs HTTPS. So I need to use ngrok.io service. After installing ngrok in terminal when I am in the project dirctory I do:

valet share

Then ngrok publish our project into a secure url something like

https://904db06e.ngrok.io -> telegramproject.test:80

Our next task is to introduce the new https address as a webhook to Telegram server. Something like this:

https://api.telegram.org/bot{my_bot_token}/setWebhook?url={url_to_send_updates_to}

In my case it will be:

https://api.telegram.org/bot70360V526:ADHMSEH1eoPfd3YSCppzYdL7PnKYxtk5k10/setWebhook?url=https://904db06e.ngrok.io/update.php

Then trigger the above url. And you see:

{
ok: true,
result: true,
description: "Webhook was set"
}

In this way if you send any message to the telegram bot you will see the automatic response ‘Hello’.

Step 7: More info and attention

If you set a webhook you can not get updates like what you see in steps 4 and 5.

If you want to delete or deactive the bot webhook you need to trigger this url after replacing the correct bot token:

https://api.telegram.org/bot{my_bot_token}/deleteWebhook

Obtain information about Webhook:

To get information about webhook parameters use the following url after replacing the correct bot token.

https://api.telegram.org/bot{my_bot_token}/getWebhookInfo

The response would be:

{
ok: true,
result: {
url: "https://904db06e.ngrok.io/update.php",
has_custom_certificate: false,
pending_update_count: 0,
max_connections: 40
}

You can also customise max_connections.

Thank you for reading! If you enjoyed this article:

Clap it ! Share it! Follow Me in Medium!

I would like to introduce two packages for Laravel that I have recently developed: Laravel Pay Pocket, a modern multi-wallet package, and Laravel Failed Jobs, a UI for the Laravel Failed Jobs Table. I hope they may be of help to you.

https://github.com/HPWebdeveloper/laravel-pay-pocket
https://github.com/HPWebdeveloper/laravel-failed-jobs

Also I’d like to hear your opinion on this article. If you have any doubt, question or suggestion please leave a comment below.

Have a very wonderful day!

Previous Stories You will Love:

--

--