Reputation: 403
I am coding a Discord bot in which I want to do the command !quote
and it will pull a random message of of out of a specific channel with id quotesID
(that may or may not be a different channel that !quote
was sent in). I keep looking through the documentation for Discord.js but I can't find a way to get a TextChannel by its ID and then use a TextChannels .messages
function and thus get the MessageManager and then a collection of the messages.
I know I can get the guild using msg.guild
(where msg
is the trigger with !quote
) or get the tex
I am new to JavaScript and Discord.js so any info helps. (I am using Discord.js version 12.2.0)
Upvotes: 18
Views: 39044
Reputation: 745
According to your title, you want all
messages in a channel. Not just 100 of them. Since there is a max on the number of messages you can fetch per request, we will have to use the before
option to perform pagination to fetch all messages.
async function fetchAllMessages() {
const channel = client.channels.cache.get("<my-channel-id>");
let messages = [];
// Create message pointer
let message = await channel.messages
.fetch({ limit: 1 })
.then(messagePage => (messagePage.size === 1 ? messagePage.at(0) : null));
while (message) {
await channel.messages
.fetch({ limit: 100, before: message.id })
.then(messagePage => {
messagePage.forEach(msg => messages.push(msg));
// Update our message pointer to be the last message on the page of messages
message = 0 < messagePage.size ? messagePage.at(messagePage.size - 1) : null;
});
}
console.log(messages); // Print all messages
}
Upvotes: 19
Reputation: 101
As it is said in https://discord.js.org/#/docs/collection/master/class/Collection?scrollTo=array you can use the method <Collection>.array()
to get an array of the values in the Collection. It is like [...Collection.values()]
or Array.from(Collection.values())
.
Upvotes: 0
Reputation: 1589
If you want to get a specific channel with an id, you need to do:
const channel = client.channels.cache.get("Your channel ID");
Then, to collect messages in this channel (limit is set to 100 messages max, so you can't collect more than 100 messages in this channel except if you do your own messages storing system).
channel.messages.fetch({ limit: 100 }).then(messages => {
console.log(`Received ${messages.size} messages`);
//Iterate through the messages here with the variable "messages".
messages.forEach(message => console.log(message.content))
})
Upvotes: 34