How-to-Build-Your-First-Telegram-Bot-Using-PHP-in-Under-30-Minutes

How to Build a Telegram Bot Using PHP in Under 30 Minutes

Last updated: August 10, 2023

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

$chatId = $update["message"]["chat"]["id"];
$message = $update["message"]["text"];

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:

if (strpos($message, "/weather") === 0) {
}

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 (strpos($message, "/weather") === 0) {
$location = substr($message, 9);
}

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:

$weather = json_decode(file_get_contents("https://api.openweathermap.org/data/2.5/weather?q=".$location."&appid=mytoken"), TRUE)["weather"]["main"];

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:

file_get_contents($path."/sendmessage?chat_id=".$chatId."&text=Here's the weather in ".$location.": ". $.weather);

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

<?php
$path = "https://api.telegram.org/bot<yourtoken>;

$update = json_decode(file_get_contents("php://input"), TRUE);

$chatId = $update["message"]["chat"]["id"];
$message = $update["message"]["text"];

if (strpos($message, "/weather") === 0) {
$location = substr($message, 9);
$weather = json_decode(file_get_contents("https://api.openweathermap.org/data/2.5/weather?q=".$location."&appid=mytoken"), TRUE)["weather"][0]["main"];
file_get_contents($path."/sendmessage?chat_id=".$chatId."&text=Here's the weather in ".$location.": ". $weather);
}
?>

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:

Other Use Cases For Telegram Bots

Telegram has become one of the top chat applications used by a global network of people. With so much interest in the platform, there is a lot of excitement around using bots to take the chat experience to the next level.

Outside of weather updates, you could technically create anything you can program — that’s the beauty of APIs. For example, you could create a bot that hooks into any number of fun APIs to do things like retrieve characters from the Star Wars universe, fetch various XKCD comics, or return random Kanye West quotes. Or, your bot could do more than simple GET operations, such as generating unique copy or summarizing chat notes using an LLM API, like OpenAI GPT-3, Bard, or Goose AI.

Some of these use cases will be easy to integrate, and others will be a bit more advanced compared to our simple weather data bot.

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.