How to find member by username?

Issue

Discord.js 13.6.0 | Node.js 16.14.2

I want to find member by username, same as in bot UnbelievaBoat (https://i.stack.imgur.com/WNPv5.png)

Example: username is WorldGod

Type e.g. ?userinfo worl or ?userinfo WORLD and bot find member WorldGod

Code example:

const arg = args[0] or const arg = args.join(" ")

let member = message.guild.members.cache.filter(member => member.user.username.includes(arg))[0]

message.reply(`${member.id}`) or message.reply(`${member.user.id}`)

TypeError: Cannot read properties of undefined (reading ‘id’)

TypeError: Cannot read properties of undefined (reading ‘user’)

Solution

the .includes() function returns a boolean so what you want to do is create a function based on that boolean.
this is the new code i made for you.

// make members an array
let members = []
message.guild.members.cache.filter(mems => {
  // if users username includes the arg
  mems.user.username.includes(arg) ? 
  members.push(mems.user) // if so it pushes user into array 
  : null // else null
})

// this will send the user's name and id
message.reply(`${members[0].username} ${members[0].id}`)

this creates an array for members, then filters users of the guild and if the username includes the argument it will add the user to the array.

After it pushes the user you can access that user however you want… you can get its avatarURL, tag, id, username, etc…

If you want to eventually make it so you list all the options this will work fine because they will all be in the members array, and very easy to map.

hope this helped 😉

Answered By – gavin

Answer Checked By – Senaida (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.