Search code examples
cachingdiscorddiscord.jsbotsfetching-strategy

How to fetch a message with the ID, without having it in cache


So I programmed a system that saves the ids of certain channels (plus messages) and saves them in a file. After restarting the bot, the IDs will be read and reused. For example, fetching the specific message to edit it, therefore. Unfortunately, the cache is undefined, empty or an error occurs. Could somebody show me how to fetch a message which isn't in the cache?

Example code for an existing message and channel:

const {Discord, Client, Intents, Permissions, MessageEmbed} = require('discord.js');
const bot = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MEMBERS, Intents.FLAGS.GUILD_MESSAGES, Intents.FLAGS.GUILD_MESSAGE_REACTIONS, Intents.FLAGS.GUILD_MESSAGE_TYPING, Intents.FLAGS.GUILD_PRESENCES, Intents.FLAGS.DIRECT_MESSAGES, Intents.FLAGS.DIRECT_MESSAGE_REACTIONS, Intents.FLAGS.DIRECT_MESSAGE_TYPING, Intents.FLAGS.GUILD_VOICE_STATES]});

bot.channels.cache.get('597102497420673025').messages.cache.get('959413368911966251').embeds;

Error:

var test = bot.channels.cache.get('597102497420673025').messages.cache.get('959413368911966251').embeds;
                                                                                                  ^

TypeError: Cannot read properties of undefined (reading 'embeds')
at Client.<anonymous> (D:\E-verysBot\index.js:2288:99)
    at Client.emit (node:events:402:35)
    at WebSocketManager.triggerClientReady (D:\E-verysBot\node_modules\discord.js\src\client\websocket\WebSocketManager.js:384:17)
    at WebSocketManager.checkShardsReady (D:\E-verysBot\node_modules\discord.js\src\client\websocket\WebSocketManager.js:367:10)
    at WebSocketShard.<anonymous> (D:\E-verysBot\node_modules\discord.js\src\client\websocket\WebSocketManager.js:189:14)
    at WebSocketShard.emit (node:events:390:28)
    at WebSocketShard.checkReady (D:\E-verysBot\node_modules\discord.js\src\client\websocket\WebSocketShard.js:475:12)
    at WebSocketShard.onPacket (D:\E-verysBot\node_modules\discord.js\src\client\websocket\WebSocketShard.js:447:16)
    at WebSocketShard.onMessage (D:\E-verysBot\node_modules\discord.js\src\client\websocket\WebSocketShard.js:301:10)
    at WebSocket.onMessage (D:\E-verysBot\node_modules\ws\lib\event-target.js:199:18)

Node.js v17.3.0

Solution

    • You fetch a message, to cache it.
    // asynchronously
    const channel = client.channels.cache.get(`channelId`);
    const message = await channel.messages.fetch(`messageId`);
    return message.embeds;
    
    // synchronously
    const channel = client.channels.cache.get(`channelId`);
    channel.messages.fetch(`messageId`).then(message => {
       return message.embeds;
    })
    

    I hope this fixes your problem!