Search code examples
javascriptdiscorddiscord.js

Erro (interactionCreate) - Discord JS (v14)


Hello, come down to the necessary information.

Console error

(Discord.js v14) Ralphi online!
Comandos registrados com sucesso (local).
[nodemon] restarting due to changes...
[nodemon] restarting due to changes...
[nodemon] starting `node index.js`
(Discord.js v14) Ralphi online!
Comandos registrados com sucesso (local).
Error: Ocorreu um erro ao executar 1.
    at Object.execute (D:\MichelDev\Pessoais JM\Relphi (BOT)\events\interactionCreate.js:15:23)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
node:events:504
      throw er; // Unhandled 'error' event
      ^

DiscordAPIError[40060]: Interaction has already been acknowledged.
    at SequentialHandler.runRequest (D:\MichelDev\Pessoais JM\Relphi (BOT)\node_modules\@discordjs\rest\dist\lib\handlers\SequentialHandler.cjs:293:15)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
    at async SequentialHandler.queueRequest (D:\MichelDev\Pessoais JM\Relphi (BOT)\node_modules\@discordjs\rest\dist\lib\handlers\SequentialHandler.cjs:99:14)
    at async REST.request (D:\MichelDev\Pessoais JM\Relphi (BOT)\node_modules\@discordjs\rest\dist\lib\REST.cjs:52:22)
    at async ChatInputCommandInteraction.reply (D:\MichelDev\Pessoais JM\Relphi (BOT)\node_modules\discord.js\src\structures\interfaces\InteractionResponses.js:110:5)
    at async Object.execute (D:\MichelDev\Pessoais JM\Relphi (BOT)\events\interactionCreate.js:20:17)
Emitted 'error' event on Client instance at:
    at emitUnhandledRejectionOrErr (node:events:383:10)
    at processTicksAndRejections (node:internal/process/task_queues:85:21) {
  rawError: {
    message: 'Interaction has already been acknowledged.',
    code: 40060
  },
  code: 40060,
  status: 400,
  method: 'POST',
  url: 'https://discord.com/api/v10/interactions/1027241278359998474/aW50ZXJhY3Rpb246MTAyNzI0MTI3ODM1OTk5ODQ3NDpFRW1aY1BUUkYxQmdDVzBRU2Jia1RKUXlVZ1VmeThRN3FSaFE3T1RDQlBBR0pMOXBRU2xjWUxFOU1uMzdwYUdKZlJYSGliaWkwTU56RW5sMXBFeWo2dm1YUUh0azRJZnRsaXJJejhMUEVTYmczQzVDeGs1dlloMGNMblZMeXExVg/callback',
  requestBody: {
    files: [],
    json: {
      type: 4,
      data: {
        content: 'Ocorreu um erro ao executar o comando.',
        tts: false,
        nonce: undefined,
        embeds: undefined,
        components: undefined,
        username: undefined,
        avatar_url: undefined,
        allowed_mentions: undefined,
        flags: 64,
        message_reference: undefined,
        attachments: undefined,
        sticker_ids: undefined
      }
    }
  }
}
[nodemon] app crashed - waiting for file changes before starting...
[nodemon] restarting due to changes...
[nodemon] starting `node index.js`
(Discord.js v14) Ralphi online!
Comandos registrados com sucesso (local).

Code (InteractionCreate.js)

module.exports = {
name: "interactionCreate",
once: true,
async execute (interaction) 
{
    if(!interaction.isCommand()) return;

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

    if(!command) return;

        try 
        {
            await command.execute(interaction);
            //throw new Error("Ocorreu um erro ao executar 1.")
        }
        catch(err)
        {
            if(err)console.log(err);
            await interaction.reply({
                content:"Ocorreu um erro ao executar o comando.",
                ephemeral: true,
        });
    }
}

}

Command file

const { SlashCommandBuilder } = require("discord.js"); 
module.exports = {
    data: new SlashCommandBuilder()
        .setName("ping")
        .setDescription("Pong."),
    async execute(interaction)
    {
        interaction.reply({ 
            content: "Pong!",
            ephemeral: true,
        }); 
    }
}

In order to optimize my bot's code (discord v14) I was creating the event list. After creating the idea of ​​InteractionCreated events I started to have some problems in the code, but I still can't get the cause of the error. After a brief check on the error that is exposed in the console I checked such an "er" but I didn't find the same and I suspect (err).

Please help me, thanks.


Solution

  • So, what the Error itself means is that the Interaction you're trying to reply to has already been responded to. This could happen if you have multiple interactionCreate() listeners, defer the reply, send multiple replies, etc.

    However, I've recently come across an issue where the event will "run twice" -- it will run the first time, then run the same event again, with the same parameters. However, it only happens after the first one, which allows us to use a makeshift solution. Please note: I do not recommend using this unless you're certain that there are no other plausible solutions. I have to use it for one of my projects, and it's tedious, but still an option.

    First off, at the start of your interactionCreate() file, create a new Set.

    const alreadyResponsed = new Set();
    

    And now, you're going to want to add the token of the Interaction to that Set, and remove it after a second. This is how you would go about it:

    client.on("interactionCreate", async(i) => {
      if(alreadyResponded.has(i.token)) return;
      else {
        alreadyResponded.add(i.token);
        setTimeout(() => {
          alreadyResponsed.delete(i.token);
        }, 1000);
      }
    
      // your code here!
    });
    

    Once again, I do not recommend this solution if you have other viable methods of doing slow. It pointlessly slows your script down, and it might get fixed later. However, if you've tried a ton of stuff and couldn't fix it, similar to how it was for me, then this will work.