19
Creating simple telegram bot in Node.js and Telegraf.js (step by step)
We will learn how to create a simple bot in Node.js and Telegraf.js. It's very easy. Let’s first learn what Node.js is.
Node.js is a runtime application. It allows you to use the JS programming language outside the browser. With Node.js you can work with data analysis or write a telegram bot and create HTTP servers.
Telegraf.js is a framework for Node.js that allows you to create awesome bots in Node.js runtime.
mkdir bot-app
cd bot-app
When we create a bot in Botfather, it provides us with a bot token. The bot token, on the other hand, helps us write logic to it in node.js.
npm install telegraf
We start creating the bot by downloading Telegraf.js.
Let's first create a file called bot.js
. Importing Telegraf in bot.js
file:
// bot.js
const { Telegraf } = require('telegraf'); // importing telegraf.js
Now we declare a variable named bot and add to it the token of the bot we created in botfather.
// bot.js
var bot = new Telegraf('1928550358:AAH9Y4Bscfu2-y_OptOkzi3VyhbLaV84a8Q') // We saved our bot token to the bot variable
We write down what our bot will do when it receives the start command.
// bot.js
bot.start(ctx => ctx.reply(`
Hi, I'm a simple bot
`))
bot.launch();
// bot.js
bot.start(ctx => ctx.reply(`
Hi, I'm a simple bot (please write /help)
`))
Enter what the bot will do when the word /help is typed.
// bot.js
bot.help(ctx => ctx.reply(`
Hello, world!!!
`))
All codes:
const { Telegraf } = require('telegraf'); // importing telegraf.js
var bot = new Telegraf('1928550358:AAH9Y4Bscfu2-y_OptOkzi3VyhbLaV84a8Q') // We saved our bot token to the bot variable
bot.start(ctx => ctx.reply(`
Hi, I'm a simple bot (please write /help)
`))
bot.help(ctx => ctx.reply(`
Hello world!
`))
bot.launch();
19