discord js check if message author is admin

hljs.highlightAll();

How to check if message author is admin in Discord Js

If you are building a Discord bot using Discord Js, you might need to check if the message author is an admin. This can be useful if you want to restrict certain commands or actions to only users with admin privileges.

Method 1: Using message.member.hasPermission()

The first method to check if the message author is an admin is to use the message.member.hasPermission() function. This function checks if the member (user) who sent the message has a certain permission. We can use the "ADMINISTRATOR" permission to check if the user is an admin.


if (message.member.hasPermission("ADMINISTRATOR")) {
    // User has admin privileges
} else {
    // User does not have admin privileges
}
        

In the above code, we are checking if the member who sent the message has the "ADMINISTRATOR" permission. If they do, we can execute the code inside the if statement, which indicates that the user has admin privileges. If they do not have the permission, we can execute the code inside the else statement.

Method 2: Using message.member.roles.cache

The second method to check if the message author is an admin is to use the message.member.roles.cache property. This property returns a collection of roles that the member has.


const adminRole = message.guild.roles.cache.find(role => role.name === "Admin");

if (message.member.roles.cache.has(adminRole.id)) {
    // User has admin role
} else {
    // User does not have admin role
}
        

In the above code, we are first finding the "Admin" role in the guild using message.guild.roles.cache.find(). We then check if the member who sent the message has this role using message.member.roles.cache.has(). If they do, we can execute the code inside the if statement, which indicates that the user has admin privileges. If they do not have the role, we can execute the code inside the else statement.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe