Search code examples
javascriptdiscorddiscord.js

Discord.js V13 Set Button Cooldown


I have recently made my ticket bot, but I need to add a cooldown to the "close ticket" button to prevent someone from flooding the button and sending multiple messages, I haven't found any possible way to do that. How would I add a cooldown on a specific button?

My button code:

      const row = new client.discord.MessageActionRow()
        .addComponents(
          new client.discord.MessageButton()
          .setCustomId('confirm-close')
          .setLabel('Fechar o Ticket')
          .setStyle('DANGER'),
          new client.discord.MessageButton()
          .setCustomId('no')
          .setLabel('Cancelar Fechamento')
          .setStyle('SECONDARY'),
        );

        const verif = await interaction.reply({
          content: 'Tem certeza de que deseja fechar o ticket?',
          components: [row]
        });

For user identification, I'm using interaction.user.id


Solution

  • In general, you can do something like this for a cooldown:

    let cooldownTime = 5000; //five seconds
    let semaphore = true; //green
    
    function doSomeStuff() {
        if (semaphore) {
            //your logic
            console.log("GREEN");
            semaphore = false; //red
            setTimeout(() => {semaphore = true;}, cooldownTime);
        } else {
            console.log("RED");
        }
    }
    <input type="button" value="CLICK ME!" onclick="doSomeStuff()">

    This only affects the logic, but you can add button disabling/enabling to it as well.