Telegram Messenger and the Bot API - Part 2

telegram-messenger

In the first part - Telegram Messenger and the Bot API - I explained some basics how to set up a telegram bot and how to use it to send messages, information and more to your smartphone smartphone. Since this tool has proven to be very practical, I decided to take up the previous article again and expand it.

It's not about getting any information at a pre-defined time anymore, but simply to get in more or less direct contact with your backend. Here's an example of how to teach your messenger bot to respond to your messages. To keep the whole thing relatively short and crisp I will only explain the setup of the webhook and the processing of a command with a simple PHP script. For everything else concerning programming there are no limits to your own creativity. 😉

As already mentioned in part 1 there is the function setWebhook in the documentation of the Telegram Bot-API. This function is used to tell your Telegram Bot where to send messages received in the future. Here you send once a URL to the script on your server, which should process the messages and notifications.

The one-time call (e.g. via your own browser) for setup looks like this, where <BOT-TOKEN HERE> has to be replaced by your own Auth-Token. You also have to change the parameter URL so it will link to your script on your server webspace.

https://api.telegram.org/<BOT-TOKEN HERE>/setWebhook?url=https://www.meineseite.de/msg_receive_89572953227abdkjln438902.php&max_connections=5&allowed_updates=["message"]

If you do not only want to receive messages but also any other notification (see Telegram documentation), you simply omit the allowed_updates parameter or extend it by the respective events.

For security reasons it is recommended to put the script into a subfolder with an "exotic" name, which nobody can guess, or to name the script file that way. In my example the PHP-Script is called:
msg_receive_8957295322$!p7abdkjln438902.php

Now when the setup of the webhook is clear, we create the mentioned script on our server. Since Telegram sends the status message via JSON object (JSON-serialized) to the server, we have to accept it first. Then we convert the JSON object into an array.

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

if(!$request || !isset($request['message'])){
//request not valid
}else{
//good so far!
//Evaluate the message here and reply to the user.
}

To get an overview which information is in the array you can return it e.g. by $output = print_r($request, true); and write $output to a file or database on the server.

In this example only 3 information are interesting. The sender ID, user name and content of the message. We store these in a variable, for better clarity:

$sender_id = $request['message']['chat']['id'];
$username = $request['message']['chat']['username'];
$msg = strtolower(trim($request['message']['text']));

In the next and last step the switch is run through and if the command or message is known (e.g. "Hello World") then a suitable response is generated and sent to the user via telegram. If you send "Hello World" to the bot via telegram, it answers with "hello <username>! how are u? ;)". The code looks like this:

$answer = "";
switch ($msg)
{
case "hello world":
$answer = "hello ".$username."! how are u? ;)"; break;
}

if (strlen($answer)>0)
{
//Response to user; see Part 1
$request = TELEGRAM_URL;

$request = str_replace("<ID>", $chat_id, $request);
$request = str_replace("<TEXT>", urlencode($answer), $request);

$response = @file_get_contents($request);
$positive_answer = "{\"ok\":true";
$telegram_sent = (substr($response, 0, strlen($positive_answer)) == $positive_answer);
}

The Switch statement can now be extended by arbitrary cases and functions.

The code itself is certainly not perfect, but I hope it's easy to understand and helps as a small introduction to the subject.

Play with that - i wish you happy coding! 🙂

Author: Sascha from Tinkering-Sascha.com

Author: Sascha

Some words about myself. My name is Sascha - i'm in my mid-30s and a software developer and martial artist from germany. Besides programming and martial arts some of my interests and hobbies are cooking, fitness and hearing loud heavy metal music. :D

Related postings

My ShoppingList App / Grocery List App

Here are some informations, Screenshots and Download-Links for the Shopping List App (Pro-Version) for iOS- and Android-Devices.   Some cool new feature is, that you are now able to share, work and synchronize lists in realtime with other users (for example your wife or friend). When you go shopping at the supermarket and you strike … Continue reading "My ShoppingList App / Grocery List App"


My Recipes Book - Cooking Recipe Manager

Here are some informations, Screenshots and Download-Links for the Recipes Book App (Cookbook) for iOS- and Android-Devices. My Recipes - Create your own wonderful recipe collection on your and . My Recipes Book App - Description iOS (iPhone, iPad) A jewel in the kitchen. This wonderful recipe book you have your own culinary creations, grandmas … Continue reading "My Recipes Book - Cooking Recipe Manager"


Telegram Messenger and the Bot API

Telegram is basically a messenger similar to Whatsapp or Threema , free and easy to use. I don't want to say that it is better or worse than other messengers, but I like the Telegram Bot API so much that I want to write a little tutorial here. But first, some marginal information. Telegram is … Continue reading "Telegram Messenger and the Bot API"


self-construction - DynDNS-Alternative

If you already have your own webserver/webspace on the Internet and some programming knowledge, you can save yourself a service like DynDNS.org & Co. without much effort if you want to access parts of your home network from the road. Such services provide a host name/URL (e.g. my-home-network.dyndns.org) which is then forwarded to the IP … Continue reading "self-construction - DynDNS-Alternative"


Leave a Reply

Your email address will not be published. Required fields are marked *

I have read and accepted the privacy policy!