Telegram Messenger and the Bot API

telegram-messenger

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.

Table of contents:

Using Telegram Messenger and the Bot API

Amazon

But first, some marginal information. Telegram is completely free, and you can use the API without any costs. The Telegram Messenger encrypts all data according to the manufacturer's specifications. A combination of 256-bit symmetric AES encryption, 2048-bit RSA encryption and the secure Diffie-Hellman key exchange method is used. The app is available for all common operating systems: Windows, Mac, Linux, iOS (iPhone, iPad), Android and WindowsPhone. The Messenger can also be operated platform independent via a web browser.

The really nice thing about Telegram is the easy to use Telegram Bot API. So as a developer you are able to automate news, status updates or other information quickly and easily via Telegram directly to your smartphone smartphone or other users. The API is based on the HTTP protocol and can therefore be connected to any common platform and programming language.

I use multiple bots. Simple example: One of the bots sends me a notification if one of the servers is down. For this the servers "talk" constantly (or every 30 minutes) also via simple HTTP requests. If one server doesn't answer, the other one can send me a message and I can see what's going on. There are countless application examples, there are no limits to creativity! 😉

Step 1 - Setting up the Telegram Bot

First you should install the Telegram Messenger (Telegram.org) on your Smartphone.

Telegram Bot FatherIn the chat overview, tap on the "New Message" icon in the upper right corner and enter "Botfather" in the search field.

This is, as the name suggests, the telegram bot for the bots.

You simply write /start or /help to it and get a list of commands to create and configure your own bot.

Now enter /newbot as command and answer a few basic questions, e.g. what your bot should be called, i.e. which username it will be reachable with later.

Then you get an API access token, which is needed later for sending messages and all other functions. This must always be passed in the requests to the telegram server.

Step 2 - Setting up the recipient on the user side

Now we ask for the ID (unique number of your user account / USER, NOT of the bot!) of the user to whom we want to send messages later. This number is the recipient address of the messages.

For this we simply write /start to the user "userinfobot" from the Telegram app. The answer you get is his username, ID, and maybe the fore- and lastname (if given ;-)). The ID is important, so we write it down for later.

To make sure that your own bot can write to you later, just send /start to your new bot, as you did with the Botfather. (see step 1)

Step 3 - A small PHP script to send messages to ourselves

Now we build a small PHP script which sends a short message when called. A short look into the documentation of the Telegram-Bot-API and it becomes clear what the HTTP-Request for sending a message has to be. I have defined a constant for this. This looks like this in PHP:

define("TELEGRAM_URL", "https://api.telegram.org/bot<TOKEN>/sendMessage?chat_id=<ID>&text=<TEXT>");

In pointed brackets I have inserted 3 placeholders which are needed. The <Token> (your access token you got from the botfather, see step 1), the <ID> (the ID of the recipient, see step 2) and the <Text>. These are now filled with your values, either directly in the define statement, or a little more flexibly for later use simply via str_replace statement.

$request = TELEGRAM_URL;
$request = str_replace("<TOKEN>", "hier token eingeben", $request);
$request = str_replace("<ID>", "hier id des empfängers", $request);
$request = str_replace("<TEXT>", urlencode("Message here! Hello World!"), $request);

Now the variable $request contains the correct URL to send the test message to yourself. For testing you can easily send the message to the telegram server via file_get_contents. If necessary, set allow_url_fopen to true in the PHP configuration. - * not necessarily recommended for productive use *

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

After file_get_contents we check whether the message was sent correctly by evaluating the return value, i.e. the response of the Telegram server. If the answer is "Ok:true", then the variable $telegram_sent is set to true. If an error has occurred, this is indicated by the content of the variable $response and can be evaluated further.

AmazonReady! If you now load the script onto your server and call it out, it sends the desired message to the respective Telegram user. Now you have a simple basis, which you can extend by functionality.

If you want to talk to your bot, or if you want it to react to requests, you should have a look at the function setWebHook in the documentation. With this hook you can get the telegram servers to send a notification to any script on your server when a user writes to the bot.

What you make of it, everyone has to know for himself. How to answer the user you know now after this little tutorial... hope you like this. 😉 *happy coding*

Update: The continuation of this article on how to set up setWebhook and respond to messages from the user can be found here: Telegram Messenger and the Bot API - Part 2

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


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. Table of contents:My ShoppingList App / Grocery List AppShopping List App – Description iOS (iPhone, iPad)Shopping List App – Description AndroidShopping-/Grocery-List App – Free-Version My ShoppingList App / Grocery List App   Some cool new feature is, that … Continue reading “My ShoppingList App / Grocery List App”


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”


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!