discord.js v13 slash command interaction failed - javascript

The command doesn't run and I get an "interaction failed" error.
Please tell me which file is giving the error and how can I do it?
index.js:
client.commands = new Collection();
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
client.commands.set(command.data.name, command);
}
client.once('ready', () => {
console.log('봇이 준비됐습니다!');
});
client.on('interactionCreate', async interaction => {
if (!interaction.isCommand()) return interaction.reply({content: '없는 명령어입니다...', ephemeral: true });
const command = client.commands.get(interaction.commandName);
if (!command) return interaction.reply({ content: '명령을 실행하는 데 실패했습니다...', ephemeral: true });
try {
await command.execute(interaction);
} catch (error) {
console.error(error);
return interaction.reply({ content: '명령을 실행하는 데 실패했습니다...', ephemeral: true });
}
});
s();
keepAlive();
client.login(token);
commands/help.js:
async execute(interaction) {
const helpembed = new MessageEmbed()
.setColor('red')
.setTitle('명령어')
return interaction.reply({embeds: [helpembed]});
},

there are several things wrong with your code
File help.js:
Have you imported the MessageEmbed constructor : const { MessageEmbed } = require('discord.js');
You can't do .setColor('red'), you have to do .setColor('#ff0000')
File index.js:
const command = client.commands.get(interaction.commandName); Why are you trying to fetch our interactions in commands ? Maybe you should try with const command = client.interactions.get(interaction.commandName); (if the collection of interactions was declared)
For more details about the error, maybe check on your console and provide the error if you have acces to it.

Related

DiscordAPIError 40060: "Interaction has already been acknowledged"

I am in a problem where I am experiencing this error and I tried my best to fix this API error.
index.js:
const fs = require('node:fs');
const path = require('node:path');
const { Events, Collection, ActivityType } = require('discord.js');
const client = require('./client.js');
client.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 && 'execute' in command) {
client.commands.set(command.data.name, command);
} else {
console.log(`[WARNING] The command at ${filePath} is missing a required "data" or "execute" property.`);
}
}
client.on(Events.InteractionCreate, async interaction => {
if (!interaction.isModalSubmit()) return;
if (interaction.customId === 'myModal') {
await interaction.reply({ content: 'Your submission was received successfully!' });
const good = interaction.fields.getTextInputValue('good');
const bot = interaction.fields.getTextInputValue('bot');
client.users.send('821682594830614578', `good: "${good}"
bot: "${bot}" from ${interaction.user.username}`);
}
});
client.on(Events.InteractionCreate, interaction => {
if (!interaction.isChatInputCommand()) return;const command = interaction.client.commands.get(interaction.commandName);
if (!command) {
console.error(`No command matching ${interaction.commandName} was found.`);
return;
}
try {
command.execute(interaction);
} catch (error) {
console.error(error);
interaction.reply({ content: 'There was an error while executing this command!', ephemeral: true });
}
});
client.once(Events.ClientReady, c => {
client.user.setActivity('you or i have no food', { type: ActivityType.Watching });
console.log(`Logged in as ${c.user.tag}`);
});
client.login(process.env.token);
ping.js:
const { SlashCommandBuilder } = require('discord.js');
const client = require('./../client.js');
module.exports = {
data: new SlashCommandBuilder()
.setName('ping')
.setDescription('Ping! Pong!'),
async execute(interaction) {
await interaction.reply(`Websocket heartbeat: ${client.ws.ping} ms.
Roundtrip latency: NaN ms.`);
},
};
I placed the client variable to client.js because some commands need the client variable thus placing it in a different file. I followed the discord.js guide, so you may see some code from there.
You are using two times the InteractionCreate Event you should combine the two as followed:
client.on(Events.InteractionCreate, async (interaction) => {
if (interaction.isModalSubmit()) {
if (interaction.customId === "myModal") {
await interaction.reply({
content: "Your submission was received successfully!",
});
const good = interaction.fields.getTextInputValue("good");
const bot = interaction.fields.getTextInputValue("bot");
client.users.send(
"821682594830614578",
`good: "${good}"
bot: "${bot}" from ${interaction.user.username}`
);
}
} else if (interaction.isChatInputCommand()) {
const command = interaction.client.commands.get(interaction.commandName);
if (!command) {
console.error(
`No command matching ${interaction.commandName} was found.`
);
return;
}
try {
command.execute(interaction);
} catch (error) {
console.error(error);
interaction.reply({
content: "There was an error while executing this command!",
ephemeral: true,
});
}
} else {
interaction.reply({
content: "Interaction was no ModalSubmit or ChatInputCommand",
ephemeral: true,
});
}
});
For your problem with the double interaction reply. It would be helpful to include the full error message and your js file from the command as well. Because with the proposed solution there only can be one interaction.reply in index.js so there is no problem

Error In My Discord Bot: Cannot read properties of undefined (reading 'get')

