简体   繁体   中英

Verify the existence of a message by its ID

I would like to verify the existence of a message by its ID.

The code here works, but if the message doesn't exist, it doesn't tell me "undefined".

let channel = bot.channels.cache.get("846857716290813962");
const message = channel.messages.fetch("847383565220970497");

UnhandledPromiseRejectionWarning: DiscordAPIError: Unknown Message

You can just handle the errors that come in a try/catch block.

The following function should check if a message exists by ID, and if there are any errors, it will catch the error, console.log() it, and return false.

const checkIfMessageExists = async (channelId, messageId) => {
    try {
        let channel = bot.channels.cache.get(channelId);
        const message = await channel.messages.fetch(messageId);
        if (message) return true;
    } catch(error) {
        console.log(error.message)
    }
    return false;
}

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