0

I'm currently trying to fetch all messages in a guild, yet the .fetchMessages method only works on specific channels.

I've already tried using the .forEach function but have received multiple errors whilst doing so.

async function intervalFunc() {
  var mainGuild = client.guilds.get("562324876330008576");
  var messagesArray = [];
  await mainGuild.channels.forEach(channel => {
    if (channel.type == "text") {
      channel.fetchMessages({ limit: 20 }).then(msg => {
        messagesArray.push(msg);
      });
    }
  });
  console.log(messagesArray.length)
  //....
}

The expected output is at least a few hundred but instead, it outputs 0.

Federico Grandi
  • 6,785
  • 5
  • 30
  • 50
Caltrop
  • 895
  • 1
  • 7
  • 20

1 Answers1

1

You need to put await on the async operation:

async function intervalFunc() {
  var mainGuild = client.guilds.get("562324876330008576");
  var messagesArray = [];

  for(channel in mainGuild.channels) {
    if(channel.type == "text") {
      const messages = await channel.fetchMessages({limit: 20});
      messagesArray = [
        ...messagesArray,
        ...messages,
      ];      
    }
  }

  console.log(messagesArray.length);
}

So here it will wait for ferchMessages to return a value in an asynchronous manner and then proceed to next iteration.

Fawaz
  • 3,404
  • 3
  • 17
  • 22
  • Please note that by doing so `messagesArray` will contain collections only, not all the messages. If you want it to contain the messages you'll need to replace `messagesArray.push(msg)` with `messagesArray.push(...collection.array())` – Federico Grandi May 22 '19 at 14:56
  • @FedericoGrandi I agree the `messagesArray` will contain nested arrays/collections but we are not solving this problem here. The snippet above indicates the correct usage of `await` and storing the responses asynchronously. – Fawaz May 22 '19 at 21:54
  • @Fawaz The code after `forEach()` is called **before** `channel.fetchMessages()` returns anything. Therefore, `messagesArray` will be empty using this code - tested and confirmed. See [this explanation](https://stackoverflow.com/a/37576787). – slothiful May 22 '19 at 22:10
  • @slothiful I get your point, thanks for correcting me. I've updated my solution. – Fawaz May 23 '19 at 00:41