I've been getting this error recently and I don't really know how I'm supposed to fix this;
TypeError: Cannot read properties of undefined (reading 'get')
This is the line of code it refers to:
const command1 = interaction.client.commands.get(interaction.commandName);
It was working earlier, but I tried adding the command refresh thingy and it's not working anymore.
Here's my full code:
const { REST, Routes } = require('discord.js');
const fs = require('node:fs');
const { clientId, guildId, token } = require('./config.json');
const path = require('node:path');
const { Client, Collection, GatewayIntentBits } = require('discord.js');
const client = new Client({ intents: [GatewayIntentBits.Guilds] });
const commands = [];
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
commands.push(command.data.toJSON());
}
client.once('ready', () => {
console.log('Ready!');
});
const rest = new REST({ version: '10' }).setToken(token);
(async () => {
try {
console.log(`Started refreshing ${commands.length} application (/) commands.`);
const data = await rest.put(
Routes.applicationCommands(clientId),
{ body: commands },
);
console.log(`Successfully reloaded ${data.length} application (/) commands.`);
} catch (error) {
console.error(error);
}
})();
client.on('interactionCreate', async interaction => {
if (!interaction.isChatInputCommand()) return;
const command1 = interaction.client.commands.get(interaction.commandName);
if (!command1) {
console.error(`No command matching ${interaction.commandName} was found.`);
return;
}
try {
await command1.execute(interaction);
} catch (error) {
console.error(error);
await interaction.reply({ content: 'There was an error while executing this command!', ephemeral: true });
}
});
client.login(token);
hey try adding this code
const channel = await client.channels.fetch('<channel-id>')

Discord not loading slash commands

I am trying to make a slash command system for my discord.js bot, but it does not show up in the app
Here is the code I am using
const {
Client,
Collection,
Intents
} = require('discord.js');
const client = new Client({
intents: [Intents.FLAGS.GUILDS]
});
const fs = require('fs');
const {
Routes
} = require('discord-api-types/v9');
const { REST } = require('#discordjs/rest');
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));
const commands = [];
// Creating a collection for commands in client
client.commands = new Collection();
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
commands.push(command.data.toJSON());
client.commands.set(command.data.name, command);
}
client.on('ready', () => {
console.log(`Ready! Logged in as ${client.user.tag}`)
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
// Set a new item in the Collection
// With the key as the command name and the value as the exported module
console.log(`Loaded slash command /${command.data.name}.`)
}
const CLIENT_ID = client.user.id;
const rest = new REST({
version: '9'
}).setToken("myToken");
(async () => {
try {
await rest.put(
Routes.applicationCommands(CLIENT_ID), {
body: commands
},
);
console.log('Successfully registered all application commands globally');
} catch (error) {
if (error) console.error(error);
}
})();
})
client.on('interactionCreate', async interaction => {
if (!interaction.isCommand()) return;
const command = client.commands.get(interaction.commandName);
if (!command) return;
const { options } = interaction
try {
await command.execute(interaction, options, client);
} catch (error) {
console.error(error);
await interaction.reply({
content: `ERROR: There was a problem executing the **${command.name}** command. Please try again later.`,
ephemeral: true
});
}
});
client.login("myToken")
This is my command file (My ping.js file)
const { SlashCommandBuilder } = require("#discordjs/builders");
module.exports = {
data: new SlashCommandBuilder()
.setName("ping")
.setDescription("Ping Pong!"),
async execute(interaction, options, client) {
interaction.reply("Pong!")
}
}
Whenever I launch my bot, no slash commands appear. All the strings are logged to the console though.
I have given the bot application.commands scope.

TypeError: Cannot read properties of undefined (reading 'destroy')

I get this error:
TypeError: Cannot read properties of undefined (reading 'destroy')
When running this code:
const { SlashCommandBuilder } = require("#discordjs/builders");
require('dotenv').config()
module.exports = {
data: new SlashCommandBuilder()
.setName("restart")
.setDescription("Restarts the bot."),
async execute(interaction, args, client) {
let isBotOwner = interaction.user.id == '847213179142799452';
if (isBotOwner) {
interaction.reply('Restarting...').then(m => {
client.destroy().then(() => {
client.login(process.env.TOKEN);
});
});
} else {
interaction.reply('You cannot run this command unless you are the developer of me.')
}
}
}
The error is on client.destroy().
I've been looking in the docs and guides and on google but can't find anything on how to get it to work.
Could it be because I'm trying to destroy the client through a slash command?
Here is the command/interaction handler:
const {
Client,
Collection,
Intents
} = require('discord.js');
const client = new Client({
intents: [Intents.FLAGS.GUILDS]
});
const fs = require('fs');
require('dotenv').config()
client.commands = new Collection();
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
// Set a new item in the Collection
// With the key as the command name and the value as the exported module
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);
await interaction.reply({
content: 'There was an error while executing this command!',
ephemeral: true
});
}
});

How do I ping someone in a reply to a command in Discord.js

How I want my bot to ping people
I want to make it so that my bot pings people whenever it replies to a command, like how I'm replying in the image, with the #ON and not actually including a mention in the message.
I tried declaring it in the client options in the index.js file, but it doesn't seem to work.
My index.js file:
const fs = require('fs');
const { Discord, Client, Collection, Intents, MessageEmbed } = require('discord.js');
const bottoken = process.env.token
const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES], allowedMentions: { repliedUser: true } });
client.commands = new Collection();
const eventFiles = fs.readdirSync('./events').filter(file => file.endsWith('.js'));
for (const file of eventFiles) {
const event = require(`./events/${file}`);
if (event.once) {
client.once(event.name, (...args) => event.execute(...args, client));
} else {
client.on(event.name, (...args) => event.execute(...args, client, MessageEmbed));
}
}
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
client.commands.set(command.name, command);
}
client.login(bottoken);
The command that I'm testing with (this is my only command, I want to make sure that stuff like these options work before adding more commands):
module.exports = {
name: 'ping',
description: 'Replies with Pong!',
async execute(interaction) {
await interaction.reply({ content: 'Pong!' });
},
};
CommandInteraction.reply only replies to the Interaction. You need to use Message.reply.
client.on('messageCreate', message => {
if (message.author.bot) return false;
if (message.content === 'reply') {
message.reply({
content: 'This is a reply.'
})
}
});

Categories