How to Build a Telegram Bot Step by Step using PHP – Complete Guide

-

Affiliate Disclosure: Every purchase made through our affiliate links earns us a pro-rated commission without any additional cost to you. Here are more details about our affiliate disclosure.

Telegram Bot using PHP:- Telegram messages are heavily encrypted and can self-destruct. Synced. Telegram lets you access your chats from multiple devices.

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 guide, I’ll tell you, how you can write/ create your own Telegram bot easily using PHP.

Step 1: Setup or Create your Bot’s Telegram Profile

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.

To setup a New Bot Profile, enter the /newbot command.

The BotFather will ask you to choose a display name and username for your bot. Make sure that, the username has to end in “bot” and must be unique. For example, the display name is Study Warehouse Bot and and username StudyWarehouseBot

Once BotFather accepts your username, 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 2: Create a Webhook for Your Bot

The next step is setting up the webhook that will communicate with your bot.

A webhook in web development is a method of augmenting or altering the behavior of a web page or web application with custom callbacks. These callbacks may be maintained, modified, and managed by third-party users and developers who may not necessarily be affiliated with the originating website or application.

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:

  1. your API token (you should have this from step one)
  2. 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.

Congratulations!!! your webhook is now up and running!

Step 3: Write the Logic for Your Bot

At this point, you have everything you need to write the logic for your Telegram bot.

To write your code or logic, you can use any IDE or editor you want. 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>

Let’s create a Bot that tells the weather update

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"];

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("http://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("http://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 4: 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 5: Test and Share your New Bot

Now it’s time to test out your new Telegram bot!

If all done fine, Share your Bot with others. All the Best

Related Articles

Like our Article/ Blog? Can buy a Buttermilk for our team.. Click here

Pardeep Patelhttps://pardeeppatel.com/
Hi!, I am Pardeep Patel, an Indian passport holder, Traveler, Blogger, Story Writer. I completed my M-Tech (Computer Science) in 2016. I love to travel, eat different foods from various cuisines, experience different cultures, make new friends and meet other.

Share this article

-- Advertisement --

LEAVE A REPLY

Please enter your comment!
Please enter your name here

-- Advertisement --