How to make a button work infinitely and not only once when pressed discord.js

Viewed 53

I just learnt how to make a button in discord.js, and I even learnt how to make a cookie counter, but the only problem is that I can only click it once. If I do it again, it doesn't work. My code is:

let button = new ButtonBuilder()
        .setCustomId('cookie')
        .setLabel('0')
        .setStyle(ButtonStyle.Primary)

        let clicker = new ActionRowBuilder()
        .addComponents(
            button,
        );
        console.log(button);
        console.log(button.data.label);

for the components and

        const filter = i => i.customId === 'cookie' && i.user.id === `${interaction.user.id}`;

        const collector = interaction.channel.createMessageComponentCollector({ filter, time: 15000 });

        collector.on('collect', async i => {
            if (i.customId === 'cookie'){
                // cookieCount(guildid, messageid);
                const newCookie = Number(button.data.label + 1);
                clicker = new ActionRowBuilder()
                .addComponents(
                    new ButtonBuilder()
                    .setCustomId('cookie')
                    .setLabel(`${newCookie}`)
                    .setStyle(ButtonStyle.Primary),
                );

                await i.update({ embeds: [embed], components: [clicker]})
            }
        });

for the update. Btw I'm relatively new to discord.js.

2 Answers

The time option is how long the collector will run in milliseconds. If you remove that option, it should go forever.

const collector = interaction.channel.createMessageComponentCollector({ filter });

If you are wanting to have a button that works indefinitely and through restarts of the bot you can create an event called interactionCreate and then you can filter that to run only when it's a button interaction.

From that you can check the name of the clicked button then run the correct code for that button. Using the event allows all buttons that the bot has sent to be used.

import { Client, Interaction, InteractionType } from 'discord.js';

client.on('interactionCreate', interaction => {
    if(interaction.type == InteractionType.MessageComponent) {
        if(interaction.customId == 'button_1') {
          // Your code....
        }
    }
});
Related