首页 > 解决方案 > Discord 斜杠命令“交互失败”V13

问题描述

Discord 在 v13 中添加了这些斜杠命令,我已按照 discordjs.guide 网站了解如何操作。

我的代码是:

//packages

const { Client, Collection, Intents } = require("discord.js");
const client = new Client({ intents: [Intents.FLAGS.GUILDS] });
const disbut = require("discord-buttons");
client.commands = new Collection();
const moment = require("moment");
const { MessageEmbed } = require("discord.js");
const AntiSpam = require("discord-anti-spam");
const ms = require("ms");
const { Slash } = require("discord-slash-commands");
const slash = new Slash(client);
const rtkn = ">r";
const { REST } = require("@discordjs/rest");
const { Routes } = require("discord-api-types/v9");
const { token, owner, bowner, clientid, guildid, prefix } = require("./config.json");
const fs = require("fs");
const commandFiles = fs.readdirSync("./commands").filter((file) => file.endsWith(".js"));
const commands = [];
const cmds = [];
disbut(client);

for (const file of commandFiles) {
    const command = require(`./commands/${file}`);
    commands.push(command.data.toJSON());
}
const commands = [];

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);
        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);
    }
})();

const clean = (text) => {
    if (typeof text === "string") return text.replace(/`/g, "`" + String.fromCharCode(8203)).replace(/@/g, "@" + String.fromCharCode(8203));
    else return text;
};

client.on("message", (message) => {
    const args = message.content.split(" ").slice(1);

    if (message.content.startsWith(prefix + "eval")) {
        if (message.author.id !== owner) return;
        try {
            const code = args.join(" ");
            let evaled = eval(code);

            if (typeof evaled !== "string") evaled = require("util").inspect(evaled);

            message.channel.send(clean(evaled), { code: "xl" });
        } catch (err) {
            message.channel.send(`\`ERROR\` \`\`\`xl\n${clean(err)}\n\`\`\``);
        }
    }
});

client.on("message", (message) => {
    const args = message.content.split(" ").slice(1);

    if (message.content.startsWith(prefix + "eval")) {
        if (message.author.id !== bowner) return;
        try {
            const code = args.join(" ");
            let evaled = eval(code);

            if (typeof evaled !== "string") evaled = require("util").inspect(evaled);

            message.channel.send(clean(evaled), { code: "xl" });
        } catch (err) {
            message.channel.send(`\`ERROR\` \`\`\`xl\n${clean(err)}\n\`\`\``);
        }
    }
});

client.on("warn", (err) => console.warn("[WARNING]", err));
client.on("error", (err) => console.error("[ERROR]", err));
client.on("disconnect", () => {
    console.warn("Disconnected!");
    process.exit(0);
});
process.on("unhandledRejection", (reason, promise) => {
    console.log("[FATAL] Possibly Unhandled Rejection at: Promise ", promise, " reason: ", reason.message);
});

client.login(token);

//ping.js contents below.

const { SlashCommandBuilder } = require("@discordjs/builders");

module.exports = {
    data: new SlashCommandBuilder().setName("ping").setDescription("Replies with Pong!"),
    async execute(interaction) {
        await interaction.reply("Pong!");
    },
};

我的 ping.js 文件是:

const { SlashCommandBuilder } = require("@discordjs/builders");

module.exports = {
    data: new SlashCommandBuilder().setName("ping").setDescription("Replies with Pong!"),
    async execute(interaction) {
        return interaction.reply("Pong!");
    },
};

当我运行代码时,它会很好地注册斜杠命令,但是当我运行它时,它会显示“交互失败”。请帮忙。

标签: javascriptnode.jsdiscorddiscord.js

解决方案


您的代码结构不合理。您有很多已弃用的模块,并且您声明commands了两次。但是,问题是您从不调用client.commands.set. 在您的for...of循环中,您调用commands.push而不是client.commands.set.

我不知道该SlashCommandBuilder函数是如何工作的,但我怀疑该toJSON方法会返回如下所示的内容:

{
    name: 'commandName',
    description: 'description',
    options: []
}

您必须将循环更改为如下所示:

for (const file of commandFiles) {
    const command = require(`./commands/${file}`);
    const data = command.data.toJSON()
    client.commands.set(data.name, data);
}

推荐阅读