javascript - 减少电报机器人脚本以使其可扩展 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"]);
});
解决方案
我认为Telegraf是node.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=>{})
如果机器人听到一些字符串,即使是在文本消息的中间,机器人也会正常工作。
推荐阅读
- linux - 我如何发送电子邮件报告 URL 已更改为 urlwatch?
- mongodb - 在子模式文档中填充字段
- javascript - gulp chalk,通过方法传递字符串模板
- c++ - 在成员函数中创建对象
- python - 尝试使用 python3 导入 pyautogui 时出错
- android - 如何从带有 FLAG_ACTIVITY_SINGLE_TOP 的通知导航到活动
- asp.net - 我需要能够通过 API 将 Chargify 订阅与我的 vb.net 网络表单站点集成
- javascript - 我可以在 Math.round 计算中使用从 DOM 收集的变量吗?
- android - 架构组件的视图模型类存在于哪个线程(UI/Background)?
- javascript - 两个 https 之间的 document.referrer 为空