How to build a Telegram Bot using PHP? — Absolute beginner guide

Deepak Mohan Singh
6 min readMay 25, 2020

You are reading this, so you very well know chatbots are playing a major role in today’s businesses in the field of customer relationships. However, when it comes to Telegram, bots are used for fun(Gif, Memes sharing, etc), knowledge sharing(News, Live updates, YouTube videos, etc), and for performing easy quick tasks(File storage in the cloud, Wikipedia search, Polls, etc).

What if I tell you, creating bots in Telegram is super easy? Yeah! If you’ve read several blogs and still not yet clear on how to start building or if this is the first blog that you’re reading on building Telegram bots, then you’re at the right place!

Requirements:

* Basic understanding in PHP programming will be helpful.

One with no knowledge in PHP can also read this blog and try building bots, if the working of code in this blog is understood 🙂

Tell Me a Joke!

Let us create a simple bot named, “Tell Me a Joke!”. This bot throws us random jokes every time we ask for it, so when you feel the conversation with your friends’ gonna end, tell them a joke instantly and keep the conversation going with fun!

Try using this bot, so you get a clear idea on what we are gonna build!

BOT LINKhttps://t.me/tell_me_a_joke_bot

How do telegram bots work?

It is a must to know how the background process works. To keep it more simple, Assume a user sends a message, let’s say “Tell me a joke” to your bot. Your bot then sends this information to the Telegram API(or Bot API). This Telegram API is responsible to send this information to where your PHP code is. Your PHP code will be hosted somewhere, so this Telegram API sends information to your PHP file using your domain name(www.xyz.com/myphpcode.php). Your PHP file has that piece of code to generate a random joke. After your code generates a random joke, this joke is sent back to Telegram API. And finally, the Telegram API sends the joke back to the user as a message.

Telegram allows sending information via Telegram API(Bot API) just to make sure if the bot is an authorized one.

It checks this with a unique token you get while you create a new bot.

Now that you understand how bots in Telegram work, we’ll get started in building a bot in just 3 steps!

Step 1

⦿ Open the Telegram app, and search for “@BotFather “. You’ll get a verified bot result. Open it.

⦿ Type “/newbot “. Give any name to your bot. I’ll name it “Tell Me a Joke!”. Next, you should choose a unique name for your bot. I’ll give “tell_me_a_joke_bot”. Your bot is now created!!! You can find your bot from anywhere using:

Step 2

Now that you have created a new bot, it’s time for creating Webhooks. As mentioned earlier, whenever users send a message to the bot, the bot sends this info to Telegram API. But, what does Telegram API do next? Well, it gives you two choices:

1) You can configure Telegram API to send this info immediately to your PHP file, or 2) It keeps the info with it, and whenever your PHP file asks the Telegram API for info, it gives info to PHP file.

For real-time communication, we need immediate responses from the bot, don’t we? So, we go for the first option and it’s called “Webhook”. This sends info to our PHP file automatically when users send messages to the bot.

To set Webhook, all you need to do is, have a hosted PHP file with SSL certified domain name(Try Glitch).

Just open any browser and type the below URL:

https://api.telegram.org/bot<yourtoken>/setWebhook?url=https://<yourdomain.com/yourfile.php>

If everything works fine, your browser shows this JSON response:

{"ok":true,"result":true,"description":"Webhook was set"}

The Webhook is now set!

Step 3

It's time to code! What do we need in our code?

  1. Get user details (User name, ID, the message that the user has sent).
  2. Generate a random joke if the message is “Joke” or “Tell me a joke”.
  3. Send the joke to the user via Telegram API.

When a user sends a message, the Telegram API sends the info to the PHP file in JSON format as shown below:

{
"update_id": 6918xxxx,
"message": {
"message_id": 28,
"from": {
"id": 1200xxxx,
"is_bot": false,
"first_name": "Deepak",
"username": "deepak",
"language_code": "en-UK"
},
"chat": {
"id": 1200xxxx,
"first_name": "Deepak",
"username": "deepak",
"type": "private"
},
"date": 1509641174,
"text": "Tell me a joke please"
}
}

