0

So, I'm creating a command in which I need to send a specific message when the user pinged in the command has a certain role. The only thing I could come up with was this:

if(message.mentions.users.first().roles.cache.some(r => r.name === "Admin" || "Mod")) {
            message.channel.send('This user has a role!')  
        }

I'm stuck in place and can't find a way to deal with it. The answer is probably obvious but with my JavaScript skills, I'm getting more and more frustrated with every change I make.

Also, this is the error that I get: "TypeError: Cannot read property 'cache' of undefined"

Galgan
  • 1
  • 1
  • 1
    `message.mentions.users.first().roles` is `undefined` (hence the `cache` property cannot be read) so I'd suggest starting there to find out why. – Matt U May 27 '21 at 20:34

2 Answers2

1

Your mention accesses a User object, which is a global Discord User Representation. You want the Member object - which is a per server user representation - instead.

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

// Use Array#includes for cleaner syntax
if (mentionedMember.roles.cache.some(role => ["Admin", "Mod"].includes(role.name)) {
   message.channel.send('This member has a role!')  
}

Refer to This Answer for more information on User vs Member

Elitezen
  • 6,551
  • 6
  • 15
  • 29
0

You can't use || operator on literals like that, only on booleans.

if(message.mentions.users.first().roles.cache.some(r => r.name === "Admin" || r.name === "Mod")) {
        message.channel.send('This user has a role!')  
}

What actually happens in r.name === "Admin" || "Mod" is that r.name === "Admin" evaluates first to true or false depending on r.name value. Then in true || "Mod" or false || "Mod" "Mod" string is cast to a boolean (true for non-empty strings) so you get true || true or false || true which always evaluates to true.

Samuel Olekšák
  • 389
  • 4
  • 12
  • That's not the problem here. I want to check if the user has at leas one of the mentioned roles. Also, the problem is with ```message.mentions.users.first().roles.cache.some``` not ```r => r.name === "Admin" || "Mod"```. The exact error says "Cannot read property 'cache' of undefined" – Galgan May 27 '21 at 20:08
  • Ah, you could have mentioned the error inside the question; nevertheless you'll have to fix this one ^^^ too to make it work. – Samuel Olekšák May 27 '21 at 20:10
  • I used my version inside a different command and it works perfectly, so I don't think I need to change it :) – Galgan May 27 '21 at 20:18
  • I think your intension is to evaluate condition to true only if the user has Admin or Mod role. This condition `r => r.name === "Admin" || "Mod"` will evaluate to true always, even if user isn't Admin nor Mod. – Samuel Olekšák May 27 '21 at 20:26
  • User's do not have roles, members do – Elitezen May 27 '21 at 20:35