我不确定Math.int 是什么,以及为什么你认为if (parts[0] === Prefix + 'number') 它也会是(parts[0] === Math.int)。不幸的是,它不会像这样工作。您不能接受命令,也不能接受任何后续消息作为对机器人问题的回应。
但是,对于消息收集器来说,这是一个很好的用例。首先,您可以发送第一个问题并要求第一个限制。发送此消息后,您可以使用channel.createMessageCollector 在频道中设置消息收集器。
它接受 filter 和 options 对象。使用过滤器,您可以检查传入消息是否来自键入命令的作者以及他们的响应是否为有效数字。
createMessageCollector 返回一个MessageCollector,因此您可以订阅collect 和end 事件。
每当收集到消息时,就会发出 collect 事件。如果这是第一个响应,您可以将其存储在一个数组中 (limits) 并发送一条新消息询问最大值。
一旦用户发送第二个有效数字,end 事件就会触发,因此您可以生成一个随机数字并将其发送给用户。 end 事件也会在达到最大时间时触发,因此您可以检查原因是否是超时,如果是,则发送错误消息。
您还可以创建一个辅助函数来生成两个数字之间的随机整数:
function randomInt([min, max]) {
if (min > max) {
[min, max] = [max, min];
}
return Math.floor(Math.random() * (max - min + 1) + min);
}
这是完整的代码:
if (command === 'number') {
const embedMin = new MessageEmbed()
.setTitle(`? Get a random number ?`)
.setColor('GREEN')
.setDescription('What is the minimum number?');
await message.channel.send(embedMin);
// filter checks if the response is from the author who typed the command
// and if the response is a valid number
const filter = (response) =>
response.author.id === message.author.id && !isNaN(response.content.trim());
const collector = message.channel.createMessageCollector(filter, {
// set up the max wait time the collector runs
time: 60000, // ms
// set up the max responses to collect
max: 2,
});
// it stores the user responses
const limits = [];
collector.on('collect', async (response) => {
const num = parseInt(response.content.trim(), 10);
limits.push(num);
// if this is the first number sent
if (limits.length === 1) {
const embedMax = new MessageEmbed()
.setTitle(`? Get a random number ?`)
.setColor('GREEN')
.addField('Minimum', limits[0])
.setDescription('What is the maximum number?');
// send the next question
message.channel.send(embedMax);
}
});
// runs when either the max limit is reached or the max time
collector.on('end', (collected, reason) => {
console.log({ collected });
if (reason === 'time') {
const embedTimeout = new MessageEmbed()
.setTitle(`? Get a random number ?`)
.setColor('RED')
.setDescription(
`I'm sorry, I haven't received a response in a minute, so I'm off now. If you need a new random number again, type \`${prefix}number\``,
);
message.channel.send(embedTimeout);
}
if (limits.length === 2) {
// get a random number
const embedRandom = new MessageEmbed()
.setTitle(`? Get a random number ?`)
.setColor('GREEN')
.addField('Minimum', limits[0], true)
.addField('Maximum', limits[1], true)
.setDescription(`Your random number is: ${randomInt(limits)}`);
message.channel.send(embedRandom);
}
});
}