Telegram Messenger and the Bot API - Part 2


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.

Table of contents:

Using Telegram Messenger and the Bot API

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

kraken.jpgAs 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.<BOT-TOKEN HERE>/setWebhook?url=["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:

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
//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

kraken.jpgThe 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.

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);

$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";
echo "0";


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

Author: Sascha

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

This might also be interesting for you

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"

pi_robot - Playing with Raspberry Pi, iPad and some Code

The Raspberry Pi is still one of the most popular mini computers, not only among hobbyists. Cost-effective (about 30 to 40,- EUR depending on the model), flexible in the field of application and at the latest since the equipped with enough CPU power and memory to solve even more complex tasks. With the 1.2 GHz … Continue reading "pi_robot - Playing with Raspberry Pi, iPad and some Code"

Programming: PHP image captcha code

Here I would like to present my small but nice capture code solution, which I programmed some time ago. I was tired, also with regard to the german DSGVO (privacy laws), to include capture solutions of external providers. In addition, various privacy browsers block e.g. also javascripts, so that an external image capture module for … Continue reading "Programming: PHP image captcha code"

Training equipment: Makiwara 2.0

A Makiwara is a piece of sports equipment originating from Japan, which in karate is known mainly as a wooden hitting post. In the past (and partly still today) a makiwara is made of a flexible and non-splintering wooden board. One end of the board is driven vertically into the ground, and the other end … Continue reading "Training equipment: Makiwara 2.0"

Smart Home V1 - Do it yourself

I've been planning my smart home for some time now. Besides the cost factor for all the great things I imagine, I often lack the necessary time for detailed planning and implementation. So I decided to start somewhere and write down this DIY project in parallel...let's see where it leads...I ask for your indulgence if … Continue reading "Smart Home V1 - Do it yourself"

Leave a Reply

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

I have read and accepted the privacy policy!