Telegram is a popular instant messaging service that prides itself on security. It has all of the features you would expect from a modern chat platform, including chatbots: software-based agents that you can program to read and respond to other users’ messages.

In this short guide, I’ll walk you through how you can write your own Telegram bot in under 30 minutes using PHP.

Step One: Setup Your Bot’s Telegram Profile

The first step in creating a Telegram bot is setting up the profile that the bot will ultimately stand behind. This is also how you get a token for the Telegram API.

To set up a new bot profile, log in to your Telegram account and start a conversation with the BotFather (@BotFather), an official account that allows you to create and manage bots. In that conversation, enter the /newbot command.

The BotFather will ask you to choose a display name and username for your bot. The username has to end in “bot” and must be unique. In our example, we’ve settled on the display name WeatherBot and username DifferentWeatherBot.

Once you’ve landed on a valid username, the BotFather will automatically register your bot and reply with a token for the Telegram API, unique to that bot. Make sure not to share your token with anyone.

Step Two: Create a Webhook for Your Bot

The next step in creating a Telegram bot is setting up the webhook that will communicate with your bot. Webhooks are how APIs tell you that something has happened, which stops you from having to query the API every few minutes (or seconds) to find out whether, for example, a new message has been sent.

Telegram uses just one type of webhook, which sends you an update object whenever anything happens.

Setting up the webhook is incredibly easy. There are just two things you need to know: your API token (you should have this from step one) and the URL where you’ll be hosting your bot. The URL will be something like https://yourdomain.com/yourbot.php. Make sure that you include the https at the start of the URL; otherwise, Telegram won’t send the webhook.

Now, in a regular web browser, navigate to https://api.telegram.org/bot<yourtoken>/setwebhook?url=https://yourdomain.com/yourbot.php. Voila, your webhook is now up and running!

Step Three: Write the Logic for Your Bot

Time for the fun part! At this point, you have everything you need to write the logic for your Telegram bot. Here’s how I’ll go on…

I do too little programming to even have an IDE on my computer, so I’ll open Notepad and start writing my code in there. Since this is PHP, make sure to sandwich your logic with <?php ?>.

The first thing to do is initialize a variable that will make it easy for us to call the Telegram API. That’s as simple as $path = "https://api.telegram.org/bot<yourtoken>.

Since we’ll be receiving updates by means of the webhook, let’s create and populate an array with that update data: $update = json_decode(file_get_contents("php://input"), TRUE)

Now, for the sake of convenience later on, let’s extract two crucial pieces of data from that update — the chat ID and message (if the update is not caused by a new message, this field might be empty, and we’ll code for that later):

In case you haven’t yet guessed what this bot is supposed to do, I want it to tell me the current weather for my location of choice. For that, I’ll create a /weather [location] command.

To do that, let’s create an if statement to see if the message starts with /weather. We can accomplish that with the strpos() function, which tells us the position of a substring within a string:

Nested within that if statement, let’s write some code to extract the location by chopping off the first nine characters of the message (which is how many characters are used up by the /weather command, as well as the space that will follow it):

If this bot were to be used in production, we’d have to add some input cleansing to make sure the location takes the right format. But it’s not, so we won’t worry about that.

Now we’ll get the weather data for that location from OpenWeatherMap:

Here we ought to implement some kind of error handling, but I’m not going to bother. Instead, let’s hope for the best and shoot our bot’s response off using the Telegram API:

All in all, here’s what the code looks like:

Step Four: Upload Your Bot to a Secure Web Server

With the logic done and dusted, save your code as a PHP file. Then, upload the file to the URL you used earlier to set up the webhook.

I have my own web hosting I use for a personal website, so I’ll upload the file to the website’s root directory using cPanel.

Step Five: Test, Tweak, and Boast About Your New Bot

Now it’s time to test out your new Telegram bot! After fixing some bugs in my code (a few dropped speech marks and incorrect parsing of OpenWeatherMap’s weather data), my weather bot was up and running. I started a private conversation with my bot (the BotFather will give you its handle) and tested out my weather command:

Final Thoughts

It’s crude, but it works! You most certainly can program a Telegram bot in less than half an hour. However, if you’re planning to use your bot in production, you should definitely spend some time thinking about the edge cases: unexpected user inputs, external API failure, and so on and so forth.

Thomas Bush

About Thomas Bush

Thomas Bush is an enthusiastic freelance writer from the United Kingdom, who loves breaking down tough topics into bite-sized articles. Covering everything from cryptocurrencies to medicine, and now APIs, you can find out more about Thomas on LinkedIn or on his website at http://thomasbush.co.