How can I verify if a user has an admin role in my Discord bot?

I’m working on a Discord bot and I’m stuck on a permission issue. I want to create a command that only admins can use. But when I try to check if the user has the admin role, I get an error saying it can’t read the ‘roles’ property.

Here’s a similar code example I’m using:

if (msg.content.startsWith('!admincommand')) {
  const adminRoleId = '123456789';
  if (!msg.member || !msg.member.roles.cache.has(adminRoleId)) {
    msg.reply('Sorry, you need admin permissions to use this command.');
    console.log(`Unauthorized attempt by ${msg.author.username}`);
  } else {
    // Execute admin command
    const args = msg.content.split(' ').slice(1);
    const command = args.join(' ');
    console.log(`Admin command executed: ${command}`);
    // Process the command
    msg.delete();
  }
}

Can someone help me figure out what I’m doing wrong? I’m new to Discord.js and I’m not sure how to properly check for user roles. Thanks!

I’ve run into this issue before, and it can be a bit tricky. The problem might be that you’re trying to access roles in a DM channel, where roles don’t exist. To fix this, you should first check if the message is from a guild (server) channel.

Here’s how I solved it:

if (msg.content.startsWith('!admincommand')) {
  if (!msg.guild) {
    return msg.reply('This command can only be used in a server.');
  }

  const member = msg.guild.members.cache.get(msg.author.id);
  if (!member.permissions.has('ADMINISTRATOR')) {
    return msg.reply('You need admin permissions for this command.');
  }

  // Execute admin command here
}

This approach uses the ‘ADMINISTRATOR’ permission flag instead of checking for a specific role. It’s more reliable and covers all cases where a user might have admin rights. Hope this helps!

yo, i had similar probs. try using msg.member.permissions.has(‘ADMINISTRATOR’) instead of checking roles. it’s way easier and covers all admin types. also, make sure ur bot has the right perms in the server settings or it might not work right

I’ve encountered this issue in my Discord bot development as well. Instead of checking for a specific role, it’s more reliable to use the built-in permission system. Here’s a concise approach that worked for me:

if (msg.content.startsWith('!admincommand')) {
  if (!msg.guild) return msg.reply('Server-only command.');
  if (!msg.member.permissions.has('ADMINISTRATOR')) {
    return msg.reply('Admin permissions required.');
  }
  // Admin command logic here
}

This method is more robust as it checks for the ‘ADMINISTRATOR’ permission directly, covering all cases where a user might have admin rights, regardless of their specific roles. It also includes a check to ensure the command is used in a server context. Remember to handle errors appropriately and ensure your bot has the necessary permissions in the server settings.