Discord消息收集器(collector)超时未终止问题修复求助
猜乱序单词游戏消息收集器无法按时终止的修复方案
你开发的猜乱序单词小游戏中,消息收集器仅在用户猜对单词时才会停止,无人猜对或用户输入错误答案时无法按时自动终止并提示超时。
问题原因
- 过滤器逻辑错误:当前过滤器仅允许
listword数组中的消息被收集,导致用户输入的非列表内单词不会触发收集器的collect事件,让你误以为收集器未正常运行。 - 结束事件判断缺陷:
end事件仅在没有任何消息被收集时才发送超时提示,若用户输入了listword内的错误单词,收集器结束时不会触发提示,造成“未终止”的错觉。
修复后的完整代码
const listword = ['array', 'of', 'words']; // 随机选取目标单词并生成乱序版本 const word = listword[Math.floor(Math.random() * listword.length)].toLowerCase(); const jumbled = word .split('') .sort(() => 0.5 - Math.random()) .join(''); // 向交互发起者发送正确单词(仅自己可见) await interaction.followUp({ content: `The word is ${word}`, ephemeral: true }); // 在频道发送猜词提示 await interaction.channel.send(`Guess the word \`${jumbled}\`!`); // 修改过滤器:仅捕获非机器人用户的消息 const filter = (response) => !response.author.bot; // 创建消息收集器,设置15秒超时 const collector = interaction.channel.createMessageCollector({ filter, time: 15000, }); collector.on('collect', (response) => { const guessword = response.content.trim().toLowerCase(); if (guessword === word) { // 猜对的处理逻辑 response.react('✅'); response.reply({ content: `${response.author} guessed it right! The word was \`${word}\`.`, allowedMentions: { users: [], roles: [], repliedUser: false }, }); collector.stop('correct_guess'); // 手动停止并标记原因 } else { // 猜错的处理逻辑 response.react('❌'); } }); collector.on('end', (collected, reason) => { // 仅当超时结束时发送提示 if (reason === 'time') { interaction.channel.send(`Time is up! Nobody was able to guess the word \`${word}\`.`); } });
关键修改说明
- 过滤器调整:将原来的列表单词过滤改为排除机器人消息,确保所有用户输入都会被收集和处理。
- 结束事件优化:通过
reason参数判断收集器结束原因,仅在超时时发送提示,区分手动停止(猜对)和超时结束的场景。 - 代码精简:移除重复的
response.author.bot判断,逻辑更清晰。
内容的提问来源于stack exchange,提问作者Hypo
相关产品推荐
相关产品推荐

