简体   繁体   中英

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

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 .

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 (ie guild ). You can find more methods for a collection here . You could also use the GuildManagerMember#fetch method available in v12.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM