简体   繁体   English

所有交互的未知交互 - Discord.js v13

[英]Unknown Interaction on All interactions - Discord.js v13

All of a sudden I keep on getting this error on most interactions and my bot just sends `"Bot is thinking...".突然之间,我在大多数交互中不断收到此错误,而我的机器人只是发送“机器人正在思考......”。

[UnhandledRejection] DiscordAPIError: Unknown interaction
    at RequestHandler.execute (/Users/main/Desktop/Discordbots/gamerscavern/node_modules/discord.js/src/rest/RequestHandler.js:349:13)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
    at async RequestHandler.push (/Users/main/Desktop/Discordbots/gamerscavern/node_modules/discord.js/src/rest/RequestHandler.js:50:14)
    at async SelectMenuInteraction.reply (/Users/main/Desktop/Discordbots/gamerscavern/node_modules/discord.js/src/structures/interfaces/InteractionResponses.js:98:5)

Example this help command.示例此帮助命令。 Which returns Unknown interaction on the interaction.update() part in the collector AND in the filter when another user interacts with it.当另一个用户与之交互时,它会在收集器和过滤器中的interaction.update()部分返回未知交互。 I have no clue why this is happening.我不知道为什么会这样。 And as mentioned, it worked fine just a few hours ago.如前所述,它在几个小时前运行良好。

Here is my code:这是我的代码:

Help command:帮助命令:

const {
    Client,
    Message,
    MessageEmbed,
    MessageActionRow,
    MessageSelectMenu,
} = require('discord.js');

module.exports = {
    name: 'help',
    description: 'List all of my commands or info about a specific command.',
    aliases: ['commands'],
    usage: '[command name]',
    category: 'info',
    cooldown: 3,
    /**
     *
     * @param {Client} client
     * @param {Message} message
     * @param {String[]} args
     */
    execute: async (client, message, args, prefix) => {
        if (message.author.bot) return;
        const data = [];
        const { commands } = message.client;

        const emojis = {
            config: '⚙️',
            info: 'ℹ️',
            moderation: '🔨',
            owner: '🔐',
            utility: '🛠',
            voice: '🗣',
            welcoming: '👋',
        };

        if (!args[0]) {
            const directories = [
                ...new Set(client.commands.map((cmd) => cmd.category)),
            ].filter((e) => e !== 'secrets' && e !== undefined);

            const formatString = (str) =>
                `${str[0].toUpperCase()}${str.slice(1).toLowerCase()}`;

            const categories = directories.map((dir) => {
                const getCommands = client.commands
                    .filter((cmd) => cmd.category === dir)
                    .map((cmd) => {
                        return {
                            name: cmd.name || 'There is no name',
                            description:
                                cmd.description ||
                                'There is no description for this command',
                        };
                    });

                return {
                    directory: formatString(dir),
                    commands: getCommands,
                };
            });

            const initialEmbed = new MessageEmbed()
                .setTitle('Developer: Kev#1880')
                .setDescription(
                    '~~———————————————~~\n** Links ➼ ** [Invite](https://discord.com/api/oauth2/authorize?client_id=711371556504207423&permissions=8&scope=bot) | [Server](https://discord.gg/XkCTA88) | [Upvote](https://top.gg/bot/711371556504207423/vote)    \n~~———————————————~~\n\n**Please choose a category in the dropdown menu**'
                )
                .setColor('#5787E8')
                .setThumbnail(client.user.displayAvatarURL({ format: 'png' }))
                .setFooter(
                    `Requested by: ${message.author.tag}`,
                    message.author.displayAvatarURL({ format: 'png' })
                )
                .setTimestamp();

            const components = (state) => [
                new MessageActionRow().addComponents(
                    new MessageSelectMenu()
                        .setCustomId('help-menu')
                        .setPlaceholder('Please select a category')
                        .setDisabled(state)
                        .addOptions(
                            categories.map((cmd) => {
                                return {
                                    label: cmd.directory,
                                    value: cmd.directory.toLowerCase(),
                                    description: `Commands from ${cmd.directory} category`,
                                    emoji:
                                        emojis[cmd.directory.toLowerCase()] ||
                                        null,
                                };
                            })
                        )
                ),
            ];

            const initialMessage = await message.channel.send({
                embeds: [initialEmbed],
                components: components(false),
            });

            const filter = async (interaction) => {
                if (interaction.user.id === message.author.id) {
                    return true;
                }
                interaction.reply({
                    content: `This is not your help menu, create your own with >help!`,
                    ephemeral: true,
                });
                return false;
            };

            const collector = initialMessage.createMessageComponentCollector({
                filter,
                componentType: 'SELECT_MENU',
                time: 600000,
            });

            collector.on('collect', (interaction) => {
                console.log(interaction);
                const [directory] = interaction.values;
                const category = categories.find(
                    (x) => x.directory.toLowerCase() === directory
                );

                const categoryEmbed = new MessageEmbed()
                    .setTitle(`${formatString(directory)} commands`)
                    .setDescription(
                        '~~———————————————~~\n** Links ➼ ** [Invite](https://discord.com/api/oauth2/authorize?client_id=711371556504207423&permissions=8&scope=bot) | [Server](https://discord.gg/XkCTA88) | [Upvote](https://top.gg/bot/711371556504207423/vote)    \n~~———————————————~~\n\n**Here are the list of commands**'
                    )
                    .setColor('#5787E8')
                    .addFields(
                        category.commands.map((cmd) => {
                            return {
                                name: `\`${cmd.name}\``,
                                value: cmd.description,
                                inline: true,
                            };
                        })
                    )
                    .setThumbnail(
                        client.user.displayAvatarURL({ format: 'png' })
                    )
                    .setFooter(
                        `Requested by: ${message.author.tag}`,
                        message.author.displayAvatarURL({ format: 'png' })
                    )
                    .setTimestamp();

                interaction.update({
                    embeds: [categoryEmbed],
                });
            });

            collector.on('end', () => {
                const ranOut = new MessageEmbed()
                    .setColor('RED')
                    .setTitle('Oops!')
                    .setDescription(
                        'Interaction ran out of time! Please create a new help menu!'
                    )
                    .setThumbnail(
                        client.user.displayAvatarURL({ format: 'png' })
                    )
                    .setFooter(
                        `Requested by: ${message.author.tag}`,
                        message.author.displayAvatarURL({ format: 'png' })
                    )
                    .setTimestamp();

                initialMessage.edit({
                    embeds: [ranOut],
                    components: components(true),
                });
            });
        }
        if (args[0]) {
            const name = args[0].toLowerCase();
            const command =
                commands.get(name) ||
                commands.find((c) => c.aliases && c.aliases.includes(name));
            if (!command) {
                return message.reply({
                    content: "that's not a valid command!",
                });
            }

            // data.push(`**Name:** ${command.name}`);

            if (command.aliases)
                data.push(`**Aliases:** ${command.aliases.join(', ')}`);
            if (command.description)
                data.push(`**Description:** ${command.description}`);
            if (command.nb) data.push(`**NB:** ${command.nb}`);
            if (command.userPermissions)
                data.push(
                    `**User Permissions:** \`${command.userPermissions.join(
                        ', '
                    )}\``
                );
            if (command.botPermissions)
                data.push(
                    `**Bot Permissions:** ${command.botPermissions
                        .map((perm) => {
                            return `\`${perm}\``;
                        })
                        .join(', ')}`
                );
            if (command.usage)
                data.push(
                    `**Usage:** \`${prefix}${command.name} ${command.usage}\``
                );
            if (command.examples)
                data.push(`**Examples:**
            ${command.examples
                .map((example) => {
                    return `\`${prefix}${command.name} ${example}\``;
                })
                .join('\n')}
        `);

            data.push(`**Cooldown:** ${command.cooldown || 3} second(s)`);

            const commandHelp = new MessageEmbed()
                .setTitle(`Command: **${command.name}**`)
                .setColor('#5787E8')
                .setDescription(`${data.join('\n')}`)
                .setFooter(
                    `Requested by: ${message.author.tag}`,
                    message.author.displayAvatarURL({ format: 'png' })
                );

            return message.reply({ embeds: [commandHelp] });
        }
    },
};

interactionCreate event:交互创建事件:

const blacklist = require('../../models/blacklists.js');
const guildBlacklist = require('../../models/guildBlacklist.js');
const reactionRoles = require('../../models/reactionRoles.js');
module.exports = async (Discord, client, interaction) => {
    //Slash Command Handling
    if (interaction.isCommand()) {
        // await interaction.deferReply();
        //blacklists
        const bl = await blacklist.findOne({ Client: client.user.id });
        if (bl) {
            if (bl.Users) {
                if (bl.Users.includes(interaction.user.id)) return;
            }
        }

        const gbl = await guildBlacklist.findOne({
            Guild: interaction.guild.id,
        });
        if (gbl) {
            if (gbl.Users) {
                if (gbl.Users.includes(interaction.user.id)) return;    
            }
        }

        const cmd = client.slashCommands.get(interaction.commandName);
        if (!cmd) return interaction.reply({ content: 'An error has occured' });

        const args = [];

        for (let option of interaction.options.data) {
            if (option.type === 'SUB_COMMAND') {
                if (option.name) args.push(option.name);
                option.options?.forEach((x) => {
                    if (x.value) args.push(x.value);
                });
            } else if (option.value) args.push(option.value);
        }
        interaction.member = interaction.guild.members.cache.get(
            interaction.user.id
        );

        if (!interaction.member.permissions.has(cmd.userPermissions || []))
            return interaction.reply({
                content: 'You do not have the permissions to use this command!',
                ephemeral: true,
            });

        cmd.execute(client, interaction, args);
    }

    //Context Menu Handling
    if (interaction.isContextMenu()) {
        await interaction.deferReply();
        const command = client.slashCommands.get(interaction.commandName);
        if (command) command.execute(client, interaction);
    }

    //Reaction Roles Handling
    if (interaction.isSelectMenu()) {
        await interaction.deferReply();
        const reactionPanel = await reactionRoles.findOne({
            guildId: interaction.guildId,
            'reactionPanels.customId': `${interaction.customId}`,
        });

        if (reactionPanel) {
            //if (interaction.customId !== 'reaction-roles') return;
            const roleId = interaction.values[0];

            const role = interaction.guild.roles.cache.get(roleId);
            if (!role) return;

            const memberRoles = interaction.member.roles;

            const hasRole = memberRoles.cache.has(roleId);

            if (hasRole) {
                memberRoles.remove(roleId);
                interaction.followUp({
                    content: `${role.name} has been removed from you`,
                    ephemeral: true,
                });
            } else {
                memberRoles.add(roleId);
                interaction.followUp({
                    content: `${role.name} has been added to you`,
                    ephemeral: true,
                });
            }
        }
    }
};

What happened发生了什么


If you do not reply or acknowledge the interaction in 3 seconds.如果您未在 3 秒内回复或确认交互。 There's a cooldown!有冷却时间!
The user will see interaction failed and the reply gate is closed.用户将看到交互失败并且回复门已关闭。

Solution解决方案


However, if you defer the reply and edit later, the gate will open until you update the defer or edit the reply.但是,如果您推迟回复并稍后编辑,则大门将打开,直到您更新推迟或编辑回复。 Here's how to do it, and here's the documentation about it .这是如何做到的,这里是关于它的文档

interaction.deferReply();

// Do some stuff that takes time right here...

interaction.editReply({ content: "replied" });

To answer your other question about the bot sending Bot is thinking... ,要回答有关发送Bot is thinking...
It happens when you defer without editing the reply after.当您推迟而不编辑回复时会发生这种情况。
It will stay like that until you do something.在你做某事之前,它会一直保持这种状态。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM