0

I am trying to build my first discord bot, I have a bit of experience with javascript but am struggling at a certain part.

I want to loop through every user with a certain role, check if this user is online, then tag this user, get this users last message in a certain channel & display this users roles.

This all works fine, except that it never shows the users last message. This is my code:

client.on('message', async (message) => {
  const command = message.content.slice(prefix.length).toLowerCase();

  if (command === 'zoek') {
    var members = '';
    // loop through every user with specific role
    message.guild.roles.cache.get('872892610950357063').members.forEach(async (member) => {
      if (member.user.presence.status !== 'offline' && message.author.id !== member.user.id) {
        //add user to the members variable
        members = members+"<@" + member.user.id + "> | ";

        // get last message of this user in specific channel and add to members variable, this is where the problem is
        const channel = client.channels.cache.get("871779594229919825");
        channel.messages.fetch().then(messages => {
          for (const msg of messages.array()) {
            if (msg.author.id === member.user.id) {
              members = members+msg.content+" | ";
              break;
            }
          }
        }).catch(console.error);

        // get roles of member and add to members variable (works perfectly)
        members = getroles(member, members);
      }
    });

    if (members === '') {
      members = 'Geen spelers gevonden';
    }
    message.channel.send(members);
  }
}); 

I am aware that I need to make use of async & await, the code doesn't wait for the second loop to be ready, where it loops through messages and it never returns a message.

I read many documentations, but after struggling for 2 hours I can't make it seem to work..

Can anyone help me out, thanks in advance!

Mark
  • 31
  • 1
  • 6
  • Replace the `.forEach()` call with a loop, and replace the `.then()` call with `await` syntax. If you continue to struggle, please [edit] your question to show us your attempt. – Bergi Aug 05 '21 at 22:49

0 Answers0