DiscordAPIError 40060: "Interaction has already been acknowledged" - javascript

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

Related

interactionCreate not working DiscordJS v13

im new to coding slash commands and for some reason my interactionCreate just stops or doesnt work? this doesn't apply the same for messageCreate so. my slash command handler works but ill put it here just in case
my slash command handler:
const fs = require('fs');
const { REST } = require('#discordjs/rest')
const { Routes } = require('discord-api-types/v9')
const token = process.env.DISCORD_TOKEN
const guild = process.env.GUILD
const appid = process.env.APPID
module.exports = async (client, Discord) => {
const slashCommands = [];
fs.readdirSync('./slashCommands/').forEach(dir => {
const slashCommandFiles = fs.readdirSync(`./slashCommands/${dir}/`).filter(file => file.endsWith('.js'));
for(const file of slashCommandFiles) {
const slashCommand = require(`../slashCommands/${dir}/${file}`)
slashCommands.push(slashCommand.data.toJSON());
}
});
const rest = new REST({ version: '9'}).setToken(token);
(async () => {
try {
console.log("Started registering slash command files!")
await rest.put(
guild
? Routes.applicationGuildCommands(appid, guild)
: Routes.applicationGuildCommands(appid),
{
body: slashCommands
}
);
console.log('Successfully registered slash commands')
} catch (err) {
console.log(err)
}
})();
}
my interactionCreate file:
module.exports = (client, Discord) => {
client.on('interactionCreate', async interaction => {
if(!interaction.isCommand()) return;
const slashCommand = client.slashCommands.get(interaction.commandName)
if(!slashCommand) return;
try {
await slashCommand.execute(client, interaction)
} catch (err) {
if(err) console.log(err);
await interaction.reply({ content: "There was an error trying to execute this command!", ephemeral: true})
}
})
}
the file i want to execute:
const { SlashCommandBuilder } = require('#discordjs/builders')
module.exports = {
data: new SlashCommandBuilder()
.setName('hello')
.setDescription('cool'),
async execute(client, interaction){
await interaction.reply({ content: "Hello!"})
}
}
it also says "The application did not respond" when i try to execute the slash command. All the file directories given in the slash command handler are all correct aswell

DiscordJs & distube - Why can't I do anything after I play music?

I am using DiscordJs and distube to create a bot for my discord server. I am using slash commands. The problem is that I can't execute any command (so I cannot even execute /stop or play another song) after I play a song. This is my code:
const {SlashCommandBuilder} = require("#discordjs/builders");
module.exports = {
data: new SlashCommandBuilder()
.setName("play")
.setDescription("Play a song.")
.addStringOption(option => option.setName("song").setDescription("The song link or name.").setRequired(true)),
async execute(interaction) {
interaction.reply({content: 'Music started.', ephemeral: true});
const {member, channel, client} = interaction;
await client.distube.play(member.voice.channel, interaction.options.get("song").value, {textChannel: channel, member: member});
}
}
My command handler:
const fs = require("fs");
const { REST } = require('#discordjs/rest');
const { Routes } = require('discord-api-types/v9');
const clientId = '12345678';
const guildId = '12345678';
module.exports = (client) => {
client.handleCommands = async (commandsFolder, path) => {
client.commandArray = [];
for (const folder of commandsFolder) {
const commandFiles = fs.readdirSync(`${path}/${folder}`).filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
const command = require(`../commands/${folder}/${file}`);
await client.commands.set(command.data.name, command);
client.commandArray.push(command.data.toJSON());
}
}
const rest = new REST({ version: '9' }).setToken("sometextthatidontwanttoshow");
await (async () => {
try {
console.log('Started refreshing application commands.');
await rest.put(
Routes.applicationGuildCommands(clientId, guildId),
{body: client.commandArray},
);
console.log('Successfully reloaded application commands.');
} catch (error) {
console.error(error);
}
})();
}
}
And this is the function that "creates" the commands:
module.exports = {
name: "interactionCreate",
async execute(interaction, client) {
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
})
}
}
}
And this is my index file
const {Client, Intents, Collection} = require("discord.js");
const fs = require("fs");
const client = new Client({intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES, Intents.FLAGS.GUILD_VOICE_STATES]});
client.commands = new Collection();
const {DisTube} = require("distube");
client.distube = new DisTube(client, {
emitNewSongOnly: true,
leaveOnFinish: false,
emitAddSongWhenCreatingQueue: false
});
module.exports = client;
const functions = fs.readdirSync("./src/functions").filter(file => file.endsWith(".js"));
const eventFiles = fs.readdirSync("./src/events").filter(file => file.endsWith(".js"));
const commandsFolders = fs.readdirSync("./src/commands");
(async () => {
for (const file of functions) {
require(`./src/functions/${file}`)(client);
}
client.handleEvents(eventFiles, "./src/events");
client.handleCommands(commandsFolders, "./src/commands");
await client.login('mybeautifultoken')
})();
Any help is highly appreciated. Thanks in advance.
Okay, I believe the issue lies in the fact that you're awaiting your command.execute(). I believe behind the scenes what this is doing is that its creating a promise that resolves once your discord bot's music finishes playing.
While its correct to use these functions asynchronously, when you call it like this it actually blocks all the other similar asynchronous functions (slash commands) from occurring until this one resolves. Let me know if this fixes it.
module.exports = {
name: "interactionCreate",
async execute(interaction, client) {
if (!interaction.isCommand()) return;
const command = client.commands.get(interaction.commandName);
if (!command) return;
try {
command.execute(interaction); //removed await
} catch (error) {
console.error(error);
await interaction.reply({
content: "There was an error while executing this command.",
ephemeral: true
})
}
}
}
index edits
await client.handleEvents(eventFiles, "./src/events");
await client.handleCommands(commandsFolders, "./src/commands");

