Open In App

Node.js Bot.on() Method

Last Updated : 06 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

The Bot.on() method is used in the Node.js Modern Tele graf Bot Framework. This Framework provides various functions to interact with the official Telegram Bot API. This method is executed when a particular event occurs during the conversation with the bot for eg: Events like Sending text, Sending Photo, etc these operations handle by the Context function. 
Syntax: 

TelegrafBot.on(event, Context function)

Parameters: This Method accepts two parameters as mentioned above and described below: 

  • .Event: Occurrence of particular activity during the conversation with a bot.  
  • Context function:  This function encapsulate telegram update information.

Return Type: The return type of the function is void.

Installing Module: Install the module using the following command:

npm install telegraf

Steps to get the keys: 
 First, get the GET BOT_TOKEN from BOTFATHER in telegram. Just search for BOTFATHER in Telegram and select the verified one as shown  below: 

Type /start and then click on /newsbot as shown below: 
 

Now type the name of the bot and that must be unique. 

Now just copy the token From the BotFather. And for deleting the token simply search /delete the token in BotFather. 

Project structure: 


Filename: bot.js 

javascript




const token = 'Enter the token';
const telegraf = require("telegraf");
const token = 'Token';
const bot = new telegraf(token); //Creating object of Telegraf
 
bot.on("text", ctx => {
    //"Event of the text"
 
    ctx.reply("This is the text") //context function reply the message
 
})
bot.on("photo", ctx => {
    ctx.reply("This is the photo"); //context function reply the message
    })
});


 Run the bot.js file using the following command: 

node bot.js

Output:


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads