Thought
Thought

Reputation: 5846

DiscordJS, Delete previous embed message after receiving slash command

I have a bot that sends an embed message after receiving a /xyz with something like this

    client.on("interactionCreate", async (interaction) => {
      if (!interaction.isCommand()) return;
    
      const { commandName } = interaction;
    
      if (commandName === "xyz") {

         const embed = {
          title: "title of embed message",
          description: "description of embed message",
          ....
          }

    await interaction.channel.send({ embeds: [embed] });  
}

I would like to know how to delete the previous embed messages the bot sent, before sending a new one after receiving the /xyz command

Upvotes: 1

Views: 1085

Answers (2)

MrMythical
MrMythical

Reputation: 9041

Set a variable on the outer scope that you will assign when sending the embeds. Delete it whenever the command is run

let embedBefore;
client.on("interactionCreate", async (interaction) => {
      if (!interaction.isCommand()) return;
    
      const { commandName } = interaction;
    
      if (commandName === "xyz") {
         await embedBefore?.delete().catch(console.error) // delete the embed, catch and log error if thrown
         const embed = {
          title: "title of embed message",
          description: "description of embed message"
          }
        // assign embedBefore to the sent embed; Note: this is not an interaction reply
        embedBefore = await interaction.channel.send({ embeds: [embed] });
    }
})

The embed will stay there when the bot is restarted and the command is run again

Upvotes: 1

Togira
Togira

Reputation: 355

You could store the previous embed(s) (there should only be one, right, since you delete the previous ones...) in something like a Set if you have multiple embeds somehow and then before you send your response iterate over the Set and invoke the delete() method on the stored messages. Here the documentation for Sets in case you need further info.

Upvotes: 0

Related Questions