javascript - JavaScript Else if Chatbot 功能问题
问题描述
所以,我正在编写一个 Discord 机器人(使用 discord.js)。这是我的代码的一部分曾经的样子:
// When bot receives a message:
client.on('message', msg => {
// Where do you live?
if (IfIncludesAll(msg.content.toLocaleLowerCase(), ["where", ["you"], ["live"]])) {
var where_i_live = ["I live in (Town Name).", "I live in (Building), in (Town Name)."]
msg.channel.send(where_i_live[Math.floor(Math.random() * where_i_live.length)])
}
// What is your name?
else if (IfIncludesAll(msg.content.toLocaleLowerCase(), ["what", ["your"], ["name"]])) {
var my_name = ["I'm (nickname)!", "I'm (nickname).", "My name is (Full name), but you can call me (nickname)!"]
msg.channel.send(my_name[Math.floor(Math.random() * my_name.length)])
}
// Get monkedev chat to take over:
else {
if (msg.author.bot) {
return;
}
fetch(`https://api.monkedev.com/fun/chat?msg=${msg.content}&uid=${msg.author.id}`)
.then(response => response.json())
.then(data => {
msg.channel.send(data.response);
})
}
});
该代码将尝试检测我添加的问题之一,如果没有,它将让monkedev fun/chat接管。这样做的主要问题是它只能回答一个问题。为了解决这个问题(并使它不需要写太多,添加更多问题),我将它重复的大部分内容放入一个名为includesAllResponse的函数中。这是函数的样子:
function includesAllResponse(message, question, responses) {
if (IfIncludesAll(message.toLocaleLowerCase(), question)) {
return (responses[Math.floor(Math.random() * responses.length)])
}
}
因此,现在消息代码如下所示:
client.on('message', msg => {
// Where do you live?
msg.channel.send((includesAllResponse(msg.content.toLocaleLowerCase(), ["where", "you", "live"], ["Greendale.", "I live in Greendale", "Forge Cottage, in Greendale."])));
// What is your name?
msg.channel.send((includesAllResponse(msg.content.toLocaleLowerCase(), ["what", "your", "name"], ["I'm Postman Pat!", "I'm Pat.", "My name is Pat Clifton, but you can call me Postman Pat!"])));
});
现在,我不确定将接收来自monkeyev fun/chat输出的代码放在哪里,因为我不再使用if 和else if。有没有办法做到这一点?还是我需要回到类似于旧代码的东西?
解决方案
推荐阅读
- java - 当用户在 Java8 中输入错误的日期格式时如何给出错误消息
- tcp - 在 OMNET++ 中的某些事件后如何正确向服务器发送自定义消息
- react-native - 无法对齐自动完成视图
- python - 如何以不同的速率从 pandas 数据帧中对每个组进行采样
- python - 使用 Python 从字符串中提取 2 位整数
- java - 使用 PowerMockito 测试 Unirest
- ios - 将 ImageBackground 调整为全屏
- ms-access - MSAccess 富文本编辑工具中的字体限制
- java - 为什么我的代码只比较数组的第一个和最后一个数字 - Java
- python - 名称未在 python 模块中定义