简体   繁体   中英

Reducing telegram bot script to make it scalable NodeJS

I'm working on a telegram bot with node.js , how can I reduce this code to be more scalable?

const a = 'Lorem ipsum';
const b = 'Dolor sit';
const c = 'bla bla bla';

bot.onText(/\/a/, (msg, match) => {
 const chatId = msg.chat.id;
 bot.sendMessage(chatId, a);
});
bot.onText(/\/b/, (msg, match) => {
 const chatId = msg.chat.id;
 bot.sendMessage(chatId, b);
});
bot.onText(/\/c/, (msg, match) => {
 const chatId = msg.chat.id;
 bot.sendMessage(chatId, c);
});

to something like this:

const a = 'Lorem ipsum';
const b = 'Dolor sit';
const c = 'bla bla bla';

bot.onText(/\/[if they type "a" or "b" or "c"]/, (msg, match) => {
 const chatId = msg.chat.id;
 bot.sendMessage(chatId, [answer "a" or "b" or "c"]);
});

I think Telegraf is the best library for coding bots in node.js . This is a simple example written for Telegraf:

let array = ["A","B","C"]
bot.on('text',ctx => {
   array.forEach((str) => {
     if (ctx.message.text == str) {
       ctx.reply(str)
     } else {
       //  ...
     }
   })
})

This example is limited to exact text string. By using bot.hears(["A","B","C"],ctx=>{}) if the bot hears some string, even in the middle of a text message, the bot would work properly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM