Search code examples
javascriptnode.jsdiscord.js

Discord.js - Cannot get user or member by username from client object


In Discord.js, I am passing a client into the following:

async function get_remindmes(client) { 
  const outstanding_remindmes = await Remindmes.get_outstanding();
  for (let x of outstanding_remindmes) {
    let user = client.users.cache.find(y => String(y.username)+'#'+String(y.discriminator) === x.username);
  }
  return;
}

I can console.log the outstanding_remindmes array from within this function, and client.users.cache.find seems to work in other ways from within this function, but I can't seem to get user here to be anything other than undefined.


Solution

  • I assume the x variable is an object with a username and discriminator, but you're only using x.username to compare to y's username and discriminator. Should you be comparing the strings like this?

    let user = client.users.cache.find(y => (y.username + "#" + y.discriminator) === (x.username + "#" + x.discriminator))
    

    However, I'm not sure about the circumstances but it's much easier to compare users by using the user id (and it's better practice - users can change their names and even discriminators, but id will always be the same). Actually, if you have the user ids you can simply use the get function on client.users.cache, because the cache is a collection where the keys of all the elements are the user ids. For example:

    let user = client.users.cache.get(x.id);
    

    All you need to do is store the user ids in each of the entries of the outstanding_remindmes object.