Search code examples
javascriptnode.jsdiscorddiscord.js

Discord slash command "interaction failed" V13


Discord added these slash commands in v13, I have followed the discordjs.guide website on how to do it. I'm havinga bit of trouble when I actually use the commands. interaction failed.

My code is:

//packages

const { Client, Collection, Intents } = require("discord.js");
const client = new Client({ intents: [Intents.FLAGS.GUILDS] });
client.commands = new Collection();
const { MessageEmbed } = require("discord.js");
const { Slash } = require("discord-slash-commands");
const slash = new Slash(client);;
const { REST } = require("@discordjs/rest");
const { Routes } = require("discord-api-types/v9");
const fs = require("fs");
const commandFiles = fs.readdirSync("./commands").filter((file) => file.endsWith(".js"));
const commands = [];
const cmds = [];

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

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!");
    },
};

When I run the code, it registers the slash commands fine, but when I run it, it says interaction failed


Solution

  • Your code is not well structured. You have a lot of deprecated modules and you declared commands twice. The problem however, is that you never call client.commands.set. In your for...of loop, you called commands.push instead of client.commands.set.

    I don’t know how the SlashCommandBuilder function works, but I suspect the toJSON method would return something that looks like this:

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

    You have to change your loop to look like this:

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