Apollo24
Apollo24

Reputation: 95

Discord.js how to check if user has a role on a specific server

I'm trying to check if the user has a role on a specific server regardless on which server they use the bot.

For example, if I have 2 servers, server A and server B, I want to check if the user has the role "Beginner" on server A, even if I use the command in server B.

I couldn't find a way to do this on the internet, message.member.roles seems to only return the roles of the server the command was written in.

Upvotes: 0

Views: 668

Answers (2)

Tyler2P
Tyler2P

Reputation: 2370

A solution is to find the server then find the member from inside the server.
To find the guild you will use the guild.fetch(...) method and from there you then use the guildMember.fetch(...) function to find the member.

Example:

client.on("messageCreate", function(message) {
    // Find the guild
    let guild = client.guilds.fetch("guild-id");
    // Find the member in the guild
    let member = guild.members.fetch(message.author.id);

    if (member)
        message.reply("You are in the server " + guild.name);
});

Upvotes: 0

Visne
Visne

Reputation: 433

You can do it like this:

function hasRole(guildId, roleId) {
    // Get second guild
    const guild = client.guilds.cache.get(guildId);

    // Get member in that guild, by ID
    const member = guild.members.cache.get(message.author.id);

    // If member is in that guild,
    if (member) {
        // return whether they have this role
        return member.roles.cache.has(roleId);
    }
}

Of course the bot has to be in both servers.

Upvotes: 1

Related Questions