Ralfotr
Ralfotr

Reputation: 45

How to get user ID from Discord username?

I'm doing a little project where I take values from a Google sheet with form responses and DM them to specific users. I've already retrieved the user tag (User#0000) from the sheet and have stored it in tag.value.

When filling out the form, the user checks a box that they are in the server, therefore I'm trying to find the user via my server.

This is the code I've already made but it outputs an error that guild.members is undefined:

const guild = client.guilds.fetch('705686666043457606')
const applicant = guild.members.find((member) => member.name == tag.value);

UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'find' of undefined

Upvotes: 1

Views: 1414

Answers (2)

Zsolt Meszaros
Zsolt Meszaros

Reputation: 23141

In your example guild.members is undefined because .fetch() returns a promise and the returned guild doesn't have a member property.

You either need to use the .then method, to access the fetched guild:

client.guilds.fetch('705686666043457606')
  .then(guild => {
    const applicant = guild.members.cache
      .find((member) => member.user.tag === tag.value)
  })
  .catch(console.error)

...or use async/await:

async yourFunction() {
  try {
    const guild = await client.guilds.fetch('705686666043457606')
    const applicant = guild.members.cache
      .find((member) => member.user.tag === tag.value)
  } catch(err) {
    console.error(err)
  }
}

Please note that you can only use await in async functions, so make sure to convert the function where your code is by adding the async keyword.

Also, make sure you use the user tag not the username. Find the member by comparing member.user.tag in the .find() method, and not member.name.

Upvotes: 1

Pentium1080Ti
Pentium1080Ti

Reputation: 1056

In discord.js v12 members is a GuildMemberManager which means you have to use the cache first.

For example:

const guild = client.guilds.fetch('705686666043457606');
const applicant = guild.members.cache.find((member) => member.name == tag.value);

.find() can be called on a collection, which is what the cache is in the GuildMemberManager (i.e. guild). You can find more methods for a collection here. You could also use the GuildManagerMember#fetch method available in v12.

Upvotes: 0

Related Questions