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.
What is Node.js?
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.
What is Telegraf.js?
Telegraf.js is a framework for Node.js that allows you to create awesome bots in Node.js runtime.
Step 1: Download Node.js
After downloading Node.js, let's check its version.
Step 2: Creating file for our simple telegram bot
mkdir bot-app
cd bot-app
Step 3: With the help of Botfather we will create our new bot
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.
Step 4: We download Telegraf.js via NPM.
npm install telegraf
We start creating the bot by downloading Telegraf.js.
Step 5: Creating bot in Node.js and 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();
Let's check it out now:
We’ll add some options to our boat.
// 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();
Top comments (7)
Hello! thanks for the tutorial. Where can I find all the methods that I can create with Telegraf? I saw the Telegraf documentation but can't find it.
Thank you.
section.io/engineering-education/t...
Cool
This barely scratches the surface... I wasn't expecting a full-fledged article, but this is borderline useless
Ok sir
Nice tuotial, but please hide you token
I don’t want that and it’s no secret to me