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, states, informations 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. Below I will also explain how to send photos, images and screenshots via Telegram API.

Telegram Bot API - SetWebhook

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.

Send photos by Telegram Bot API

The Bot-API from Telegram offers several possibilities to send photos, pictures or screenshots.

Currently there are 3 options:
1.) Send pictures via file_id which have already been uploaded to Telegram.
2.) Send images via URL, which are located on a webserver.
3.) Upload pictures or photos directly to Telegram.

I will only present the 3rd option here, as it is probably the most frequently used.

Generally the sending of photos via Telegram is done via sendPhoto-Request (see Bot-API documentation). The URL to which you send this request looks like this, where BOT_API_KEY and EMPFAENGER_ID have to be replaced by the corresponding values.

https://api.telegram.org/BOT_API_KEY/sendPhoto?chat_id=EMPFAENGER_ID

As an example I pass an image via POST as a string base64-encoded, which is then calculated back to the original image, temporarily stored and sent (multipart/form-data). $tele_id contains the ID of the receiver and TELEGRAM_URL_PHOTO is your request URL (see above /sendPhoto). For sending curl is used.

The PHP code will look like this:

$imageBase64 = (isset($_POST['image'])) ? $_POST['image'] : "";

if (strlen($imageBase64)>0 && strlen($tele_id)>0)
{
$request = str_replace("<ID>", $tele_id, TELEGRAM_URL_PHOTO);

$filename = "tmp/screen.jpg";
$img = base64_decode($imageBase64);
$im = imagecreatefromstring($img);
imagejpeg($im, $filename);
imagedestroy($im);

$post_fields = array('chat_id' => $tele_id,
'photo' => new CURLFile(realpath($filename))
);

$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type:multipart/form-data"));
curl_setopt($ch, CURLOPT_URL, $request);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields);
$response = curl_exec($ch);

$positive_answer = "{\"ok\":true";
if (substr($response, 0, strlen($positive_answer)) == $positive_answer)
echo "1";
else
echo "0";

return;
}

The code itself is certainly not perfect. Of course you should parse the JSON telegram response and evaluate the return value (status) instead of the hardcoded string, but I hope the functionality is easy to understand and it helps as a small introduction to the game.

Have fun progging! If you like this post, feel free to leave a comment. 🙂

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

Arduino Fitnessboard v1 – Experiment

On the weekend I fortunately had some time for handicrafts and a nice idea for a fitness board for training at home, which is operated from the push-up position. A video can be found further down in this article and on the Youtube channel of tedokai.de. Everyone who does sports at home knows the problem … Continue reading “Arduino Fitnessboard v1 – Experiment”


Program your own Screen Recorder / Capture Software

While searching for an easy to use screen recorder tool, I stumbled across all kinds of free and paid software solutions. From my point of view, pretty much all of them were either completely overloaded, difficult or complicated to use. Others were just expensive in relation to the functionality. My conclusion: Program yourself! Program your … Continue reading “Program your own Screen Recorder / Capture Software”


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”


Unity 2D Platformer – Level Generator

For some time now I have been experimenting here and there with the 2D and 3D engine Unity. Especially the programming of a 2D-Platformers has been very interesting for me. However, programming a 2D game (if you are a programmer) is not the biggest problem, but in my opinion the look, because I am not … Continue reading “Unity 2D Platformer – Level Generator”


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”


Leave a Reply

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

I have read and accepted the privacy policy!