您不能在事件侦听器中添加事件侦听器。导出的对象已经在 client.on('message', fn) 中。
不过,这是 message collectors 的完美用例。当您希望机器人在发送第一个命令后接收额外的输入时,收集器很有用。
您可以设置过滤器以仅收集来自键入命令的用户的消息。您还可以使用time 选项设置时间限制,或使用max option 设置接受的最大猜测次数。
在.on('collect) 事件中,您可以检查响应是否有效,并据此发送消息。当猜到正确的数字时,我们使用collector.end() 方法停止收集更多消息。
检查下面的工作示例;我也添加了一些 cmets:
async execute(client, message, args, Discord) {
const numbers = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10'];
const randomNumber = numbers[Math.floor(Math.random() * numbers.length)];
const maxWait = 30000; // in ms, so it's 30 sec
const embed = new Discord.MessageEmbed()
.setColor('#FF0000')
.setTitle('Guess the number between 1 and 10! ?');
await message.channel.send(embed);
// filter checks if the response is from the author who typed the command
// and if the response is one of the possible guesses
const filter = (response) =>
response.author.id === message.author.id &&
numbers.includes(response.content.trim());
const collector = message.channel.createMessageCollector(filter, {
// set up the max wait time the collector runs
time: maxWait,
});
// fires when a response is collected
collector.on('collect', (response) => {
if (response.content.trim() === randomNumber) {
message.channel.send(
`??? Woohoo, ${response.author}! ???\n\nYour guess is correct, my number was \`${randomNumber}\`.`,
);
// the guess is correct, so stop this collector and emit the "end" event
collector.stop();
} else {
// another chance if the response is incorrect
message.channel.send(
`Oh, ${response.author}, \`${response.content}\` is not correct... ?\nDo you want to try another number?`,
);
}
});
// fires when the collector is finished collecting
collector.on('end', (collected, reason) => {
// only send a message when the "end" event fires because of timeout
if (reason !== 'time') return;
// if there are incorrect guesses
if (collected.size > 0) {
return message.channel.send(
`Ah, ${message.author}. Out of ${collected.size} guess${
collected.size > 1 ? 'es' : ''
} you couldn't find the number \`${randomNumber}\`. I'm not saying you're slow, but no more guesses are accepted.`,
);
}
message.channel.send(
`Okay, ${message.author}, I'm bored and I can't wait any longer. No more guesses are accepted. At least you could have tried...`,
);
});
};