Discord.js机器人Quick Math命令无法识别用户正确回复问题求助
问题原因
- 类型不匹配
你计算得到的正确答案ab是数字类型,而用户发送的消息内容m.content是字符串类型,使用严格相等运算符===判断时,类型不一致会直接返回false,导致过滤器永远匹配不到正确答案。 - 消息收集参数配置错误
你调用awaitMessages时没有设置max: 1参数,该参数表示匹配到1条符合规则的消息后就立即返回结果。你仅配置了time:30000和errors:["time"],即便过滤器匹配到了正确答案,程序还是会继续收集消息直到30秒超时,最终将收集到的消息集合作为超时错误抛出到catch分支,所以你才会在超时后才看到控制台打印的消息集合。
另外你代码里var ab = await a + b的await是多余的,两个普通数字相加是同步运算,不需要异步等待。
修复方案
修改过滤器的判断逻辑,同时补充awaitMessages的max参数,还可以加上trim()处理避免用户输入时带空格导致识别失败,参考代码如下:
const { MessageEmbed } = require('discord.js'); const Discord = require("discord.js") module.exports = { name: "game", description: "smth", aliases: ["gamestart", "startgame"], permissions: ["MANAGE_MESSAGES"], timeout: 10000, execute: async (client, message, args) => { var a = Math.floor(Math.random() * 50) + 1 var b = Math.floor(Math.random() * 50) + 1 // 去掉多余的await var ab = a + b console.log(ab) let embed = new MessageEmbed() .setTitle(":chart_with_downwards_trend: Quick Math") .setDescription(`Solve the problem below and get XP.\n\n\`${a}\` + \`${b}\` = **???**`) .setFooter("123") const msg = await message.channel.send(embed) try { let filter = (m) => { if (m.author.bot) return false; // 统一转成数字再判断,同时处理输入两端的空格 return m.channel.id == msg.channel.id && Number(m.content.trim()) === ab }; // 补充max:1参数,匹配到1条正确消息就直接返回 let res = await msg.channel.awaitMessages(filter, { max: 1, time: 30000, errors: ["time"], }); if (res && res.size > 0) { // 取第一个匹配到的消息的作者作为获胜者 const winner = res.first().author let winEmbed = new MessageEmbed() .setTitle(":chart_with_downwards_trend: Quick Math") .setDescription(`The correct answer was \`${ab}\`\n\nThe winner is **${winner.tag}**!`) .setFooter("123") msg.channel.send(winEmbed) } } catch (err) { console.log(err) msg.channel.send("No one answered!"); } } }
内容的提问来源于stack exchange,提问作者8less
相关产品推荐
相关产品推荐

