Search code examples
discorddiscord.jsdiscord-buttons

Adding buttons to an application sent to specified applicationChannelId


Yes I know TLDR but I would appreciate the help

Ok I have this wall of code below I use for applications

It uses a button to start the application (asking questions)

and after the application is filled in it sends that application to a specified applicationChannelId

is there any way I could add buttons to the application that was sent to the applicationChannelId to accept or deny members?

Accept would add a role by id and sends a message to the original applicant

//Not the code I tried using just an example for what the Accept button would do
//
let teamRole = message.guild.roles.cache.find(role => role.id == "761996603434598460")
member.roles.add(teamRole)

member.send("You have been accepted into the team")

Deny would send a message to the original applicant

I have tried doing this for the past few days but just can't get it to work it either does nothing or breaks everything

I have removed some info from the code below to make it shorter

Code for my button I already use to start the application for an applicant

client.on("message", async (message) => {
    const reqEmbed = {
        color: 0xed5181,
        title: 'Blind Spot Team Requirements',
        url: 'link',
        author: {
            name: '',
            icon_url: '',
            url: '',
        },
        description: '',
        thumbnail: {
            url: '',
        },
        fields: [{
            "name": `Read through these Requirements`,
            "value": `- requirments will go here`,
        }, ],
        image: {
            url: '',
        },
        footer: {
            text: 'Blind Spot est 2019',
            icon_url: 'link',
        },
    };
     //
    // Don't reply to bots
    let admins = ['741483726688747541', '741483726688747541'];
    if (message.content.startsWith(`#blindspot`)) {
        message.delete();
        const amount = message.content.split(" ")[1];
        if (!admins.includes(message.author.id)) {
            message.reply("You do not have permission to do that!");
            return;
        }
        // Perform raw API request and send a message with a button,
        // since it isn't supported natively in discord.js v12
        client.api.channels(message.channel.id).messages.post({
            data: {
                embeds: [reqEmbed],
                components: [{
                    type: 1,
                    components: [{
                        type: 2,
                        style: 4,
                        label: "Apply",
                        // Our button id, we can use that later to identify,
                        // that the user has clicked this specific button
                        custom_id: "send_application"
                    }]
                }]
            }
        });
    }
});

Rest of code that handles questions and sends application to applicationChannelId when complete

// Channel id where the application will be sent
const applicationChannelId = "652099170835890177";
// Our questions the bot will ask the user
const questions = ["These are the questions but have deleted them to make this shorter",];
// Function that will ask a GuildMember a question and returns a reply
async function askQuestion(member, question) {
    const message = await member.send(question);
    const reply = await message.channel.awaitMessages((m) => {
        return m.author.id === member.id;
    }, {
        time: 5 * 60000,
        max: 1
    });
    return reply.first();
}
client.ws.on("INTERACTION_CREATE", async (interaction) => {
    // If component type is a button
    if (interaction.data.component_type === 2) {
        const guildId = interaction.guild_id;
        const userId = interaction.member.user.id;
        const buttonId = interaction.data.custom_id;
        const member = client.guilds.resolve(guildId).member(userId);
        if (buttonId == "send_application") {
            // Reply to an interaction, so we don't get "This interaction failed" error
            client.api.interactions(interaction.id, interaction.token).callback.post({
                data: {
                    type: 4,
                    data: {
                        content: "I have started the application process in your DM's.",
                        flags: 64 // make the message ephemeral
                    }
                }
            });
            try {
                // Create our application, we will fill it later
                const application = new MessageEmbed()
                .setTitle("New Application")
                .setDescription(`This application was submitted by ${member}/${member.user.tag}`)
                .setFooter("If the @Username doesn't appear please go to general chat and scroll through the member list")
                .setColor("#ED4245");
                const cancel = () => member.send("Your application has been canceled.\n**If you would like to start your application again Click on the Apply button in** <#657393981851697153>");
                // Ask the user if he wants to continue
                const reply = await askQuestion(member, "Please fill in this form so we can proceed with your tryout.\n" + "**Type `yes` to continue or type `cancel` to cancel.**");
                // If not cancel the process
                if (reply.content.toLowerCase() != "yes") {
                    cancel();
                    return;
                }
                // Ask the user questions one by one and add them to application
                for (const question of questions) {
                    const reply = await askQuestion(member, question);
                    // The user can cancel the process anytime he wants
                    if (reply.content.toLowerCase() == "cancel") {
                        cancel();
                        return;
                    }
                    application.addField(question, reply);
                }
                await askQuestion(member, "Would you like to submit your Application?\n" + "**Type `yes` to get your Application submitted and reviewed by Staff Members.**");
                // If not cancel the process
                if (reply.content.toLowerCase() != "yes") {
                    cancel();
                    return;
                }
                // Send the filled application to the application channel
                client.channels.cache.get(applicationChannelId).send(application);
            } catch {
                // If the user took too long to respond an error will be thrown,
                // we can handle that case here.
                member.send("You took too long to respond or Something went wrong, Please contact a Staff member\n" + "The process was canceled.");
            }
        }
    }
});

at this point I just feel like not even doing this and keep it as is because its driving me insane


Solution

  • You very well can! just send it as you send your normal buttons!

        const {
            MessageButton,
            MessageActionRow
        } = require("discord.js"),
            const denybtn = new MessageButton()
                .setStyle('DANGER')
                .setEmoji('❌')
                .setCustomId('deny')
        
        const acceptbtn = new MessageButton()
            .setStyle('SUCCESS')
            .setEmoji('✔')
            .setCustomId('accept')
        
        
        client.channels.cache.get(applicationChannelId).send({
            embeds: [application],
            components: [new MessageActionRow().addComponents["acceptbtn", "denybtn"]]
        });
        
        const collector = msg.createMessageComponentCollector({
            time: 3600000,
            errors: ["time"],
        });
        await collector.on("collect", async (r) => {
            if (r.user.id !== message.author.id)
                return r.reply({
                    content: "You may not accept/ deny this application",
                    ephemeral: true,
                });
            if (r.customId === "acceptbtn") {
                let teamRole = message.guild.roles.cache.find(role => role.id == "761996603434598460")
                member.roles.add(teamRole)
                member.send("You have been accepted into the team")
            }
            if (r.customId === "denybtn") {
                member.send("You have been rejected");
            }
        });
    

    NOTE:
    Please be mindful that since your question lacks the functions / method definitions you are using I have used discord.js v13's methods, you may update your discord.js version and the code will work as intended ALTHOUGH the component collector's functions have been directly copy pasted from your question and in some instances such as member#send member is not defined, so please take this as an example and I urge you to write the code instead of copy pasting directly!