Discord.js: Есть ли какой-либо возможный способ отключить меню после выбора одного из его параметров?

#javascript #discord #discord.js

Вопрос:

Совсем недавно я взглянул на кнопки для своих ботов discord, и при этом я также обнаружил меню, которые вы можете создавать. Я хочу знать, как, если это возможно, отключить меню после выбора одного из его параметров. Идея меню заключается в том, что вы можете выбрать из подборки стихотворений. Прямо сейчас у меня есть только 3, так как я хочу решить эту проблему, прежде чем добавлять больше.

Вот кодировка, которую я использовал:

 const { MessageMenuOption, MessageMenu, MessageActionRow } = require("discord-buttons")

module.exports = {
    name: "poem",
    description: "Hear one of Natuski's poems!",
    async execute(client, message, args, Discord) {

        client.on('clickMenu', async (menu) => {
            if (menu.values[0] == 'ECF') {

                let ECFEmbed = new Discord.MessageEmbed()
                    .setTitle("Eagles Can Fly")
                    .setDescription("nMonkeys can climbnCrickets can leapnHorses can racenOwls can seeknCheetahs can runnEagles can flynPeople can trynBut that's about it.")
                    .setColor('#FF8CC5')

                await menu.reply.defer();
                menu.channel.send(ECFEmbed);

            } else {

                if (menu.values[0] == 'ALS') {
                    let ALSEmbed = new Discord.MessageEmbed()
                        .setTitle("Amy Likes Spiders")
                        .setDescription("You know what I heard about Amy?nAmy likes spiders.nIcky, wriggly, hairy, ugly spiders!nThat's why I'm not friends with her.nnAmy has a cute singing voice.nI heard her singing my favorite love song.nEvery time she sang the chorus, my heart would pound to the rhythm of the words.nBut she likes spiders.nThat's why I'm not friends with her.nnOne time, I hurt my leg really bad.nAmy helped me up and took me to the nurse.nI tried not to let her touch me.nShe likes spiders, so her hands are probably gross.nThat's why I'm not friends with her.nnAmy has a lot of friends.nI always see her talking to people.nShe probably talks about spiders.nWhat if her friends start to like spiders too?nThat's why I'm not friends with her.nnIt doesn't matter if she has other hobbies.nIt doesn't matter if she keeps it private.nIt doesn't matter if it doesn't hurt anyone.nnIt's gross.nShe's gross.nThe world is better off without spider lovers.nnAnd I'm gonna tell everyone.")
                        .setColor('#FF8CC5')

                    await menu.reply.defer();
                    menu.channel.send(ALSEmbed);

                } else {

                    if (menu.values[0] == 'BY') {
                        let BYEmbed = new Discord.MessageEmbed()
                            .setTitle("Because You")
                            .setDescription("Tomorrow will be brighter with me aroundnBut when today is dim, I can only look down.nMy looking is a little more forwardnBecause you look at me.nnWhen I want to say something, I say it with a shout!nBut my truest feelings can never come out.nMy words are a little less emptynBecause you listen to me.nnWhen something is above me, I reach for the stars.nBut when I feel small, I don't get very far.nMy standing is a little bit tallernBecause you sit with me.nnI believe in myself with all of my heart.nBut what do I do when it's torn all apart?nMy faith is a little bit strongernBecause you trusted me.nnMy pen always puts my feelings to the test.nI'm not a good writer, but my best is my best.nMy poems are a little bit dearernBecause you think of me.")
                            .setColor('#FF8CC5')

                        await menu.reply.d
                        await menu.reply.defer();
                        menu.channel.send(BYEmbed);
                    }
                }
            }
        });

        let poem1 = new MessageMenuOption()
            .setLabel('Eagles Can Fly')
            .setValue('ECF')
            .setDescription('')

        let poem2 = new MessageMenuOption()
            .setLabel('Amy Likes Spiders')
            .setValue('ALS')
            .setDescription('')

        let poem3 = new MessageMenuOption()
            .setLabel('Because You')
            .setValue('BY')
            .setDescription('')

        let poemMenu = new MessageMenu()
            .setID('Poem Menu')
            .setPlaceholder('Select Poem')
            .setMaxValues(1)
            .setMinValues(1)
            .addOption(poem1)
            .addOption(poem2)
            .addOption(poem3)

        let row = new MessageActionRow()
            .addComponent(poemMenu)

        await message.channel.send("A poem? O-Ok, which one would you like?", { components: [row] });
    }
}
 

Команда работает точно так, как задумывалось, но я хотел бы знать, что мне нужно добавить, чтобы сделать мой запрос возможным, если это возможно. Спасибо!

Ответ №1:

Во-первых, мы будем использовать новейшую версию discord.js это включает в себя кнопки, команды косой черты и меню выбора, вот что вы имеете в виду. Так что вам больше не понадобятся кнопки раздора.

Мы определяем команду. НЕ определяйте событие внутри команды, потому что событие будет выполняться больше раз.

 const { MessageMenuOption, MessageMenu, MessageActionRow } = require("discord-buttons")

const { MessageSelectMenu, MessageActionRow } = require("discord.js")

module.exports = {
    name: "poem",
    description: "Hear one of Natuski's poems!",
    async execute(client, message, args, Discord) {

        let selectMenu = new MessageSelectMenu()
        .addOptions([
            {
                label: "Eagles Can Fly",
                value: "EFC",
            },
            {
                label: "Amy Likes Spiders",
                value: "EFC"
            },
            {
                label: "Because You",
                value: "BY"
            }
        ])
        .setCustomId("PoemMenu") /* Do not use spaces when using IDs */
        .setPlaceholder("Select Poem")
        .setMinValues(1)
        .setMaxValues(1);
        
        let row = new MessageActionRow()
        .addComponents(selectMenu);

        await message.channel.send("A poem? O-Ok, which one would you like?", { components: [row] });
    }
}
 

И при определении клиента создайте новое событие:

 client.on("interactionCreate", i => {
    const { MessageEmbed } = require("discord.js");

    if (i.isSelectMenu()) {
        if (menu.values[0] == 'ECF') {

            let ECFEmbed = new Discord.MessageEmbed()
                .setTitle("Eagles Can Fly")
                .setDescription("nMonkeys can climbnCrickets can leapnHorses can racenOwls can seeknCheetahs can runnEagles can flynPeople can trynBut that's about it.")
                .setColor('#FF8CC5')

            await i.reply(EFCEmbed);

        } else {

            if (menu.values[0] == 'ALS') {
                let ALSEmbed = new Discord.MessageEmbed()
                    .setTitle("Amy Likes Spiders")
                    .setDescription("You know what I heard about Amy?nAmy likes spiders.nIcky, wriggly, hairy, ugly spiders!nThat's why I'm not friends with her.nnAmy has a cute singing voice.nI heard her singing my favorite love song.nEvery time she sang the chorus, my heart would pound to the rhythm of the words.nBut she likes spiders.nThat's why I'm not friends with her.nnOne time, I hurt my leg really bad.nAmy helped me up and took me to the nurse.nI tried not to let her touch me.nShe likes spiders, so her hands are probably gross.nThat's why I'm not friends with her.nnAmy has a lot of friends.nI always see her talking to people.nShe probably talks about spiders.nWhat if her friends start to like spiders too?nThat's why I'm not friends with her.nnIt doesn't matter if she has other hobbies.nIt doesn't matter if she keeps it private.nIt doesn't matter if it doesn't hurt anyone.nnIt's gross.nShe's gross.nThe world is better off without spider lovers.nnAnd I'm gonna tell everyone.")
                    .setColor('#FF8CC5')

                await i.reply(ALSEmbed);

            } else {

                if (menu.values[0] == 'BY') {
                    let BYEmbed = new Discord.MessageEmbed()
                        .setTitle("Because You")
                        .setDescription("Tomorrow will be brighter with me aroundnBut when today is dim, I can only look down.nMy looking is a little more forwardnBecause you look at me.nnWhen I want to say something, I say it with a shout!nBut my truest feelings can never come out.nMy words are a little less emptynBecause you listen to me.nnWhen something is above me, I reach for the stars.nBut when I feel small, I don't get very far.nMy standing is a little bit tallernBecause you sit with me.nnI believe in myself with all of my heart.nBut what do I do when it's torn all apart?nMy faith is a little bit strongernBecause you trusted me.nnMy pen always puts my feelings to the test.nI'm not a good writer, but my best is my best.nMy poems are a little bit dearernBecause you think of me.")
                        .setColor('#FF8CC5')

                    await i.reply(BYEmbed);
                }
            }
        }
    })