Create a Telegram bot using Webtask

Telegram bots are awesome, so easy to create and an incredible approach where you don't need to use any website or application to setup them. You do by simply talk with the father of the bots, the @BotFather.

The bot API is really well documented. You have two ways to "listen" to what people types: one by subscribing to a long polling request and another by receiving webhooks.

We're going to use the second one, the webhooks.

Let's do the magic:

Create the bot

Send a message to @BotFather, that says:

/newbot

It will ask you a few questions about your bot (bot name, description, etc).

You would like to configure your bot details, please chat with the @BotFather, I wouldn't enter in details here on how to set custom commands, start description, etc.

Ok, now to the web server part...

Setup the web server part

If you didn't hear about Webtask before, it's a simple tool to run code with an HTTP request. Sounds pretty basic (it is, and it's not!), but they allows you to store node.js code in their servers and execute it based on HTTP calls. Awesome.

First you need an account on Webtask, click on the Try it now! button, choose the social service you want to use to register, and you're ready.

Next you need to install the command line utility, follow the instructions here:

Create the script to run as the bot backend

This is the basic script for the bot backend:

Replace the token variable as your pleasure, and of course, use the commands you want!

Then, you need to publish your code to Webtask, if you used a file called hello_bot.js, just type:

wt create hello_bot.js

It will upload the script and will return an URL like:

https://webtask.it.auth0.com/api/run/wt-your-email-0/hello_bot?webtask_no_cache=1

This will be our webhook URL. Let's the bot know it by running this command on your terminal:

curl -X POST -H "Content-Type: multipart/form-data" -F "url={your:url}" 'https://api.telegram.org/bot{your:token}/setWebhook'

Replace {your:url} and {your:token} by your webhook url and your bot token respectively.

Example:

curl -X POST -H "Content-Type: multipart/form-data" -F "url=https://webtask.it.auth0.com/api/run/wt-your-email-0/hello_bot?webtask_no_cache=1" 'https://api.telegram.org/bot1234:1234567890/setWebhook'

You should receive something like:

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

Done!

Now you can execute commands, if you type '/hello' in a chat with the bot, you should receive the response from the server, in our example world!.

Note: keep in mind that for bot webhooks you need to have a web server with SSL encryption (gladly the kind guys of Auth0, provides SSL encryption in Webtask by default!).

Posted on 29 Jul 2015
Written by Leandro Ardissone