BULLETBOT
BULLETBOT

Reputation: 51

Is there any possible way to notice if the user exists or not? | Discord.js

I want to check that the user is mentionable or not. If it's a text, i'm getting a error called TypeError: Cannot read property 'username' of undefined

I think it's understandable, that's what I said. Here is my code.

const taggedUser = message.mentions.users.first();
...


if(command == "avatar") {
  let member = message.mentions.members.first();
  if(!args.length){ 
    message.channel.send(`Your Avatar: <${message.author.displayAvatarURL({ format: "png", dynamic: true })}>`);
    }
    else if(args[0]) {
      message.channel.send("This"+ "`" + taggedUser.username + "`" + "'s avatar: " +  `<${taggedUser.displayAvatarURL({ format: "png", dynamic: true })}>`);
    }
    else if(args[0] == member.user.bot || args[0] == member.kickable){
      message.channel.send("Type a mentionable user, not a text.");
    }
 }

Upvotes: 1

Views: 1128

Answers (1)

Dylan Kerler
Dylan Kerler

Reputation: 2187

You can check if a user exists like this:

if (taggedUser !== undefined) /* then the user exists */

you can also do:

taggedUser ? taggedUser.username : "No user exists";

or with optional chaining

taggedUser?.username // returns undefined if taggedUser doesn't exist

Example:

else if(args[0]) {
  taggedUser ? // if tagged is  truthy then run this first bit
      message.channel.send("This"+ "`" + taggedUser.username + "`" + "'s avatar: " +  `<${taggedUser.displayAvatarURL({ format: "png", dynamic: true })}>`);
    :
      message.channel.send("No User") // if tagged is falsey
}

Javascript contains what is known as truthy and falsey values - This means that types implicitly cast to true or false and you can do conditional checks on types. for example if ([1,2,3]) { /* runs */ } because arrays are truthy. Read more here: https://developer.mozilla.org/en-US/docs/Glossary/Truthy

The above ternary operator works like this

condition ? 
   /* if condition is truthy run this */ 
: 
   /* if condition is falsey run this */

Upvotes: 1

Related Questions