I\'m building a Discord bot and I want to have an if
statement that will only proceed if the message author has an administrator role in the guild.
I\'v
These answers seem outdated:
Use: msg.member.roles.cache.has(roleID)
On the GuildMember object, you have a hasPermission function available.
So you can just do member.hasPermission('ADMINISTRATOR')
If you are interested in all the other strings, that are permission resolvable, you can find them in the discord.js docs.
Some of the following code must be modified to use in the newest major Discord.js version (v12 at the time of this edit) due to the implementation of Managers.
There's really three different questions needed to be addressed here. They're all related, but each have different direct answers.
How do I check if the message author has an Admin role?
The GuildMember that sent a message is accessed via the Message#member property, as opposed to Message#author which returns a User. Remember, a member has roles and permissions, not a user.
A Collection of a member's roles can be retrieved with GuildMember#roles.
You can search for a role two main ways:
So, tying this all together:
if (message.member.roles.has'roleIDHere')) console.log('User is an admin.');
or
if (message.member.roles.find(role => role.name === 'Admin')) console.log('User is an admin.');
How do I check if the message author's role has the Administrator permission?
Message#member
.GuildMember#roles
collection.Collection#find()
.For example:
if (message.member.roles.find(role => role.hasPermission('Administrator'))) console.log('User is an admin.');
You can apply this concept to any specific role, too.
Best method for this situation...
How do I check if the message author has the Administrator permission?
Message#member
to access the GuildMember.Consider this short example:
if (message.member.hasPermission('ADMINISTRATOR')) console.log('User is an admin.');
Quick, right?
Make sure you check that the message your client receives is not a DM before attempting to check if the user is an Admin. Message#member
is undefined when the message isn't sent in a guild, and trying to use properties of it will throw an error.
Use this condition, which will stop if the message is a DM:
if (!message.guild) return;