我已对您的代码进行了整理并对其进行了修改以使其更易于扩展。我还调整了Discord.js cooldown tutorial,让冷却时间自动添加到每个命令中。
如果您想让代码变得更好,我强烈建议您通读Discord.js guide。
完整的解释可以在这个答案的底部找到。
示范操场: discord.gg/2duzjPT.
演示
代码
const Discord = require('discord.js');
const client = new Discord.Client();
const prefix = '!';
const cooldowns = new Discord.Collection();
client.once('ready', () => {
console.log('Ready!');
});
client.on('message', (message) => {
if (message.author.bot || !message.content.startsWith(prefix)) return;
const [ command, ...args ] = message.content.slice(prefix.length).split(/\s+/g);
if (!cooldowns.has(command)) {
cooldowns.set(command, new Discord.Collection());
}
const now = Date.now();
const timestamps = cooldowns.get(command);
const cooldownAmount = 1 * 60 * 1000;
if (timestamps.has(message.author.id)) {
const expirationTime = timestamps.get(message.author.id) + cooldownAmount;
if (now < expirationTime) {
const timeLeft = (expirationTime - now) / 1000;
return message.reply(`Please wait ${timeLeft.toFixed(1)} more second(s) before reusing the \`${command}\` command.`);
}
}
timestamps.set(message.author.id, now);
setTimeout(() => timestamps.delete(message.author.id), cooldownAmount);
switch (command) {
case 'random':
let tomb = ['something1', 'something2', 'something3'];
let i = tomb[Math.floor(Math.random() * tomb.length)];
message.channel.send(i);
break;
default:
message.reply(`The command \`${command}\` was not recognized.`);
}
});
client.login(process.env.token);
说明
创建一个集合来存储有冷却时间的命令:
const cooldowns = new Discord.Collection();
如果消息是由机器人发送的,或者消息不是以前缀 (!) 开头,则消息处理程序退出:
if (message.author.bot || !message.content.startsWith(prefix)) return;
消息被分成一个命令和参数数组;这是通过删除以 .slice(prefix.length) 开头的前缀,然后在每个空白间隙处使用 .split(/\s+/g) 拆分消息来完成的:
const [ command, ...args ] = message.content.slice(prefix.length).split(/\s+/g);
如果请求的命令不在冷却集合中,则将其添加并将其值设置为新集合:
if (!cooldowns.has(command)) {
cooldowns.set(command, new Discord.Collection());
}
以毫秒为单位的当前时间放在一个变量中:
const now = Date.now();
所请求命令的集合被放置在一个变量中;这包含在 1 分钟内使用过请求的命令的所有用户:
const timestamps = cooldowns.get(command);
默认冷却时间设置为 1 分钟:
const cooldownAmount = 1 * 60 * 1000;
这会检查用户是否是请求命令集合的一部分;如果是,则计算他们可以再次使用该命令的时间,并检查是否超过了过期时间;如果没有,则计算剩余时间,向用户发送消息并退出消息处理程序:
if (timestamps.has(message.author.id)) {
const expirationTime = timestamps.get(message.author.id) + cooldownAmount;
if (now < expirationTime) {
const timeLeft = (expirationTime - now) / 1000;
return message.reply(`Please wait ${timeLeft.toFixed(1)} more second(s) before reusing the \`${command}\` command.`);
}
}
如果用户在 1 分钟内未使用该命令,则将其用户 ID 添加到集合中,并创建一个计时器以在一分钟后自动从集合中删除其用户 ID:
timestamps.set(message.author.id, now);
setTimeout(() => timestamps.delete(message.author.id), cooldownAmount);
最后,机器人会检查用户输入了什么命令并执行某些代码;如果该命令未被识别,则向用户发送一条消息:
switch (command) {
case 'random':
let tomb = ['something1', 'something2', 'something3'];
let i = tomb[Math.floor(Math.random() * tomb.length)];
message.channel.send(i);
break;
default:
message.reply(`The command \`${command}\` was not recognized.`);
}
参考文献