javascript - 正在寻找我的不和谐机器人的 8ball 命令的修复程序
问题描述
如果我只使用 ?8ball,该命令就可以正常工作。如果我将我的问题添加到命令中,我似乎无法弄清楚如何让机器人回复,例如?8ball 我应该呆在家里吗?或?8ball 是或否?
如果有用户的问题,我如何让我的机器人对 8ball 命令做出反应?我敢打赌这很简单,但不幸的是我对编码知之甚少。
感谢您的帮助。
这是代码。它适用于 ?8ball 但如果我添加问题则无效。
client.on('message', msg => {
if (msg.content === '?8ball') {
msg.reply(eightball[Math.floor(Math.random() * eightball.length)]);
}
解决方案
问题是您的 if 语句正在明确寻找
?8球
如果您希望它响应任何包含“?8ball”的请求,您可以改用:
client.on('message', msg => {
if( msg.content.includes('?8ball') ) {
msg.reply(eightball[Math.floor(Math.random() * eightball.length)]);
}
}
需要注意的是,这将无法确定他们所问的问题,只是它包含一个预定义的字符串(更糟糕的是它不检查字符串是在消息的前面还是在中间)。您必须进行额外的解析才能从消息中获取问题,例如String.split()。
将 String.split() 和Array.shift()与Array.join()一起使用以获取与查询分开的消息内容的示例:
client.on('message', msg => {
var msgarray = msg.content.split(' ');
//If the first part of the created array matches your message.
if( msgarray[0] === '?8ball' ) {
//Remove first part of array and put it together again.
msgarray.shift();
//Put the user query back together without the first part and spaces between the words
var msgcontent = msgarray.join(' ');
msg.reply(eightball[Math.floor(Math.random() * eightball.length)]);
}
});
推荐阅读
- kotlin - Moshi 改造请求
- html - 基于地理位置的 JavaScript 自动货币转换器
- c# - Elasticsearch - 通过 NEST 以编程方式添加文档 - 如何在 Elastic Cloud 中保存数据?
- python - 我收到一个 OP_REQUIRES failed at whole_file_read_ops.cc:116 错误,即使图像存在
- c# - Microsoft.EntityFrameworkCore.Database.Connection[20004]
- javascript - 在 Node 中压缩 PNG 数据 url
- python - python 新手(如在 1 周内),需要帮助指向正确的方向
- c++ - 使用 libcurl 作为 std::string 返回帖子值
- python - 尝试安装 meilisearch 时出现拒绝访问错误
- cut - 运行'cut -f 1 sample.txt'的输出没有区别