From this JSON object, you need to get Chat id, First Name and Text message. You can simply do that in PHP by:

$update = json_decode(file_get_contents("php://input"), TRUE); $chatId = $update["message"]["chat"]["id"]; $userName = $update["message"]["chat"]["first_name"]; $message = $update["message"]["text"]; $token = <YOUR_BOT_TOKEN>;

If the message contains the word “joke”, we are gonna fetch a random joke from any joke providing website via API call. I’m using icanhazdadjoke.com to fetch a random joke.

if (strpos($message, "joke") !== false || strpos($message, "Joke") !== false) 
{
//Joke Endpoint URL
$url = 'https://icanhazdadjoke.com/';
//Set User agent, Response format, and get Joke as JSON response
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_USERAGENT, 'TellMeAJokeBot/1.0 (http://www.mysite.com/)');
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Accept: application/json"));
$result = curl_exec($ch);
//Store JSON string in variable
$json = json_decode($result, TRUE);
//Fetch Joke alone from JSON
$joke = $json["joke"];
//Send the joke to requested user in Telegram
$tg_api='https://api.telegram.org/bot'.$token.'/sendMessage?chat_id='.$chatId.'&text='.$joke."😂";
file_get_contents($tg_api);
}

For those who don’t know curl functions used in the above code, refer below:

Our code issues a GET request to the server of icanhazdadjoke.com and receives the document it asked for(A random joke). icanhazdadjoke.com needs user-agent to be added in HTTP header to know who’s requesting for jokes. So, the CURLOPT_USERAGENT parameter is used to show my website name to icanhazdadjoke.com. The joke should be sent by icanhazdadjoke.com in JSON format. So, we used the CURLOPT_HTTPHEADER parameter and set “application/json”.

For those who don’t know the json_decode function used in the above code, refer below:

The json_decode() function is an inbuilt function in PHP that is used to decode a JSON string response. It converts a JSON encoded string into a PHP variable. Now $json variable will be having the below JSON with it:

{
"id": "R7UfaahVfFd",
"joke": "My dog used to chase people on a bike a lot. It got so bad I had to take his bike away.",
"status": 200
}

To fetch joke alone, we used $joke = $json[“joke”].

And finally, to send the joke to the requested user, we can use the URL provided by Telegram, which is:

$tg_api='https://api.telegram.org/bot'.$token.'/sendMessage?chat_id='.$chatId.'&text='.$joke."😂";

The overall PHP code:

<?php 
$update = json_decode(file_get_contents("php://input"), TRUE); $chatId = $update["message"]["chat"]["id"];
$userName = $update["message"]["chat"]["first_name"];
$message = $update["message"]["text"];
$token = <YourBotToken>;
if(strpos($message, "joke") !== false || strpos($message, "Joke") !== false)
{
$url = 'https://icanhazdadjoke.com/';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_USERAGENT, 'TellMeAJokeBot/1.0 (http://www.mysite.com/)');
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Accept: application/json"));
$result = curl_exec($ch);
$joke = json_decode($result, TRUE)["joke"]; $tg_api='https://api.telegram.org/bot'.$token.'/sendMessage?chat_id='.$chatId.'&text='.$joke."😂";
file_get_contents($tg_api);
}
else
{
$help = "Hi ".$userName."! I have infinite jokes with me 😎 Type \"𝙏𝙚𝙡𝙡 𝙢𝙚 𝙖 𝙟𝙤𝙠𝙚\" or just type \"𝙅𝙤𝙠𝙚\", and i'll send you a random joke 😂"; $tg_api='https://api.telegram.org/bot'.$token.'/sendMessage?chat_id='.$chatId.'&text='.$help; file_get_contents($tg_api);
}
?>

And here’s the work!

The Working

Start building your Telegram bot now! Also, there are many other features like inline mode, commands, adding your bot to groups, and much more.

Hope you liked it! Give it a 👍 and share it with who are really interested in building bots!

Originally published at http://codingthing.wordpress.com on May 25, 2020.

--

--