Search code examples
javascriptif-statementdiscorddiscord.js

Checking if someone has a role in DiscordJS is not working


I have a embed with buttons and I want to check if someone has a role.

case "lock":
    if(!guild.members.me.roles.cache.some((r) => r.id === docs.Handlers))
        return interaction.reply({content: "You don't have the permissions for that", ephemeral: true});

    if(data.Locked == true)
        return interaction.reply({content: "Ticket is already locked.", ephemeral: true});
                    
    await ticketSchema.updateOne({ChannelID: channel.id}, {Locked: true});
    embed.setDescription("The ticket has been locked successfully!");

    data.MembersID.forEach((m) => {
        channel.permissionOverwrites.edit(m, {SendMessages: false});
    });

    return interaction.reply({embeds: [embed]});

The first IF is what bothers me.

Here is the "docs" variable.

const docs = await TicketSetup.findOne({GuildID: guild.id});

And the TicketSetup part: Handlers: String,

I have a separate command that is used to set the Handlers as a role in the server.

.addRoleOption(option =>
    option.setName("handlers")
    .setDescription("Select the ticket handlers role.")
    .setRequired(true)
)
......
const handlers = options.getRole("handlers");
......
Handlers: handlers.id,

I want to make that if someone doesn't have a docs.Handlers role it says "You don't have a perm...", but if someone does have it, it should work for him. I'm guessing that I'm not using the if statement correctly but I can't fix it.


Solution

  • As per the discord.js docs, guild.members.me is:

    The client user as a GuildMember of this guild

    This means that you're checking your bot's own permisisons instead of the user's.

    In order to check the user's permissions, you'll want to use interaction.member:

    if(!interaction.member.roles.cache.some((r) => r.id === docs.Handlers))
    

    If this fails, the member might not be in cache, and you'll need to fetch it first.

    Aditionally, as @Jiralite mentioned in the comments, you can use .has(), which will do the same thing as .some((r) => r.id === docs.Handlers):

    if(!interaction.member.roles.cache.has(docs.Handlers))