Reputation: 69
Can someone help? I wanted my commands to be able to be used with @olios or 49556804 *** 0471817. I don't know what I'm doing wrong but my code isn't working.
let userLevel = mentions.users.first () || msg.guild.members.cache.get (args [0]) || msg.author
const userLevelID = userLevel.id
const userLevelName = userLevel.user.username
And I get something like this from the console:
TypeError: Cannot read property 'username' of undefined
Can it be done at all, or it worked on mentions and ID?
Upvotes: 0
Views: 50
Reputation: 23161
While both msg.mentions.users.first()
and msg.author
return a User
, msg.guild.members.cache.get(args[0])
returns a GuildMember
. Both User and GuildMember have an id
property, but only GuildMember
has a user
.
If you try to get the user
from a GuildMember
, you will be fine, but you will always receive a TypeError if you try to get it from a User
.
You can update your code to get the user
from message.guild.members.cache.get(args[0])
only. I used optional chaining (?
) to ignore it if there is no args[0]
and fall back to msg.author
.
The following will work with all three cases:
let userLevel =
msg.mentions.users.first() ||
msg.guild.members.cache.get(args[0])?.user ||
msg.author;
const userLevelID = userLevel.id;
const userLevelName = userLevel.username;
console.log({ userLevelID, userLevelName });
Optional chaining requires Node.js v14+. If you have an older version you can use a simple AND operator:
let userLevel =
message.mentions.users.first() ||
(message.guild.members.cache.get(args[0]) &&
message.guild.members.cache.get(args[0]).user) ||
message.author;
Upvotes: 2