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

Discord.js V13斜杠命令执行报interaction failed错误求解

问题原因

你的代码存在3个核心问题导致交互无响应触发错误:

  • 未将加载到的命令实例存入client.commands集合,触发interactionCreate事件时无法匹配到对应的命令执行逻辑,程序直接中断无返回,Discord接收不到响应就会提示interaction failed
  • 重复声明commands变量,加载完命令数据后又用const commands = []将注册用的命令数组清空(你当前能正常注册是偶发的变量提升问题,属于隐患)
  • 引入了多余的第三方包discord-slash-commands,discord.js v13已经原生支持斜杠命令交互,该第三方包会拦截原生的交互事件导致你的监听器失效
修复方案

按照以下步骤修改主文件代码:

  1. 删除所有discord-slash-commands相关的引入和实例化代码
  2. 删除重复的const commands = []声明
  3. 在命令加载循环中添加将命令存入client.commands的逻辑
  4. 补全你代码中缺失的token、clientId、guildId变量赋值

修复后的主文件核心代码参考:

// 引入依赖
const { Client, Collection, Intents } = require("discord.js");
const { REST } = require("@discordjs/rest");
const { Routes } = require("discord-api-types/v9");
const fs = require("fs");

// 配置参数 请替换为你自己的参数
const token = '你的机器人Token';
const clientId = '你的机器人客户端ID';
const guildId = '你的测试服务器ID';

// 初始化客户端
const client = new Client({ intents: [Intents.FLAGS.GUILDS] });
client.commands = new Collection();

const commandFiles = fs.readdirSync("./commands").filter((file) => file.endsWith(".js"));
const commands = [];

// 加载命令
for (const file of commandFiles) {
    const command = require(`./commands/${file}`);
    commands.push(command.data.toJSON());
    // 新增:将命令存入client.commands集合
    client.commands.set(command.data.name, command);
}

// 交互监听器
client.on("interactionCreate", async (interaction) => {
    if (!interaction.isCommand()) return;

    const command = client.commands.get(interaction.commandName);
    if (!command) return;

    try {
        await command.execute(interaction);
    } catch (error) {
        console.error(error);
        // 兼容已经延迟回复的场景
        if (interaction.deferred || interaction.replied) {
            await interaction.editReply({ content: "There was an error while executing this command!", ephemeral: true });
        } else {
            await interaction.reply({ content: "There was an error while executing this command!", ephemeral: true });
        }
    }
});

// 注册命令
const rest = new REST({ version: "9" }).setToken(token);
(async () => {
    try {
        console.log("Started refreshing application (/) commands.");
        await rest.put(Routes.applicationGuildCommands(clientId, guildId), { body: commands });
        console.log("Successfully reloaded application (/) commands.");
    } catch (error) {
        console.error(error);
    }
})();

client.login(token);

修改完成后重启机器人即可正常执行斜杠命令,ping.js代码无需改动。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 08:18:03