javascriptdiscorddiscord.jsdiscord-buttonsdiscord-interactions

how do I Build a discord button that replies with a new set of button


I want it to be where you type in your slashcommand example:"/bank" and it'll show 2 different buttons "offense" "defense" then when you click one of those buttons it'll pop up another set up buttons to click from. Right now it works to where I do /bank and it'll reply with the two buttons offense and defense and it'll reply with you clicked which ever button was clicked. But I want to to reply with another set up buttons.

// this is my button command bank.js

const { SlashCommandBuilder } = require('@discordjs/builders');
const { MessageActionRow, MessageButton, MessageEmbed } = require('discord.js');

module.exports = {
    data: new SlashCommandBuilder()
        .setName('bank')
        .setDescription('Replies with some buttons!'),
    async execute(interaction) {
        const row = new MessageActionRow()
            .addComponents(
                new MessageButton()
                    .setCustomId('offense')
                    .setLabel('Offense')
                    .setStyle('SUCCESS'),

                    new MessageButton()
                    .setCustomId(' defense')
                    .setLabel('Defense')
                    .setStyle('DANGER'),
            );

            const embed = new MessageEmbed()
            .setColor('#0099ff')
            .setTitle('Map: BANK ')
            .setURL('https://discord.js.org')
            .setImage('https://i.imgur.com/s54Riow.jpeg')
            .setDescription('Choose your team shitter');

            await interaction.reply({  ephemeral: true, embeds: [embed], components: [row] });

    },
};

this is my interactionCreate.js


module.exports = {
    name: 'interactionCreate',
    async execute(interaction, client) {
        if(interaction.isButton())
        interaction.reply("you clicked" + interaction.customId);
        console.log(interaction);

        if (!interaction.isCommand()) return;
        if (!interaction.isButton()) return;

        const command = client.command.get(interaction.commandName);
        if(!command) return;

        try{
            await command.execute(interaction);
        }catch(error){
            console.error(error);
            await interaction.reply({content : "There was an error while executing action"})
        }

        console.log(`${interaction.user.tag} in #${interaction.channel.name} triggered an interaction.`);
    },
};

this is my index.js

// Require the necessary discord.js classes
const fs = require('node:fs');
const path = require('node:path');
const { Client, Collection, Intents } = require('discord.js');
const { token } = require('./config.json');

const client = new Client({ intents: [Intents.FLAGS.GUILDS] });

client.commands = new Collection();

// command files 
const commandsPath = path.join(__dirname, 'commands');
const commandFiles = fs.readdirSync(commandsPath).filter(file => file.endsWith('.js'));

for (const file of commandFiles) {
    const filePath = path.join(commandsPath, file);
    const command = require(filePath);
    client.commands.set(command.data.name, command);
}

// event files
const eventsPath = path.join(__dirname, 'events');
const eventFiles = fs.readdirSync(eventsPath).filter(file => file.endsWith('.js'));

for (const file of eventFiles) {
    const filePath = path.join(eventsPath, file);
    const event = require(filePath);
    if (event.once) {
        client.once(event.name, (...args) => event.execute(...args));
    } else {
        client.on(event.name, (...args) => event.execute(...args));
    }
}
// When the client is ready, run this code (only once)
client.once('ready', c => {
    console.log(`Ready! Logged in as ${c.user.tag}`);
});

// When any message is sent in any channel it'll all be logged into the terminal
client.on('message', async msg => {
    if(!msg.content.startsWith(config.prefix)) return;

    var command = msg.content.substring(1);

    if(!client.commands.has(command)) return;

    try{
        await client.commands.get(command).execute(msg);
    } catch(error) {
        console.error(error);
        await msg.reply({content: "there was an error", epthemeral: true})
    }
});

// interaction files
client.on('interactionCreate', async interaction => {
    if (!interaction.isCommand()) return;

    const command = client.commands.get(interaction.commandName);

    if (!command) return;

    try {
        await command.execute(interaction);
    } catch (error) {
        console.error(error);
        await interaction.reply({ content: 'There was an error while executing this command!', ephemeral: true });
    }
});

// Login to Discord with your client's token
client.login(token);

this is my deploy-commands.js

