According to the Message#fetch()
docs, this function simply fetches the message it was called on. However, I’m not sure in which circumstance it would ever make sense to use this function.
According to the screenshot above, this method returns Promise<Message>
. I’m confused, because why would you need to fetch a message you already have access to? For example:
// let's say somebody sent the message `hello` client.on('message', (message) => { console.log(message.content) // this would return `hello` message.fetch((message) => console.log(message.content)) // this would also return `hello`; it's the same object
So, what’s the point of it? If you didn’t have access to the message, you wouldn’t be able to use Message.fetch()
anyways.
And I’d ask the same question for Channel#fetch
, ClientUser#fetch
, Guild#fetch
, GuildMember#fetch
, GuildPreview#fetch
, etc.
Advertisement
Answer
If we dive into the source of the Message
class and look for the fetch
method, we see something like this:
/** * Fetch this message. * @param {boolean} [force=false] Whether to skip the cache check and request the API * @returns {Promise<Message>} */ fetch(force = false) { return this.channel.messages.fetch(this.id, true, force); }
The fetch()
method in this cases, retreives the last message posted in the channel. If you invoke this method and log the output, you see that it fetches the message you have posted. It simply returns asynchronous message object. Promise<Message>
.
So let’s say you post this message Hello, i'm a message.
and invoke and log the .fetch()
method, you see in the console the message object and content Hello, i'm a message.
. All this does is fetching the message posted in the channel. Same goes for channel#fetch
, ClientUser#fetch
.
All it does is using the cache to fetch a channel, user, guild, message. The force
argument is to receive the realtime data.
The force
flag is used if you want to skip the cached message and want to do the API request.
If you wish to fetch all messages or a few messages, you can use the MessageManager
class:
message.channel.messages.fetch('Message ID');
or
message.channel.messages.fetch({ limit: 5, // Amount of messages to be fetched in the channel before: "Snowflake (ID from message to be fetched)", after: "Snowflake (ID from message to be fetched)", });
More on this: https://discord.js.org/#/docs/main/stable/typedef/ChannelLogsQueryOptions