Creating a Confirm Button

I’m trying to create a purge command which has a confirm and cancel button. However, I can’t move the variable amount, which the command interaction gets, to the button detection, because the button detection can’t detect the command parameters. My replit.

I’d recommend attaching the “amount” directly to the custom id of the button itself.

// Like, your purge command in index.js
} else if (interaction.commandName == 'purge') {
  const amount = interaction.options.get('amount').value;
  const channel = interaction.channel;

  const cancel = new ButtonBuilder()
    .setCustomId('cancel')
    .setLabel('Cancel')
    .setStyle(ButtonStyle.Secondary);

  const confirm = new ButtonBuilder()
    .setCustomId(`confirm-${amount}`) // Here we add the amount to the customId.
    .setLabel('Confirm')
    .setStyle(ButtonStyle.Danger);

  const confirmButtons = new ActionRowBuilder()
    .addComponents(cancel, confirm);

  interaction.reply({ content: `Are you sure you want to purge ${amount} messages?`, ephemeral: true, components: [confirmButtons]})
}

// Button Interaction
} else if (interaction.isButton()) {
  console.log(interaction.componentType);
  if (interaction.customId.startsWith('confirm')) {
    const amount = parseInt(interaction.customId.split('-')[1]); // Extract the amount from the customId.
    interaction.channel.bulkDelete(amount, true);
    interaction.reply({ content: `Successfully deleted ${amount} messages.`, ephemeral: true});
  } else if (interaction.customId === 'cancel') {
    interaction.reply({ content: "Purge cancelled.", ephemeral: true });
  }
}

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.