0
votes

Hey I'm currently working on something that you can do ,user and it will show user info about that user.

if(args.length < 1) {
        var user = message.author;
    } else {
        var user = client.users.cache.get(args[0]);
    }

    if(!user || user == undefined) return message.channel.send("**Error:** An error occurred!");

But "user" is always undefined and I don't know why

3
what do you mean by args[0]. is it a pinged object or id of a user?Barış Çiçek
I think in the else part you want to find a mentioned user. For that, you have to use message.mentions.user.first.Rak Laptudirm

3 Answers

0
votes

I assume that you would mention someone in that command. The reason this doesn't work is because client.users.cache.get doesn't take mentions, it only takes memberIDs.

What you should do instead is get the mention from the message. You do that by accessing the MessageMentions class.

message.mentions.members.first();

If you want/need to use IDs then your code will work. If you wish to use names you need to use the find() method.

client.users.cache.find(u => u.username === args.join(' '));

Note: We join(' ') the args here to use it with multi-word names. Also note that the names only work if they are spelled correctly, meaning capitalization is important.

0
votes

I believe you should have been using message.guild.members.cache instead of client.users.cache. I've used the question mark operator here, this is how you use it:

condition ? value_if_condition_is_true : value_if_condition_is_false

I've also removed user == undefined as it does the exact same thing as !user

const memberMention = message.mentions.members.first();

var user = args[0] ? message.guild.members.cache.get(args[0]) : memberMention ? memberMention : message.author;

if (!user) return message.channel.send("**Error:** An error occurred!");
0
votes

The reason user is always undefined because you are calling it out of scope.

if(args.length < 1) {
        var user = message.author; // the user variable is only valid in this "if" block
    } else {
        var user = client.users.cache.get(args[0]); // the user variable is only valid in this "else" block
    }

    if(!user || user == undefined) return message.channel.send("**Error:** An error occurred!");

Instead, you should include your code in the main if-else block or declare the user variable global by not using a variable declaration keyword.

if(args.length < 1) {
        user = message.author; // the user variable is only valid in this "if" block
    } else {
        user = client.users.cache.get(args[0]); // the user variable is only valid in this "else" block
    }

    if(!user) return message.channel.send("**Error:** An error occurred!");
    console.log(user.tag)
    //further code here...

I've also cleaned up some redundancies for you: if(!user) will cover undefined as well, so no need to include || user == undefined