DEV Community

Digvijay Singh Rathore
Digvijay Singh Rathore

Posted on • Updated on

How to make a Telegram bot using Node JS?

As I recently released a telegram bot, I got frequently asked about a tutorial. I think, it's probably easy to code something when you get the right documentation but I faced hard time learning how to build telegram bots using node js. So here's a quickstart tutorial. I am going to use Telegraf API for it, I found it the easiest. Though you can try others as shown on telegram.org.

  1. Register a bot.
  2. Telegraf API
  3. Deployment.

Firstly, open telegram and search for BotFather (yes, it's a bot). BotFather will be used to manage, register and edit all your bots. Type /newbot to start the procedure of registering your first bot. Give required information, choose the username wisely, though you can edit the rest later. At the end of it, BotFather will provide you with the token to send https requests, save that somewhere.

Now bootstrap a new Node JS project and based on your requirements/proficiency add the libraries. Install the Telegraf NPM package by "npm i telegraf". It's time we write some code!

Copy/paste the code below.

const telegraf = require('telegraf');
const bot = new telegraf('----YOUR--TELEGRAM--TOKEN----');

Now you have initialized your script to talk to the bot associated with the token. Quickly, enter the below given code to your code editor and read the comments to understand it.

bot.start((ctx) => ctx.reply("Hello your are talking to king of all bots!"));
//the above line runs when a user interact with the bot for the first time or //type /start. Everything that goes into ctx.reply("message goes here") will be //sent as a message to the user by the bot.
bot.hears('hello', (ctx) => {
ctx.reply("Heyya! I am the kind.")
});
//bot.hears waits for the user to pass in a keyword that triggers a message or //action by the bot. It accepts the first parameter to be a keyword and then an //arrow function which has ctx.reply

Amazing, now we have a bot that sends some message when starts and reply on the work "hello". You can test it by doing "npm start" and trying the keywords in telegram. Works fine? Good.

Till now, we were hosting the bot locally but we want anyone to access it anytime. So now we need to deploy it to some cloud servers. Heroku is a free service that lets you host your Node JS projects.

Just create a github repo, connect to heroku and deploy. Simple and obvious steps. Once the code is deployed, anyone can talk to the bot because the script refers to the bot on the access token.

Congratulations! You just made your first telegram bot using node js and deployed it. Ask me on Instagram if you are stuck somewhere or just leave a tweet.
Instagram - https://instagram.com/digvijaysrathore
Twitter - https://twitter.com/novadigvijay
Know about my telegram bot - https://newstelegraph.netlify.app
Use my bot - https://t.me/NewsTelegraphBot

Top comments (0)