'How to make a button event handler in discord.js V.13

I create a function to send an embed message with a button and now I would like to create an event handler to detect when the button is clicked and execute a function in response.

I would like to create the button handler in the same folder then the event's handler folder.

The folder where I want to place my event handler



Solution 1:[1]

I finally make this code and it worked :

// Button Handler
client.buttons = new Collection();
const buttonFolders = fs.readdirSync('./buttons');

for (const folder of buttonFolders) {
    const buttonFiles = fs.readdirSync(`./buttons/${folder}`).filter(file => file.endsWith('.js'));
    for (const file of buttonFiles) {
        const button = require(`./buttons/${folder}/${file}`);
        client.buttons.set(button.data.name, button);
    }
}

client.on('interactionCreate', async interaction => {
    if(interaction.isButton()) {
        const button = client.buttons.get(interaction.customId);
        if(!button) return;

        try {
            await button.execute(interaction);
        } catch (error) {
            console.error(error);
            await interaction.reply({ content: 'There was an error while executing the button script !', ephemeral: true});
        }
    } else {
        return;
    }
})

Solution 2:[2]

button is interaction. So you can make your button handler in interactionCreate handler. You check interaction type with if statement like this;

client.on("interactionCreate", async (interaction) => {
  if (interaction.isButton()) {
    // ** Buttons handler
  }

  if (interaction.isCommand()) {
    // ** Slash commands handler
  }
});

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 cigien
Solution 2 Suleyman Celik