javascript - how do I Build a discord button that replies with a new set of button - Stack Overflow

I want it to be where you type in your slashmand example:"bank" and it'll show 2 differ

I want it to be where you type in your slashmand 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 mand 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('')
            .setImage('.jpeg')
            .setDescription('Choose your team shitter');

            await interaction.reply({  ephemeral: true, embeds: [embed], ponents: [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 mand = clientmand.get(interactionmandName);
        if(!mand) return;

        try{
            await mand.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] });

clientmands = new Collection();

// mand files 
const mandsPath = path.join(__dirname, 'mands');
const mandFiles = fs.readdirSync(mandsPath).filter(file => file.endsWith('.js'));

for (const file of mandFiles) {
    const filePath = path.join(mandsPath, file);
    const mand = require(filePath);
    clientmands.set(mand.data.name, mand);
}

// 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 mand = msg.content.substring(1);

    if(!clientmands.has(mand)) return;

    try{
        await clientmands.get(mand).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 mand = clientmands.get(interactionmandName);

    if (!mand) return;

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

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

this is my deploy-mands.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 mands = [];
const mandFiles = fs.readdirSync('./mands').filter(file => file.endsWith('.js'));


for (const file of mandFiles) {
    const mand = require(`./mands/${file}`);
    mands.push(mand.data.toJSON());
}

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

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

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

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

I want it to be where you type in your slashmand 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 mand 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')
            .setImage('https://i.imgur./s54Riow.jpeg')
            .setDescription('Choose your team shitter');

            await interaction.reply({  ephemeral: true, embeds: [embed], ponents: [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 mand = client.mand.get(interaction.mandName);
        if(!mand) return;

        try{
            await mand.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.mands = new Collection();

// mand files 
const mandsPath = path.join(__dirname, 'mands');
const mandFiles = fs.readdirSync(mandsPath).filter(file => file.endsWith('.js'));

for (const file of mandFiles) {
    const filePath = path.join(mandsPath, file);
    const mand = require(filePath);
    client.mands.set(mand.data.name, mand);
}

// 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 mand = msg.content.substring(1);

    if(!client.mands.has(mand)) return;

    try{
        await client.mands.get(mand).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 mand = client.mands.get(interaction.mandName);

    if (!mand) return;

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

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

this is my deploy-mands.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 mands = [];
const mandFiles = fs.readdirSync('./mands').filter(file => file.endsWith('.js'));


for (const file of mandFiles) {
    const mand = require(`./mands/${file}`);
    mands.push(mand.data.toJSON());
}

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

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

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

        console.log('Successfully reloaded application (/) mands.');
    } catch (error) {
        console.error(error);
    }
})();
Share Improve this question edited Jun 1, 2022 at 4:44 JustAG33K 1,5763 gold badges16 silver badges34 bronze badges asked Jun 1, 2022 at 4:29 DCamDCam 311 gold badge2 silver badges8 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 2

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 mands. As a remendation, 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 mand and runs the `
        const mand = client.mand.get(interaction.mandName);
        if(!mand) return;

        try{
            await mand.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',
              ponents: [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',
              ponents: [ActionRow],
              ephemeral: true
            });
        
        }
        return;
    }

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

        const mand = client.mand.get(interaction.mandName);
        if(!mand) return;

        try{
            await mand.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 ponents.

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745551898a4632614.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信