Open In App

How to create Telegram Chatbot with Node.js ?

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

In this article, we will discuss how to create a telegram chat box with Node.js, with the help of telegram, we can create as many as bots as we want, and we can configure them according to our needs. Nowadays, bots in telegrams are mainly used to protect users from spam or maintain privacy in the telegram group.

Let’s understand how to register for a telegram bot. For every telegram bot, we need to bot-token that is responsible for communicating and authenticating the admin of the telegram bot. Let’s understand the steps to generate a new bot token for the telegram bot.

Steps to Generate bot token in telegram:

Step 1: Go to the telegram, and search bot father. This is the bot present in the telegram that is responsible to generate a unique token for every new bot.

 

Step 2: Type /start after opening the Bot Father, and click on /newbot

 

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

 

Remember: Never share this token with anyone for security purposes.

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

Let’s understand how to use this token for creating a new bot:

Project structure:

 

Filename: bot.js

Javascript




const token = 'Enter the token';
let TelegramBot = require('node-telegram-bot-api');
let bot = new TelegramBot(token, { polling: true });
 
// Matches "/echo [whatever]"
bot.onText(/\/echo(.+)/, (msg, match) => {
 
    // The 'msg' is the received Message from Telegram
    // and 'match' is the result of executing the regexp 
    // above on the text content of the message
 
    let chatId = msg.chat.id;
 
    // The captured "whatever"
    let resp = match[1];
 
    // send back the matched "whatever" to the chat
    bot.sendMessage(chatId, resp);
});


Steps to run the application: Write the below code in the terminal to run the application:

node bot.js

Output: 

 


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads