1
votes

So, the title briefly explains what I want.

When a member joins my Discord server, I want the bot to assign them the User role automatically. Before that happens, I want to verify if the bot has permission to manage roles and so far I have the following in my code.

 /** Event will trigger when a user joins the server **/
 bot.on("guildMemberAdd", function(member) {
  if (!bot.user.hasPermission("MANAGE_ROLES")) {
    var embed2 = new discord.RichEmbed()
     .setTitle("Error")
     .setDescription("The bot doesn't have the appropriate permissions to assign new members roles automatically.\nTo resolve this problem, go to **Server Settings** and then navigate to the **Roles** option. Next, click on **Bots**, and then click on the slider next to **Manage Roles** to activate it.")
     .setColor("#3937a5")
    bot.channels.get("466878539980079105").send(embed2);
 } else {
  member.addRole(member.guild.roles.find("name", "User"));
 }
});

If the bot doesn't have the permissions, it will get the attention of staff by posting an alert to the #alert channel.

However, I attempt to join with a new Discord account, it reports in the console that hasPermission isn't a function, and then stops.

Would there be any suggestions on how to resolve this code?

2
where did you find the hasPermission method? I can't find it in the docs. so it's correct that hasPermission is not a function - Philipp Sander

2 Answers

2
votes

On Discord.js we have users and members. Users is a user of Discord. Member is a member of a Discord Server. The user object doesn't have information about roles, nicknames, permissions. Members do, because they are related to that server.
So if you want to grab the bot as the member of the guild you need to use something like this:

<guild>.me

This will return the member object of the bot from the selected guild.
When a member is added to the guild you get the GuildMember object, and with that you also get the guild. So you can use this:

member.guild.me

And finally to check the bot has permissions:

if(member.guild.me.hasPermission("MANAGE_ROLES"))

Note:

hasPermission() and hasPermissions() will be deprecated in DiscordJS v13 and replaced with permissions.has()

e.g : member.permissions.has(Permissions.FLAGS.SEND_MESSAGES);

2
votes

the error message is correct, user has no function called hasPermission. but the role property does.

https://discord.js.org/#/docs/main/stable/class/Role?scrollTo=hasPermission