简体   繁体   中英

How to check if a message exists? (discord.js)

I have got an embed manager here, and I want to check if the embed exists. I delete it after it got sent, and if someone else deletes it before that, I get a DiscordAPI error. I've tried several things, but never got a solution. Can you help?

This is my code:

    error(channel, title, content) {
        var message
        var embed = new MessageEmbed() 
            .setColor(COLORS.red)
            .setDescription(content)
        if(title) {
            embed.setTitle(title)
        }
        channel.send(' ', embed).then((m) => {
            message = m
            try {
                setTimeout(function() {
                    if(MESSAGE EXISTS) {
                        m.delete()
                    } else {
                        return;
                    }
                }, 5500);
            } catch(e) {
            }

        })
        return message

    },

Edited:

    error(channel, title, content) {
        var message
        var embed = new MessageEmbed() 
            .setColor(COLORS.red)
            .setDescription(content)
        if(title) {
            embed.setTitle(title)
        }
        channel.send(' ', embed).then((m) => {
            message = m
            try {
                setTimeout(function() {
                    try {
                        channel.messages.fetch(m.id)
                      .then(m => console.log(m.content)) //it fetched the message - good
                    } catch (error) {
                        console.log(error)
                    }
                }, 5500);
            } catch(e) {
            }

        })
        return message

    },

stack trace:

DiscordAPIError: Unknown Message
    at RequestHandler.execute (D:\Discord Bot\node_modules\discord.js\src\rest\RequestHandler.js:154:13)
    at processTicksAndRejections (node:internal/process/task_queues:93:5)
    at async RequestHandler.push (D:\Discord Bot\node_modules\discord.js\src\rest\RequestHandler.js:39:14)
    at async MessageManager._fetchId (D:\Discord Bot\node_modules\discord.js\src\managers\MessageManager.js:135:18) {
  method: 'get',
  path: '/channels/797648418104934470/messages/798863571924418562',
  code: 10008,
  httpStatus: 404
}
npm ERR! code 1
npm ERR! path D:\Discord Bot
npm ERR! command failed
npm ERR! command C:\Windows\system32\cmd.exe /d /s /c node main.js debug

The API error is caused by discord trying to delete a message that doesnt exist (you have already deleted it). Try to resolve the promise by fetching the id of the embed in a try catch statement, then going from there - this way you avoid the API error.

try {
    channel.messages.fetch(message.id)
  .then(message => console.log(message.content)) //it fetched the message - good
} catch (error) {
    return; //the message no longer exists and will be ignored
}

Don't make it more difficult than needed. .send , .fetch , and .delete all return a promise. It means you can (and should) use the catch method to catch any errors. You don't need to use try-catch blocks, unless you want to use async/await instead of .then/catch .

Check the code below, I've added all the catch es. Check how it catches the error when the message doesn't exists (checking the err.httpStatus ), or when the message can't be deleted for any other reason.

channel.send(embed)
  .then((sentMessage) => {
    setTimeout(() => {
      channel.messages
        .fetch(sentMessage.id)
        .then((fetchedMessage) => {
          console.log('Message exists');

          fetchedMessage
            .delete()
            .then(() => console.log('Message deleted successfully'))
            .catch((err) => console.log('Could not delete the message', err));
        })
        .catch((err) => {
          if (err.httpStatus === 404) {
            console.log('Message already deleted');
          } else {
            console.log(err);
          }
        });
    }, 5000);
  });

so I have had a similar issue and I think my solution to it might be aplicable to your problem.

 function msgExists(channelID, messageID){


/*get channel*/
const channel = client.channels.cache.get(channelID); //(get channel)

/*get channel messages*/
channel.messages.fetch({ limit: 100 }).then(messages => {
    let count = 0;
    let max = (messages.length - 1);
    //Iterate through the messages.
    messages.forEach(message => {                                   
                                    
                                    if (messageID === message.id){
                                        console.log("message found");
                                    }
                                    if (count == (max)){
                                        console.log("message could not be found");
                                    }
                                    
                                    count++;
                                });
    

  });  

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM