DiscordAPIError: Unknown Message - How can I check if a message is deleted before attempting to delete it

Viewed 572

In a hypothetical situation like below, the bot can send an embed then delete the message in 3 seconds.

message.reply({ embeds: [embed] })
.then((msg) => {
setTimeout(() => msg.delete(), 3000)
})

When a user deletes the message before the bot, the bot crashes and I get this error:

C:\Users\\Documents\GitHub\omex\node_modules\discord.js\src\rest\RequestHandler.js:298
      throw new DiscordAPIError(data, res.status, request);
            ^

DiscordAPIError: Unknown Message
    at RequestHandler.execute (C:\Users\\Documents\GitHub\\node_modules\discord.js\src\rest\RequestHandler.js:298:13)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
    at async RequestHandler.push (C:\Users\\Documents\GitHub\\node_modules\discord.js\src\rest\RequestHandler.js:50:14)
    at async MessageManager.delete (C:\Users\\Documents\GitHub\\node_modules\discord.js\src\managers\MessageManager.js:205:5)
    at async Message.delete (C:\Users\\Documents\GitHub\\node_modules\discord.js\src\structures\Message.js:709:5) {
  method: 'delete',
  path: '/channels/877943546932494377/messages/888575942379847681',
  code: 10008,
  httpStatus: 404,
  requestData: { json: undefined, files: [] }
}

So is there a way to detect if a message is deleted before attempting to delete it?

2 Answers

Building off this answer by TayDex you should check Message#deleted after the timeout has ended. The reason being is that once the timer starts, it's possible that the message gets deleted within the 3 seconds it's counting down.

Additionally you can add a catch() callback to Message#delete() for error handling and preventing crashes.

message.reply({ embeds: [embed] })
.then(msg => {
   setTimeout(() => {
      if (!msg.deleted) {
         msg.delete()
         .catch(err => {
            console.log('An error occurred but the bot is still running')
            console.error(err)
         })
      }
   }, 3000)
})
Related