Skip to content
Advertisement

Discord.js | Command Cooldown is set but not working

So the message.js where the cooldown go and help.js is a command, help command is currently set to 60 seconds as can you see at the cooldown but no matter what I input there it doesn’t work and still set to less than 1 second I guess for the output kindly check the GIF included to this question.

enter image description here

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`nClick [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.nCommand 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:**n```${
                            command.help.description ||
                            "There is no Description for this command."
                        }```n**Usage:**n```${
                        command.help.usage || "No Usage"
                    }```n**Permissions:**n```${
                        command.help.accessableby || "Members"
                    }```n**Cooldown (in seconds):**n```${
                        command.help.cooldown || "No Cooldown"
                    }```n**Aliases:**n```${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
};

Advertisement

Answer

Inside of your message.js, you probably confused command with the exported command object (from help.js for example). Use better variable naming, like commandText so it is clear, that it is a text/string.

Your command object is cmd, which you use to execute the command using the exported function .run(). The cmd also contains .help property, which has the .cooldown property you want.

Here look at a simple example, how I would handle this problem.

// ... 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 ...

Note that we use command.help.cooldown not command.cooldown or command.name, etc. Because the exported object itself doesn’t have such properties. You added a property .help to the exported object using module.exports.help = { ... }, which contains the name and cooldown, etc.

To implement my solution into your code you need to replace the following (inside 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}`
    );
}

Result:

enter image description here

Advertisement