如果收集器没有得到正确的答案,Bot就会崩溃



我制作了一个&scramble命令,该命令基本上会对一个单词进行加扰,并将其显示给人们猜测,30秒后,它将停止接受答案,并说出谁先答对了,这一部分工作正常,但当没有人答对时,机器人会因为没有返回某人而崩溃,给出错误TypeError: Cannot read property 'author' of undefined

module.exports = {
name: 'scramble',
execute(message, args) {
const Discord = require('discord.js')
let givenword = args.slice(0).join(" ");

function scramble(givenword) {
var word= givenword.split("")
n = word.length
for(var i = n - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i+1));
var tmp = word[i];
word[i] = word[j]
word[j] = tmp;
}
return word.join("")
}
scrambledword = scramble(givenword)
const embed = new Discord.MessageEmbed()
.setTitle('Scramble time!')
.setColor("RANDOM")
.setDescription("The word is: " + scrambledword)
.setFooter('You have 30 seconds to try and guess it, the first person to answer correctly ')
message.channel.send({embed});
message.delete()

const filter = m => m.content.includes(givenword)
const collector = message.channel.createMessageCollector(filter, { time: 30000 });

collector.on('collect', m => {
console.log(`Collected ${m.content}`);
});

collector.on('end', collected => {
if (collected.length <= 0) {
message.channel.send('Sadly it seems like no one has guessed the answer right... The word was ' + givenword + "!")
} else {
message.channel.send(`${collected.first().author} got the correct answer first! The answer was ${givenword}`);
}
console.log(`Collected ${collected.size} items`);
});


}
}
快速查看discord.js的文档可以发现属性Collection#length不能等于或小于0,因为它不存在。但是,您仍然可以使用Collection#array()Collection#keyArray()进行转换。我个人更喜欢第二种选择,因为我们不需要这里的其余数据。
collector.on('end', collected => {
if (collected.keyArray().length <= 0) {
message.channel.send('Sadly it seems like no one has guessed the answer right... The word was ' + givenword + "!")
} else {
message.channel.send(`${collected.first().author} got the correct answer first! The answer was ${givenword}`);
}
console.log(`Collected ${collected.size} items`);
});

最新更新