首页 > 解决方案 > 减少电报机器人脚本以使其可扩展 NodeJS

问题描述

我正在开发一个电报机器人node.js,我怎样才能减少这个代码以提高可扩展性?

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);
});

像这样:

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"]);
});

标签: javascriptnode.jsbotstelegram

解决方案


我认为Telegrafnode.js. 这是为 Telegraf 编写的一个简单示例:

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

此示例仅限于精确的文本字符串。通过使用bot.hears(["A","B","C"],ctx=>{})如果机器人听到一些字符串,即使是在文本消息的中间,机器人也会正常工作。


推荐阅读