You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Discord.js v14应用命令注册成功但无法响应问题求助

问题排查与修复

核心问题:交互类型判断错误

在Discord.js v14中,interaction.isCommand()仅用于识别斜杠命令,上下文菜单命令(用户/消息右键菜单)需要用interaction.isContextMenuCommand()来判断。你的代码直接对非斜杠命令返回,导致上下文菜单的交互根本没进入处理逻辑,自然无法响应。

修复步骤

1. 修改interactionCreate.js的交互判断

替换原有的判断逻辑,同时兼容斜杠命令和上下文菜单命令:

const client = require('../../index.js');
const { MessageEmbed } = require("discord.js");
const config = require("../../config.json");

client.on('interactionCreate', async interaction => {
    // 同时匹配斜杠命令和上下文菜单命令
    if (!interaction.isCommand() && !interaction.isContextMenuCommand()) return;

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

    if (!command) return interaction.reply({ content: "无效命令", ephemeral: true });

    try {
        await command.run(client, interaction);
    } catch (e) {
        function id(length) {
            var result = '';
            var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
            var charactersLength = characters.length;
            for (var i = 0; i < length; i++) {
                result += characters.charAt(Math.floor(Math.random() * charactersLength));
            }
            return result;
        }

        const errorId = id(12);
        console.error(`错误ID: ${errorId}\n`, e);
        await interaction.reply({ content: `错误ID: \`${errorId}\``, ephemeral: true });
    }
});

2. 确认上下文菜单命令已被正确加载到集合中

检查你的命令加载代码(通常是index.js或专门的命令加载器),确保上下文菜单命令和斜杠命令一样被添加到client.slash_commands集合里。示例加载逻辑如下:

const fs = require('fs');
const path = require('path');
const { Collection } = require('discord.js');

client.slash_commands = new Collection();

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);
    // 将命令添加到集合中
    if ('data' in command && 'run' in command) {
        client.slash_commands.set(command.data.name, command);
    } else {
        console.log(`[警告] ${filePath} 中的命令缺少必要的"data"或"run"属性`);
    }
}

3. 可选:区分上下文菜单类型(按需使用)

如果需要针对用户/消息上下文菜单做不同逻辑,可以在命令的run函数里判断:

async run(interaction) {
    if (interaction.isUserContextMenuCommand()) {
        // 用户右键菜单逻辑
        await interaction.reply({ content: `你右键了用户 ${interaction.targetUser.tag}!`, ephemeral: true });
    } else if (interaction.isMessageContextMenuCommand()) {
        // 消息右键菜单逻辑
        await interaction.reply({ content: `你右键了消息: ${interaction.targetMessage.content.slice(0, 20)}...`, ephemeral: true });
    }
}

验证修复

重新部署机器人,触发上下文菜单命令,此时应该能正常收到"hi!"的回复。如果仍有问题,检查控制台是否有报错,或重新执行命令注册脚本确保命令已更新。

内容的提问来源于stack exchange,提问作者Di Mostavay

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 12:17:39