Discord.js|已设置命令冷却时间,但不起作用 [英] Discord.js | Command Cooldown is set but not working

查看:24
本文介绍了Discord.js|已设置命令冷却时间,但不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,help命令当前设置为60 seconds,因为您可以在cooldown中看到,但无论我在那里输入什么,它都不起作用,仍然设置为小于1秒。我猜对于输出,请检查此问题包含的GIF

Message.js:

const Discord = require("discord.js");
const settings = require("../../config/settings.json");

const cooldowns = new Discord.Collection();

module.exports = async (client, message) => {
    if (message.author.bot) return;
    const prefixesdatabase = client.settings.ensure(message.guild.id, settings);

    if (!client.settings.get(message.guild.id, "prefix")) {
        client.settings.set(message.guild.id, {
            prefix: settings.prefix
        });
    }

    if (message.content.match(new RegExp(`^<@!?${client.user.id}>( |)$`))) {
        message.reply(`my prefix is: `${prefixesdatabase.prefix}``);
    }

    if (!message.content.startsWith(prefixesdatabase.prefix)) return;
    const command = message.content
        .split(" ")[0]
        .slice(prefixesdatabase.prefix.length);
    const args = message.content.split(" ").slice(1);
    if (!cooldowns.has(command.name)) {
        cooldowns.set(command.name, new Discord.Collection());
    }
    const now = Date.now();
    const timestamps = cooldowns.get(command.name);
    const cooldownAmount = (command.cooldown || 2) * 1000;
    if (timestamps.has(message.author.id)) {
        const expirationTime = timestamps.get(message.author.id) + cooldownAmount;
        if (now < expirationTime) {
            const timeLeft = (expirationTime - now) / 2000;
            return message.reply(
                `Before using **${
                    prefixesdatabase.prefix
                }${command}**, please wait for **${timeLeft.toFixed(
                    1
                )} second for cooldowns!**`
            );
        }
    }
    timestamps.set(message.author.id, now);
    setTimeout(() => timestamps.delete(message.author.id), cooldownAmount);
    let cmd;
    if (client.commands.has(command)) {
        cmd = client.commands.get(command);
    } else if (client.aliases.has(command)) {
        cmd = client.commands.get(client.aliases.get(command));
    }
    try {
        cmd.run(client, message, args);
    } catch (e) {
        return console.log(`Invalid command: ${command}`);
    } finally {
        console.log(
            `${message.author.username} using command ${prefixesdatabase.prefix}${command}`
        );
    }
};

help.js

const Discord = require("discord.js");

module.exports.run = async (client, message, args) => {
    const settings = require("../../config/settings.json");
    const prefixesdatabase = client.settings.ensure(message.guild.id, settings);

    const helpArray = message.content.split(" ");
    const helpArgs = helpArray.slice(1);

    if (!helpArgs[0]) {
        const embed = new Discord.MessageEmbed()
            .setColor("#b491c8")
            .setDescription(
                `**My prefix:** `${prefixesdatabase.prefix}` , Slash Commands list for `/help`
Click [HERE](https://discord.com/api/oauth2/authorize?client_id=${client.user.id}&permissions=8&scope=bot%20applications.commands) to invite me to your server.`
            )
            .addField("**:gear: Basic**", "`help`, `ping`, `vote`, `uptime`, `setprefix`")
            .addField(
                "**🛠️ Moderation**",
                "`ban`, `clear`, `clearwarn`, `createchannel`, `createemoji`, `kick`, `lockchannel`, `mute`, `rename`, `slowmode`, `unban`, `unlockchannel`, `unmute`, `warn`, `warnings`"
            )           
            .addField(
                "**⚙ Utility**",
                "`aes256`, `avatar`, `channel`, `embed`, `roleinfo`, `reverse`, `setafk`, `snipe`, `stats`, `timer`, `translate`, `whois`, `weather`, `youtube`"
            )
            .addField(
                "**:magic_wand: Pruning**",
                "`urole`, `unorole`, `krole`, `knorole`, `fetch`"
            )           
            .addField(
                "**:tada: Giveaways**",
                "`start-giveaway`, `reroll`, `end-giveaway`"
            )
            .addField(
                "**:frame_photo: Images**",
                "`captcha`, `circle`, `delete`, `gay`, `changemymind`, `trigger`, `clyde`, `petpet`, `magik`, `iphonex`"
            )
            .addField(
                "**:musical_note: Music**",
                "`play`, `stop`, `skip`, `queue`, `autoplay`, `loop`, `volume`, `pause`, `resume`"
            )
            .addField(
                "**:partying_face: Fun**",
                "`8ball`, `cat`, `deaes256`, `kiss`, `meme`, `ngif`, `pat`, `poke`, `smug`, `thigh`, `tickle`"
            )           
            .addFields(
                { name: ':desktop: Github (Source Code)', value: 'https://github.com/mashwishi/PruneBot' },
                { name: ':revolving_hearts: Support the Developer:', value: 'https://ko-fi.com/mashwishi' }   
              )         
            .setTitle('Prune Bot | Commands')
            .setFooter(`©${nowyear} ${client.user.username} Created by Mashwishi.
Command requested by: ${message.author.username}#${message.author.discriminator}`, `https://i.imgur.com/ypxq7B9.png`)
            .setThumbnail('https://i.imgur.com/ypxq7B9.png')    
            .setAuthor('Join our Discord Server', 'https://i.imgur.com/hKeHeEy.gif', 'https://discord.io/LIMYAW');
        message.channel.send({ embed });
    }

    if (helpArgs[0]) {
        let command = helpArgs[0];

        if (client.commands.has(command)) {
            command = client.commands.get(command);
            let alia = command.help.aliases;
            if (command.help.aliases < 1) alia = "No aliases";

            const embed = new Discord.MessageEmbed()
                .setAuthor(
                    `Command: ${command.help.name}`,
                    client.user.displayAvatarURL()
                )
                .setDescription(
                    `
            **Description:**
```${
                            command.help.description ||
                            "There is no Description for this command."
                        }```
**Usage:**
```${
                        command.help.usage || "No Usage"
                    }```
**Permissions:**
```${
                        command.help.accessableby || "Members"
                    }```
**Cooldown (in seconds):**
```${
                        command.help.cooldown || "No Cooldown"
                    }```
**Aliases:**
```${alia}````
                    
                )
                .setColor("#4a4b4d")
                .setFooter(
                    `© ${nowyear} ${client.user.username} | This command requested by ${message.author.username}#${message.author.discriminator}`
                );

            message.channel.send(embed);
        } else {
            const embeds = new Discord.MessageEmbed()
                .setDescription(`${emojis.cross} Command is not found!`)
                .setColor("RED");

            return message.channel.send(embeds);
        }
    }
};

module.exports.help = {
    name: "help",
    description: "This command is used for displaying all commands.",
    usage: "p!help",
    accessableby: "Members",
    aliases: ['?', 'commands', 'command'],
    cooldown: 60
};

推荐答案

message.js中,您可能将command与导出的命令对象(例如从help.js)混淆。使用更好的变量命名,如commandText,这样很明显,它是一个文本/字符串。

您的命令对象是cmd,您可以使用它来使用导出的函数.run()执行命令。cmd还包含.help属性,该属性具有您需要的.cooldown属性。

这里看一个简单的例子,我将如何处理这个问题。

// ... Somewhere in the code (probably index.js or main.js) ...

client.commands = new Map();
client.aliases = new Map();

// ... Inside of your command handler (command.js) ...

// The command variable defined as a require of command file (for example help.js)

client.commands.set(command.help.name, command);
command.help.aliases.forEach(alias => {
    client.aliases.set(alias, command.help.name);
});

// ... Inside of your message handler (message.js) ...

let commandText = message.content.split(" ")[0].slice(prefixesdatabase.prefix.length);
if (!client.commands.has(commandText)) {
    commandText = client.aliases.get(commandText);
    if (!commandText) return;
}

const command = client.commands.get(commandText);
const cooldownAmount = (command.help.cooldown || 2) * 1000;

// ... Rest of your code ...
请注意,我们使用command.help.cooldown不是command.cooldowncommand.name等,因为导出的对象本身没有这些属性。您已使用module.exports.help = { ... }将属性.help添加到导出的对象,该属性包含namecooldown等。

要将我的解决方案实现到您的代码中,您需要替换以下内容(在message.js中):

// ... Rest of your code ...

if (!message.content.startsWith(prefixesdatabase.prefix)) return;

let commandText = message.content.split(" ")[0].slice(prefixesdatabase.prefix.length);
if (!client.commands.has(commandText)) {
    commandText = client.aliases.get(commandText);
    if (!commandText) return;
}

const command = client.commands.get(commandText);
const args = message.content.split(" ").slice(1);

if (!cooldowns.has(command.help.name)) {
    cooldowns.set(command.help.name, new Discord.Collection());
}

const now = Date.now();
const timestamps = cooldowns.get(command.help.name);
const cooldownAmount = (command.help.cooldown || 2) * 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(
            `Before using **${
                prefixesdatabase.prefix
            }${commandText}**, please wait for **${timeLeft.toFixed(
                1
            )} second for cooldowns!**`
        );
    }
}

timestamps.set(message.author.id, now);
setTimeout(() => timestamps.delete(message.author.id), cooldownAmount);

try {
    command.run(client, message, args);
} catch (e) {
    return console.log(`Invalid command: ${commandText}`);
} finally {
    console.log(
        `${message.author.username} using command ${prefixesdatabase.prefix}${commandText}`
    );
}

结果:

这篇关于Discord.js|已设置命令冷却时间,但不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