Telegram Bot: Chatbot with PHP

So here’s something that I just learned. It worked for me but funny thing is I don’t really understand how it works. Hahah… I can code a little in PHP and my website is as far as my PHP and web development skills go. Nothing fancy but it works, you know? May I also highlight that due to this common flukes in PHP writing, many programmers look down at PHP. I’m just a hobbyist, so.

But, I will show you how to make a simple Chatbot using PHP. Why PHP? Because it’s easy, requires common tools and can be deployed quickly. Before we start, you need these:

Pre-requisites

  1. Some PHP knowledge or general coding knowledge.
  2. An offline webserver to develop, or skip this and use Step 3.
  3. An online webserver to upload everything (and/or develop in it).
  4. A Desktop Telegram for rapid testing.

Beginning

  1. Use this external guide first (Thank you Thomas for writing this), this is what I used. I will add my version of the bot for Step 3 (Writing the codes for the bot). Thomas’ version is a bot that fetches current weather condition based on the input location. It’s nice but the instructions were foggy to me. Let me be another foggy instructor to you, ha ha ha.
  2. Why bother writing on top of another guide you may ask. Because the guide I used was hard to understand (for me). I’m a newbie still although I have been dabbling with various codes for many years (in my head now I want to learn Ruby, hmmm). I aim to make it easy to follow for those who are just as clueless.
  3. If your webservers, bot and token are set, let’s begin!

My Bot

My bot is called Mr. Robobot. It serves as a fun bot. I try to make something like the old school mIRC bots back in the day. It can say hi in various ways, it can give you random 4 digit lottery numbers (because my friends are lottery players) and it sends photo memes. A lot other stuff too that is similar to what I mentioned above, but our goal today is to see how easy it is. I promise.

The “Head”

  1. Create a project folder for this bot. You will access this directory with your webserver.
  2. Create an index.php file of your root project folder. You can name it whatever you want anyway.
  3. In the index.php file, put the following codes:
$path = "https://api.telegram.org/botYOUR_TOKEN_HERE";
$update = json_decode(file_get_contents("php://input"), TRUE);
$chatId = $update["message"]["chat"]["id"];
$message = $update["message"]["text"];

$userId = $update["message"]["from"]["first_name"];
  1. If you came from the site I gave you earlier, you’ll notice the first four lines are similar. I added the last line.
  2. Line 1: Create a path to your Telegram Webhook.
  3. Line 2: Each message has a unique id. It will capture that.
  4. Line 3: This command helps you to hook a message from Telegram and put it into an array, which you will dissect later on in various forms.
  5. Line 4: This is basically the input text which will be read by the bot.
  6. Line 5: Captures the name of person sending a request.

Command & Programme

This is the best part, making those commands! Our first command is a simple random number generator (lottery numbers). The goal is to generate random 4 digits to the person requesting it. Ok? Let’s go.

$rand4D = rand(0,9).",".rand(0,9).",".rand(0,9).",".rand(0,9);

if($message == "/lottery" || $message == "/luckypick"){

file_get_contents($path."/sendMessage?parse_mode=HTML&chat_id=".$chatId."&text=".$userId."'s <i>lucky fodi</i> is ... <b>".$rand4D."</b>. Good luck! ".$tip);

}

See how short that is? Ok this is what it means:

  1. Line 1: Create a variable that holds the random functions (see rand() in the PHP manual). There are more elegant ways to write this using if-else or some loops but let’s keep it simple because we want to know how everything connects.
  2. Line 2: An if(){} statement. Find the beginning curly brace { and where it ends }. Whatever is in between, those are the responding commands.
  3. So in the if(){} statement, we want to check if someone inputs /lottery or /luckypick. When somebody types in /lottery and hit send to the chat, Line 3 will respond.
  4. Line 3: file_get_contents() will retrieve and parse the $_GET/$_POST data. The query begin after the / with sendMessage? and all the relevant attributes like parse_mode=, chat_id= and text=. See below if it’s difficult to see:
  5. i. sendMessage?
    ii. parse_mode=HTML
    iii. & (use & to connect multiple attributes)
    iv. chat_id=”.$chatId.”
    v. &
    vi. text=
  6. They became this: sendMessage?parse_mode=HTML&chat_id=”.$chatId.”&text=
  7. parse_mode will allow you to format your messages with simple HTML tags like bold, italic or underline.
  8. chat_id corresponds to the initiated command (by whom) and later replies to it.
  9. text is pretty straightforward; the responding text will be put in it. So all your command results (in this case, a text response with 4 random digits) will be put in text = ” “.
  10. In text= we put in $userId so that it will mention the person who sent the command (/lottery). The output will be something like the picture below:
My command is different but you get the idea.

Pretty neat, huh? That [ /help ] at the end of the response is just an additional text I included so that other users can tap on /help to get all the available commands (you can name yours whatever you want). If I send the same command again, a newly generated random 4 digits will be sent by the bot until you’re tired of tapping.

Wrapping It Up

Save everything and add your bot to your friend’s group, or interact with the bot directly.

So, instead of using the usual some_function(){ …codes… } in a conventional coding situation, we use the if(){} statement instead. You can say that the robot is on standby all the time.

I have 10 different commands with some commands with similar behaviours. One of my command sends random laughs when /haha is invoked. It’s pretty entertaining, my friends love it. The other sends random photo memes relevant to a single person (some in joke stuff) whenever a person sends the command. I’m still learning myself and I hope to discover more soon. In the mean time, I probably should get my hands on learning Ruby next because there are not many resources explaining how to work with bots using PHP. Sucks for me, I love PHP.

Here’s a homework for you: Tweak the given codes so that it’ll send a photo instead. Hint: 1) change the variable that holds the rand() function to an image path. 2) use sendPhoto? instead of sendMessage? 3) change text= to photo=

Did that help? Please comment to let me know. Either way, this is just another future reference for me 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *

LINKS :)

© botdroid.me since 1998. Engine by Wordpress. Custom theme. Privacy Policy. Browse comfortably please. Borrowed media credits.