Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Discord.js get an array of all messages in a channel

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)

like image 433
Jared Cohen Avatar asked Aug 09 '20 03:08

Jared Cohen


1 Answers

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))
})
like image 53
Dorian349 Avatar answered Sep 18 '22 08:09

Dorian349