Bots have always been the limelight in Telegram, which sets it apart, and years ahead of its competitors.
Given the fact that bots, that too developed by third-party developers, have existed on it for such a long time, its bot ecosystem is far more developed than other IM apps such as Messenger.
While it’s good to have multiple bots to interact with and make your life easier in Telegram, it’s extremely tempting to create one of your own. Often times, the problem with that is that most tutorials require you to know coding, and the other ones just look too complicated to even try. The challenge isn’t to merely create a bot, but to make a responsive one. These tutorials end up complicating the “responsive” part, by giving scattered instructions about API and similar things.
To help you with your goal of creating a responsive Telegram bot, we have prepared a tutorial which will teach you to set up your own bot using “botfather”. All you need to do, is follow the simple steps below.
- Open Telegram on your phone.
2. Tap on the pen symbol in the bottom-right corner. Tap on the magnifier icon and search “@botfather”, and tap on BotFather.
3. Tap “Start” and you’ll be presented with a list of commands that you can use with the bot.
4.Send “/newbot”. Send the name that you want to keep for your bot. Now, set a username for your bot. It must end with “bot”.
5. Congratulations, your bot has now been created. You can either use the link received in the message from BotFather, or search for your bot on Telegram. Save the API token in the message, in an easily accessible place in your device (such as a note-taking app).
6. Open Telegram, and search for your bot. Try talking to it.
7.Well, let us guess. It didn’t respond at all, did it? That is because it doesn’t know how to respond, yet. Don’t worry, we are here to teach you how to take care of that.
All you need to do for this, is to create a bot server which will run in the back and provide your bot the ability to respond.
Setting up a server for your bot
Every time your bot receives a message, it sends a message, formed as an API call, to the server. The server then processes the message and sends back the pre-determined response.
Long polling and Webhooks are the two ways that your server can receive updates in the form of.
In long polling, messages are periodically checked for and are responded to. It’s slow and not recommended.
On the other hand, Webhooks is fast, responsive, and responds to messages, whenever any are received.
In this tutorial, we are going to be using webhooks. Every webhook, is called with an “update object”. For handling your update, you need a server.
While you can use anything you prefer, to create your own server, we personally used node.js.
Step one, is to initialize your project.
## Create new directory and enter this directory
mkdir my-telegram-bot
cd my-telegram-bot
## Now, initialize the npm project
npm init
You’ll now get a package.json file. The next step is installing your dependencies. It can be done by the following command:
npm install –save express axios body-parser
“express” is the application server that we are using, “axios” is the http client and “body-parser” will support us in analyzing the response received from every request.
Now, create a new file, titled “index.js”:
var express = require(‘express’);
var app = express();
var bodyParser = require(‘body-parser’);
const axios = require(‘axios’)
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({
extended: true
})); // for parsing application/x-www-form-urlencoded
//This is the route the API will call in case of a reponse
app.post(‘/new-message’, function(req, res) {
const {message} = req.body
//Each message contains “chat” and a “text” object, which has an “id” that is the chat id
if (!message || message.text.toLowerCase().indexOf(‘juju’) <0) {
// In case a message is not present, or if our message does not have the word juju in it, do nothing and return an empty response
return res.end()
}
// If we’ve gotten this far, it means that we have received a message containing the word “juju”.
// Respond by hitting the telegram bot API and responding to the approprite chat_id with the word “Abhi”
// Remember to use your own API toked instead of the one below “https://api.telegram.org/bot<your_api_token>/sendMessage”
axios.post(‘https://api.telegram.org/bot270485614:AAHfiqksKZ8WmR2zSjiQ7_v4TMAKdiHm9T0/sendMessage’, {
chat_id: message.chat.id,
text: ‘Abhi’
})
.then(response => {
// We get here if the message was successfully posted
console.log(‘Message posted’)
res.end(‘ok’)
})
.catch(err => {
// …and here if it was not
console.log(‘Error :’, err)
res.end(‘Error :’ + err)
})
});
// Finally, start our server
app.listen(3000, function() {
console.log(‘Telegram app listening on port 3000!’);
});
By running node index.js, you can run this server on the local machine. If you get the message “Telegram app listening on port 3000!” on your console, then everything has been done right.
Deploying your service
Again, just like in the case of a server, it’s upon you to deploy your server any way you want, but we prefer to use the service now.
First, install now on the system.
npm install -g now
Now, add a start script to the package.json file.
Our file looks like this:
{
“name”: “telegram-bot”,
“version”: “1.0.0”,
“description”: “”,
“main”: “index.js”,
“scripts”: {
“test”: “echo \”Error: no test specified\” && exit 1″
},
“author”: “FrankJonas <[email protected]> “,
“license”: “ISC”
}
Time to add a start script so that you get:
{
“name”: “telegram-bot”,
“version”: “1.0.0”,
“description”: “”,
“main”: “index.js”,
“scripts”: {
“test”: “echo \”Error: no test specified\” && exit 1″,
“start” : “node index.js”
},
“author”: “Soham Kamani <[email protected]> (https://sohamkamani.com)”,
“license”: “ISC”
}
Once the script’s been added, run the following command:
now
(Note: run it in the root directory of your project folder i.e. where the package.json file is)
If you are using now for the first time, you’ll be presented with some instructions for signing in. Follow them, and you’ll get the following:
- Deploying ~/Documents/experiments/telegram-bot
- Using Node.js 6.2.1 (default)
- And an address which will be copied to your clipboard.
The link/address that you just received, is the one that your server is deployed on. Your API would be available on the link/new-message (this was pre-defined in index.js).
The final step is to add the Telegram API in the terminal. It’ll assure that the app knows that our bot has to communicate with this address whenever any message is received.
curl -F “url=https://telegram-bot-zztjfeqtga.now.sh/new-message” https://api.telegram.org/bot<your_api_token>/setWebhook
Time to chat with your bot. According to the system that we have created, every time that you’ll send “juju” to the bot, you’ll receive the reply “abhi”.
Pretty neat, huh? While the tutorial doesn’t focus on advanced optimizations of a bot, it’s a pretty good guide to kickoff your journey into the world of Telegram bots (and “bots” in general). You can find a bunch of similar or advanced tutorials on the internet once you are done setting up this neat and simple bot.
That’s all that we have for you today. Do post your queries and experiences with Telegram bots, in the comment section below.