APIs and Webhooks

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

Intro

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!

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.

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=IRBOT&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.

Self Signing & Submitting a Cert

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 two), we’ll look at a very simple script, and how it interacts with the chat.