discord.js v13 slash command interaction failed

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.

ReferenceError: client is not defined Discord.js

I cannot figure out why its saying this error here, its telling me that client isnt defined when it is defined right here though im also unsure of anything else that im missing because all of my code so far has been from the offical documentation of discord.js
(The guild and client id's have been removed for privacy reasons)
Code:
const { REST } = require('#discordjs/rest');
const { Routes } = require('discord-api-types/v9');
const { token } = require('./config.json');
const fs = require('fs');
const commands = [];
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));
// Place your client and guild ids here
const clientId = '';
const guildId = '';
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
commands.push(command.data.toJSON());
}
const rest = new REST({ version: '9' }).setToken(token);
(async () => {
try {
console.log('Started refreshing application (/) commands.');
await rest.put(
Routes.applicationCommands(clientId),
Routes.applicationGuildCommands(clientId, guildId),
{ body: commands },
);
console.log('Successfully reloaded application (/) commands.');
} catch (error) {
console.error(error);
}
})();
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
client.commands.set(command.data.name, command);
}
client.once('ready', () => {
console.log(`${client.user.tag}`)
});
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));
} else {
client.on(event.name, (...args) => event.execute(...args));
}
}
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);
return interaction.reply({ content: 'There was an error while executing this command!', ephemeral: true });
}
});
client.on('interactionCreate', async interaction => {
if (!interaction.isCommand()) return;
const { commandName } = interaction;
if (commandName === 'ping') {
await interaction.reply('Pong!');
} else if (commandName === 'server') {
await interaction.reply(`Server name: ${interaction.guild.name}\nTotal members: ${interaction.guild.memberCount}`);
} else if (commandName === 'user') {
await interaction.reply(`Your tag: ${interaction.user.tag}\nYour id: ${interaction.user.id}`);
}
});
client.on('interactionCreate', interaction => {
if (!interaction.isCommand()) return;
console.log(interaction);
});
client.on('interactionCreate', async interaction => {
if (!interaction.isCommand()) return;
if (interaction.commandName === 'ping') {
await interaction.reply('Pong!');
}
});
client.login(token);
You need to instantiate a Discord.Client in order to get access to discord.js apis.
const {Client, Intents} = require('discord.js')
const client = new Client({intents: [/* Your intents here */]})
client.login(/* your token */)
client.on('ready', function () {
/* client is ready */
}
Since discord.js v12, intents were introduced, so you will also need to use them.
More about intents: https://discordjs.guide/popular-topics/intents.html#error-disallowed-intents

Discord slash command interactions failing despite event handler logging the interactions correctly

Following along with discordjs.guide/creating-your-bot
I've made an event handler that's working correctly and returning the expected terminal logs.
However, none of the commands that were previously working are working. I've had this happen before and I had to restart the bot and the commands started functioning correctly again.
The bit I can't figure out is the interaction are being logged in my terminal successful yet they're showing up as failed interactions in the discord.
My command handler;
const fs = require('fs');
const { REST } = require('#discordjs/rest');
const { Routes } = require('discord-api-types/v9');
const { clientId, guildId, token } = require('./config.json');
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());
}
const rest = new REST({ version: '9' }).setToken(token);
(async () => {
try {
await rest.put(
Routes.applicationGuildCommands(clientId, guildId),
{ body: commands },
);
console.log('Successfully registered application commands.');
} catch (error) {
console.error(error);
}
})();
my event handler;
const fs = require('fs');
const { Client, Intents } = require('discord.js');
const { token } = require('./config.json');
const client = new Client({ intents: [Intents.FLAGS.GUILDS] });
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));
} else {
client.on(event.name, (...args) => event.execute(...args));
}
}
client.login(token);
Ping command:
const { SlashCommandBuilder } = require('#discordjs/builders'); module.exports = {
data: new SlashCommandBuilder()
.setName('ping')
.setDescription('Replies with Pong!'),
async execute(interaction) {
await interaction.reply('Pong!');
},
};
interactionCreate event listener:
module.exports = { name: 'interactionCreate', execute(interaction) { console.log(${interaction.user.tag} in #${interaction.channel.name} triggered an interaction.); }, }; This is triggering correctly at least, I'm getting an output in my log that's expected.
And my interactionCreate although this lives in with my command handling folder/code. I'll post the folder structure below as well.
client.on('interactionCreate', async interaction => {
if (!interaction.isCommand()) return;
const command = client.commands.get(interaction.commandName);
//If the command doesn't exist, it will return undefined, so exit early with return.
if (!command) return;
//If it does exist, call the command's .execute() method, and pass in the interaction variable as its argument.
try {
await command.execute(interaction);
//In case something goes wrong, log the error and report back to the member to let them know.
} catch (error) {
console.error(error);
await interaction.reply({ content: 'There was an error while executing this command!', ephemeral: true });
}
});

Categories