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

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 Table of contents:Building  an Arduino Fitness BoardFitnessboard - RequirementsFitnessboard … Continue reading "Arduino Fitnessboard v1 - Experiment"

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 & 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. which is then forwarded to the IP … Continue reading "self-construction - DynDNS-Alternative"

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! Table of … Continue reading "Program your own Screen Recorder / Capture Software"

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"

Privacy Browser for more security and privacy

More data protection, security and above all more privacy on the Internet is demanded from all sides, and not only after the entry into force of the EU-wide data protection basic regulation (). In general one can understand this wish, because who would like to voluntarily allow large IT companies to pass on their own … Continue reading "Privacy Browser for more security and privacy"

Leave a Reply

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

I have read and accepted the privacy policy!