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>
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'));
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)