Cannot get the id of a username Discord JS

JustABotTryingToCode
let string = `${args[1]} ${args[2]}`
console.log(string)
const idofuser =  client.users.cache.find((u) => u.username === `${string}`).id

My friends Discord Name is Like "Avex Sports" and DiscordJS says: cannot read property "id" of undefined, i would appricate any help

Worthy Alpaca

Lets start with the string. What you did here works but only if the name you want to find has two words. If you want to use a name with more or less words then this will not work. So we can .slice(1) here assuming that the name really starts at the second argument.

let string = args.slice(1).join(" ");

Next we try to find the user object. Here you should use a .toLowerCase() on both sides of === to make sure that you don't run into capitalization problems.

let user = client.users.cache.find(u => u.username.toLowerCase() === string.toLowerCase());

Lastly we check if the user actually exists because, as said in the comments, you can never assume that something exists. If the user does not exist we return here and send a message that replies to the author.

if (!user) {
  return message.reply("That user doesn't exist!");
}
// The rest of your code

If the user does exist then you just continue with whatever you want to do here.

See here https://discordjs.guide/ for more information.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related