Checking if my bot has permissions to manage roles - javascript

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?

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);

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

Related

member.roles.add is not a function

I don't know why but I get this error in the console when someone joins the server and doesn't want to give it a role
Error:
TypeError: member.roles.add is not a function
let roleID = "1005089670629175439";
client.on("guildMemberAdd", (member, roleID) => {
member.roles.add(roleID);
console.log("Mistic BOT | Added role for new user");
});
First check if you enabled privileged intents on discord developer portal.
This is how you do it
Make sure you're logged on to the Discord website.
Navigate to the application page.
Click on the bot you want to enable privileged intents for.
Navigate to the bot tab on the left side of the screen.
Scroll down to the “Privileged Gateway Intents” section and enable server members intent.
On your code you don't need to pass the roleID if its in the same file just simply use something like this
client.on("guildMemberAdd", (member) => {
let roleID = "1005089670629175439";
member.roles.add(roleID);
console.log("Mistic BOT | Added role
for new user");
});

Self Permission Check

How do I check if the bot (Self) has permissions to send messages and make it an if statement? Im using discord js and I've seen forums like member.roles.cache has, but none cover the bot itself, so how do I check that?
As Elitezen said, you can get GuildMember object using Guild#me but to check if your bot can send messages for example in guild where the command was executed you have to use this:
if(message.guild.me.permissions.has("SEND_MESSAGES")) { // check if bot has SEND_MESSAGES permission
// your code
}
You can use Guild#me to get the client's GuildMember object in that guild.
// guild = message.guild or any guild object
if (guild.me.roles.cache.has(...)) {
}
Update: in Discord.JS V14 you now have to use guild.members.me

Issue with Discord.js avatarURL

.avatarURL for discord.js is not displaying any image.
I'm trying to make a command for my discord bot that lets someone ping another and have the bot display their profile picture. I quickly homed in on .avatarURL being the solution for this, but it doesn't seem to be displaying any image at all. Any help would be appreciated.
if (message.content.startsWith(`${prefix}showpfp`)) {
let embed = new Discord.RichEmbed().setTitle(tMember.displayName + "'s Profile Picture").setImage(tMember.avatarURL).setColor('#add8e6')
message.channel.send(embed);
}
after typing in command _showpfp #user the bot will respond with
user's Profile Picture
and thats it...
The issue is that tMember doesn't have a property avatarURL. In your comment you say that you get the value of tMember by doing message.mentions.members.first(), however message.mentions.members is a collection of GuildMembers. A GuildMember doesn't have a property avatarURL.
However, the class User does have the property avatarURL. Therefor you need to fetch the member as an instance of User first. Luckily for you, the class GuildMember has a property .user which does just that.
So the fix for your problem is to change the parameter of the setImage to tMember.user.avatarURL, as can be seen below.
if (message.content.startsWith(`${prefix}showpfp`)) {
let embed = new Discord.RichEmbed().setTitle(tMember.displayName + "'s Profile Picture").setImage(tMember.user.avatarURL).setColor('#add8e6')
message.channel.send(embed);
}

How to make a bot find a channel owner / compare to the author's ID

I'm making a bot where if you do d!move, the bot will move the channel where the message was sent in under a category via ID. I also want to make it so that whoever does the command has permissions such as MANAGE_CHANNELS, which I've already added. The problem is that when I want to confirm whoever created that channel is the person that activated the command, the bot says yes. I did this on an alt account, where I made the channel and my alt was the one initializing it, and the bot said "success!" I also wanted to make it so if someone else made the channel, and when I did it, it would work because I made the bot know my ID.
I've researched Google and found nothing.
I've tried using a function with fetchAuditlog but get anywhere.
if(!message.channel.client.user.id == message.author || !message.author.id == `329023088517971969`) return message.channel.send("You don't own this channel!")
else message.channel.send("success!");
message.channel.setParent(`576976244575305759`);
I expect the bot to be able to check if the author created the channel, and lead to You don't own this channel if they don't own it. But if they do then the bot moves the channel.
The actual result is the bot moving the channel anyway regardless if they own the channel or not.
As #André has pointed out, channel.client represents the client itself, not the user who created the channel. Also, the last line in your code is not part of the else statement, so that's why it's run regardless of the conditions you defined.
To reach a solution, you can make use of the guild's audit logs. You can search for entries where the user is the message author and a channel was created. Then, all you have left is to check if one of those entries is for the current channel, and run the rest of your code if so.
Sample:
message.guild.fetchAuditLogs({
user: message.author,
type: 'CHANNEL_CREATE'
}).then(logs => {
if (!logs.entries.find(e => e.target && e.target.id === message.channel.id)) return message.channel.send('You don\'t own this channel.');
else {
// rest of code
}
}).catch(err => console.error(err));
When you go <anything>.client.user it will return the bot client.
If you want to see who created the channel you would have to check the Audit Logs or save it internally.
I've checked the documents. Here's what it says for .client about the
channel. It says the person that initialized the channel, or the
person that created it.
On documentation I see this:
The client that instantiated the Channel
instantiated is different of initialized

Discord.js client.addMemberToRole not working

So, I'm programming a Discord bot, and one of the things I want it to do is to assign roles to members given certain conditions. After looking through the documentation, specifically here, I figured bot.addMemberToRole would be a good command to use. However, when I ran it, I got this error message:
TypeError: bot.addMemberToRole is not a function
I was understandably confused, as the documentation clearly says that this IS a function. I have tried doing bot.addMemberToRole(member, role);, addMemberToRole(member, role);, and several other iterations. This is my most recent attempt:
const Discord = require('discord.js');
const bot = new Discord.Client();
bot.addMemberToRole(member, role, function(err){
if(err){
console.log(err);
}
});
I have also done just this:
bot.addMemberToRole(member, role);
Both gave the same TypeError as above.
I have no idea why it doesn't work. I followed the documentation exactly, the member and role variables I pass into it are the proper type, and other Discord.js commands work just fine in my bot. Any help would be appreciated.
You're using an old version of the docs so that function doesn't exist anymore. They should really get rid of those. You're looking for GuildMember.addRole(Role or String).
To add a member to a role, you need a GuildMember and a Role object (or the name of the role). Assuming you have the User object and the Guild object (your bot has a list of the guilds/servers it's joined and most events will have the guild they're associated with), you can get the GuildMember by using Guild.fetchMember(User). From there, you can add the role on the GuildMember using either the string or object based version of addRole.
Here's an example of how to do it upon receiving a message from a user which is very easy since the message has a GuildMember associated with it.
const Discord = require('discord.js');
const bot = new Discord.Client();
bot.on('message', (message) => {
const guildMember = message.member;
guildMember.addRole('bot-added-role');
});

Categories