PART 2 Telegram Bot Tutorial – Bot Script and User Interaction

To try out BobBot for yourself, head over to telegram.me/BobRossBot

In the last post, I covered creating the bot in Telegram and setting up the webhook. In this post we’ll look at getting a script at the other end of that webhook and having your bot interact with the user.

BobBot.php

Our Bot is going to wait for a user to say /bob, and then reply with a nugget of wisdom from Bob Ross. BobBot will be written in PHP, but your bot can be written in any language really! I might cover nodejs in a future post. However, I’ll assume you don’t need a walkthrough of PHP! Check out learnXinYMinute’s PHP docs for a quick run through.

You can find BobBot on GitHub here, fully commented. I’ll go through each line here anyway. In the meantime, you can put that file up on your server, at the same domain as your webhook is set to point to. If you’ve changed your mind on the domain, simple create a new webhook. You can delete the old one by visiting

https://api.telegram.org/bot000000000:AAAAa0aAA_aaA-Aaaa0A0Aa_a0aa0A0AAAA/setwebhook

then make the new one as per part 1’s explanation. Now, let’s look at the code line per line!

BobBot’s Code

$botToken = "000000000:AAAAa0aAA_aaA-Aaaa0A0Aa_a0aa0A0AAAA";
$website = "https://api.telegram.org/bot".$botToken;

We set up our bot’s token here so that BobBot knows to send replies to our API link. Be sure to put your token in here!


$content = file_get_contents("php://input");

You can read all about file_get_contents here. Long story short, when you send a message to Bobbot in the telegram client, it pings your API link. Your webhook sends than info onto BobBob.php. That information comes in as php://input, which get’s put into the $content variable

$update = json_decode($content, TRUE);
$message = $update["message"];

We take $content, and turn it into an array called update. Then I’m grabbing the message element of that array. This is the JSON version of the layout currently inside $message

{
  "message_id":2,
  "from":{"id":126101111,"first_name":"Paul"},
  "chat":{"id":126101111,"first_name":"Paul","type":"private"},
  "date":1446297296,
  "text":"A Message"
}

Now, we can easily grab all the elements we need to send a reply.

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

Now we have the text we were sent, and the chatId the message came from. This makes checking if we should reply and replying easy!


 

$bobWisdom is just an array of Bob Ross quotes. I wont reproduce them here. But remember! There’s no such thing as accidents, only happy little mistakes!

$todaysWisdom = array_rand($bobWisdom, 1);

$todaysWisdom grabs a random array element integer from $bobWisdom. You can read more about it here. Remember, $todaysWisdom is an integer, not a string!


 

if($text === "/bob") {
  file_get_contents($website."/sendmessage?chat_id=".$chatId."&text=".$bobWisdom[$todaysWisdom]);
}

This is where most of the magic is happening. We check if the user said /bob. If they didn’t nothing will happen. If they do, we do another file_get_contents and this time we specify our bot API link and we call the sendmessage method using the $chatId for the chat_id parameter and our random wisdom element as our text parameter. This is the equivalent of going to the URL:

https://api.telegram.org/bot000000000:AAAAa0aAA_aaA-Aaaa0A0Aa_a0aa0A0AAAA/sendmessage?text=Happy%20Little%20Clouds&chat_id=1111111111

Conclusion
Our BobBot is now being aimed at by our Webhook and is responding back to the Bot API. We have a working telegram bot!

PART 1 Telegram Bot Tutorial – APIs and Webhooks

To try out BobBot for yourself, head over to telegram.me/BobRossBot

Recently my friends and I migrated from Hangouts to Telegram for a multitude of reasons, but the most exciting one for me was the bot API. I’ve always wanted to put a bot into out chat for any number of reasons, and telegram finally offered me that opportunity.

However, when I went to look over the API docs and the bot examples, I came away stumped. Admittedly, the API was usually only difficult to follow as this was my first time working with one, but the bot example was hilariously verbose. Hellobot is described as “A very basic example”, but there’s not a single comment in the code to help you figure out what’s going on. Beyond that, there’s just way too much going on if you’re trying to get started.

On top of that, it may not be immediately clear to newbies how to begin making that bot in chat communicate with your site. So, allow me to walk you through what I’ve learned so far. I’ll link to the docs whenever available so that you can link my extremely simplified version with the much more detailed docs.

The BotFather
Firstly, you’ll need to talk to the BotFather, which is Telegram’s own bot creating bot. This will put together all of the telegram side things for you, like naming your bot, giving it an image, and setting up the commands your bot knows so your user wont be lost. (It’s important to note that even though you can /setcommands here, this doesn’t actually affect what your bot can do. It just makes the bot’s commands show up in chat.)

Anyway, open up BotFather in your telegram client, and type

/newbot

Botfather will ask you for a name. This doesn’t need to be unique and can be changed at any time. Next you will be asked for a username. This does need to be unique and will also form the url of your bot. This can’t be changed! After you’ve done these two things, you’ll be given the unique URL to your bot and a unique token for accessing the API with. You can open a chat by clicking on that URL and clicking start. Your token will look like this:

000000000:AAAAa0aAA_aaA-Aaaa0A0Aa_a0aa0A0AAAA

I’ll use this fake token throughout this post, but you should always swap in your own token!

The API Link
Now, head on over to

https://api.telegram.org/bot000000000:AAAAa0aAA_aaA-Aaaa0A0Aa_a0aa0A0AAAA/

This is the API link to your bot. This is going to be the back and forth between your Telegram chat bot and your server code. Messages will be sent from your bot to this link. From here we’ll send them on to your server. Your server will get the message, decide what to do and then fire the response back to the API link, which will be sent on to your telegram chat.

[IMAGEHERE]

This will be obvious for anyone who’s worked with APIs before, but can be confusing for newbies, who are often expected to just pluck this information out of the air. Anyway, when you visited the above link (after swapping in your unique token!) you were probably told “Error: Method not found”. That’s fine. We’re going to be putting the methods after the “/” at the end of that URL. Let’s start with a basic “getme“. So, go to

https://api.telegram.org/bot000000000:AAAAa0aAA_aaA-Aaaa0A0Aa_a0aa0A0AAAA/getme

and you’ll be returned a JSON that looks like this:

{"ok":true,"result":{"id":yourBOTID,"first_name":"yourBOTNAME","username":"yourBOTUSERNAME"}}

Get Updates
If this works, then we’re good to go! If not, go back and make sure the BotFather set your bot up properly, and that you started the chat. Next let’s check out the getupdates method. getUpdates is one of the two ways we can grab messages from your bot’s chats. It wont be what we use in our final version, but it is helpful to see how your bot parses the messages it’s sent. If you go to

https://api.telegram.org/bot000000000:AAAAa0aAA_aaA-Aaaa0A0Aa_a0aa0A0AAAA/getupdates

, you’ll see an empty JSON like this:

{"ok":true,"result":[]}

Now, let’s send our bot a message in the telegram client. Once you’ve done that, run the getupdates method in your browser again. You should see:

{"ok":true,"result":[{"update_id":111111111,
"message":{"message_id":2,"from":{"id":212390921,"first_name":"Paul"},"chat":{"id":212390921,"first_name":"Paul","type":"private"},"date":1446297296,"text":"A Message"}}]}

From this you can see that our messages are being recorded in a JSON object. We’ll work with that later.

Sending Messages
Now, let’s send ourselves a message using the sendmessage method. We’ll need the id from the getupdates method earlier. Don’t forget to swap in your chat_id with the bot and your bot token! Then, simply visit

https://api.telegram.org/bot000000000:AAAAa0aAA_aaA-Aaaa0A0Aa_a0aa0A0AAAA/sendmessage?text=I R BOT&chat_id=212390921

And your bot will hopefully send you a message! This is the only interacting method I’ll going through today, but your bot can send all kinds of things like images and files. Be sure to look through the bot API for more methods!

Setting up the Webhook
Okay, so we can send and receive our messages via the API link. We’re half way there! Next we need to get those messages forwarding to our own server. We’re not going to use getUpdates, because it’s outdated and inefficient. Thankfully, there’s a better method, and that’s setWebhook. The only issue with setWebhook is that Telegram requires that your website uses SSL, in otherwords, that your site has a certificate and can correctly be visted via https://yourdomain.com. Thankfully, as of August 2015, Telegram allows you to sign your own certificate, which cuts out the costly factor of buying one. On the down side, you will need to submit that certificate to them when you set up the webhook. Let’s take it one step at a time.

Step 1: Create your cert & set up your site to use it.
This sounds hard, but Digital Ocean have an excellent and easy to follow tutorial here if your site is hosted using nginx. One amendment for the purposes of Telegram bots is that the tutorial states that you can use your site domain or the ip address of your server. However, the IP address will not work with our bot webhook. You have to use the domain where your script will be hosted.

Step 2: Set up the webhook on the Linux command line
If your site is already signed, then you can use the URL method we’ve used for getupdates and sendmessage to set up your webhook. However, if, like me, you’ve self signed your cert, you’ll need to upload your cert as a file, and telegram wont accept this with the URL method as a string! Thankfully, this process is simple thanks to the Linux command line. In a terminal, type:

curl -F "url=https://your_domain.com/where-the-script-will-be/bot-script.php" -F "certificate=@/location/of/cert/nginx.crt" https://api.telegram.org/bot000000000:AAAAa0aAA_aaA-Aaaa0A0Aa_a0aa0A0AAAA/setWebhook

The domain should go straight to where you intend to put your bot script, which we’ll talk about later. The certificate should point to nginx.crt (which is what it was named in the Digital Ocean tutorial). The final URL is simply calling the setWebhook method on your bot token. That should be your webhook set up. You wont be able to call the getUpdates method anymore, as the webhook will block it.

Conclusion
We’ve set up the bot, looked at how to call some of it’s methods, and most importantly the webhook is up and running! In part 2, we’ll look at a very simple script, and how it interacts with the chat.