Home > Blockchain >  Check if the message sender has a specific role
Check if the message sender has a specific role

Time:03-12

I'm new in Discord bot coding and I want to create a command where the bot only replies if the message sender has a specific role.

According to the discord.js documentation I have to use GuildMemberRoleManager.cache. Sadly, it isn't working.

The whole command looks like this:

client.on('messageCreate', (message) => {
  if (
    message.content.toLowerCase() === prefix   'test' &&
    GuildMemberRoleManager.cache.has(AdminRole)
  )
    message.reply('test');
});

CodePudding user response:

You should get the author's roles. Only members have roles, so you will need to get the author as a member using message.member. message.member returns a GuildMember and GuildMembers have a roles property that returns a GuildMemberRoleManager (the one you mentioned in your original post).

Its cache property is a collection of the roles of this member, so you can use its has() method to check if the user has the admin role:

client.on('messageCreate', (message) => {
  let adminRole = 'ADMIN_ROLE';
  let isAdmin = message.member.roles.cache.has(adminRole);

  if (message.content.toLowerCase() === prefix   'test' && isAdmin)
    message.reply('test');
});

CodePudding user response:

Define the variables which will make you easy to understand as you are new

const guild = message.guild.id;
const role = guild.roles.cache.get("role id");
const cmduser = message.author;
const member = await guild.members.fetch(cmduser.id);

and make if statement like

if(member.roles.cache.has(role.id)) {
      return message.channel.send("test")
    }

if you want bot to check if user have administrator perm than

message.member.hasPermission('ADMINISTRATOR')

Check all perm flags on Discord Perm Flags

So according to your code it will be

const guild = message.guild.id;
const role = guild.roles.cache.get("role id");
const cmduser = message.author;
const member = await guild.members.fetch(cmduser.id);

client.on("messageCreate",(message) => {
    if(message.content.toLowerCase() === prefix   "test" && member.roles.cache.has(role.id))
        message.reply("test")
})
  • Related