const fs = require('node:fs');
const path = require('node:path');
const { REST } = require('@discordjs/rest');
const { Routes } = require('discord-api-types/v9');
const { clientId, guildId, token } = require('./config.json');

const commands = [];
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));


for (const file of commandFiles) {
    const command = require(`./commands/${file}`);
    commands.push(command.data.toJSON());
}

const rest = new REST({ version: '9' }).setToken(token);

(async () => {
    try {
        console.log('Started refreshing application (/) commands.');

        await rest.put(
            Routes.applicationGuildCommands(clientId, guildId),
            { body: commands },
        );

        console.log('Successfully reloaded application (/) commands.');
    } catch (error) {
        console.error(error);
    }
})();

Solution

  • We will be working inside of your interactionCreate.js where you collect the buttons.

    We will need to update the interaction with the new message. docs

    I am noticing duplicate code in your index.js and interactionCreate.js. This is where you run the slash commands. As a recommendation, you may want to remove the if (!interaction.isCommand()) return; in the interactionCreate.js and remove the index.js listener. Just to have one file handing the interactionCreate event. I'll be doing this in the example.

    Also you may find a problem in the future since in blank.js there is a space inside of the interaction customId.

    Example with one Listener

    const { MessageButton, MessageActionRow } = require('discord.js');
    
    module.exports = {
        name: 'interactionCreate',
        async execute(interaction, client) {
            if (interaction.isCommand()) { // Checks if the interaction is a command and runs the `
            const command = client.command.get(interaction.commandName);
            if(!command) return;
    
            try{
                await command.execute(interaction);
            }catch(error){
                console.error(error);
                await interaction.reply({content : "There was an error while executing action"})
            }
    
            console.log(`${interaction.user.tag} in #${interaction.channel.name} triggered an interaction.`);
            return;
    
        } else if (interaction.isButton()) { // Checks if the interaction is a button
            interaction.reply("you clicked" + interaction.customId);
            console.log(interaction);
    
            if (interaction.customId === 'offense') { // Check for the customId of the button
                console.log(`${interaction.user.tag} in #${interaction.channel.name} clicked the offense button.`);
            
                const ActionRow = new MessageActionRow().setComponents(new MessageButton() // Create the button inside of an action Row
                  .setCustomId('CustomId')
                  .setLabel('Label')
                  .setStyle('PRIMARY'));
            
                return interaction.update({ // update the interaction with the new action row
                  content: 'Hey',
                  components: [ActionRow],
                  ephemeral: true
                });
            
            }
        }
        },
    };
    

    With the original example

    module.exports = {
        name: 'interactionCreate',
        async execute(interaction, client) {
            if(interaction.isButton()) {
            interaction.reply("you clicked" + interaction.customId);
            console.log(interaction);
    
    
            if (interaction.customId === 'offense') { // Check for the customId of the button
                console.log(`${interaction.user.tag} in #${interaction.channel.name} clicked the offense button.`);
            
                const ActionRow = new MessageActionRow().setComponents(new MessageButton() // Create the button inside of an action Row
                  .setCustomId('CustomId')
                  .setLabel('Label')
                  .setStyle('PRIMARY'));
            
                return interaction.update({ // update the interaction with the new action row
                  content: 'Hey',
                  components: [ActionRow],
                  ephemeral: true
                });
            
            }
            return;
        }
    
            if (!interaction.isCommand()) return;
            if (!interaction.isButton()) return;
    
            const command = client.command.get(interaction.commandName);
            if(!command) return;
    
            try{
                await command.execute(interaction);
            }catch(error){
                console.error(error);
                await interaction.reply({content : "There was an error while executing action"})
            }
    
            console.log(`${interaction.user.tag} in #${interaction.channel.name} triggered an interaction.`);
        },
    };
    

    If you need to get the embed that was sent in the original message, you can use <interaction>.embeds to get the embed and then edit it to your liking.

    Now if you don't want to edit the interaction and reply with a new message remember that if your original message is an ephemeral you can't delete it. You can use replying methods.

    Explanation

    We are checking for the customId that was used when building the button. After we create an action row and add the new message button. Then we are updating the original message content with different components.

    Feel free to leave a comment if you run into any problems