Open In App

Node.js Bot.hears() Method

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

The Bot.hears() method is used in the Node.js telegraf Module. This module provides various functions to interact with the official Telegram Bot API. This method executes when the given captured message matches the given keywords. 

Syntax: 

TelegrafBot.hears(keyword, callback)

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

  • keyword: It can be array, String, or mixed that to be matched.  
  • Callback: This function encapsulate telegram update information and executes it when a keyword matches.

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:

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

Step 2: Type /start and then click on /newbot as shown below:

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

Step 4: 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




// Requiring module
const telegraf = require("telegraf");
 
// Your Token
const token = 'Enter your token';
 
// Creating object of Telegraf
const bot = new telegraf(token);
 
bot.hears("GFG", ctrx => {
 
    // ctx object holds the Update object
    // from Telegram API So you can use
    // everything you see there
 
    // Exexutes when 'GFG' keyword match
    ctrx.reply("GFG valid Form");
})
 
bot.hears("ByeBye", ctrx => {
 
    // Executes when 'ByeBye' keyword match
    ctrx.reply("Bye bye");
})
 
// Launch the program
bot.launch()


Run 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