DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Arya Anish
Arya Anish

Posted on

Build a telegram bot using node.js

This article covers the basics of creating a telegram bot using node.js. I assume you know the basics of node.js and npm. Before we begin, create two files app.js and .env. After that, install telegraf.js and dotenv using npm

Why?

Well, there's a number of things you can build. For example, you can create a pizza ordering app, an e-commerce app (with the new payment feature) etc... the possiblities are endless.

How do I get started?

As mentioned above, install telegraf.js and dotenv. Then, create two files app.js and .env.

Setting the token

Message /newbot to bot father and once you fill all the details about the bot, click on Api Token and copy the token. Now set the token in the .env file. Here is an example:

BOT_TOKEN=<your bot token>
Enter fullscreen mode Exit fullscreen mode

Adding the code

To create a simple bot open your app.js file and paste all this code

require('dotenv').config();
const { Telegraf } = require('telegraf');

const bot = new Telegraf(process.env.BOT_TOKEN);
bot.start((ctx) => ctx.reply('Welcome'));
bot.help((ctx) => ctx.reply('Send me a sticker'));
bot.on('sticker', (ctx) => ctx.reply('πŸ‘'));
bot.hears('hi', (ctx) => ctx.reply('Hey there'));
bot.launch();

// Enable graceful stop
process.once('SIGINT', () => bot.stop('SIGINT'));
process.once('SIGTERM', () => bot.stop('SIGTERM'));
Enter fullscreen mode Exit fullscreen mode

Running the bot

Once you have done the setup and all the other stuff, you can run your code using this command: node.js. And voila your bot is successfully running. To test it, dm a sticker to your bot and you will see it reply to you :)

Conclusion

In this article, I showed you the basics of creating and running a telegram bot with node.js. To learn more visit their website. Also here's a nice article showing how to create an e-commerce bot.

Top comments (0)

Hey 😍

Want to help the DEV Community feel more like a community?

Head over to the Welcome Thread and greet some new community members!

It only takes a minute of your time, and goes a long way!