Add a role in Discord.js - javascript

I'm new at JS and I'm trying to make my bot give a specific role to a specific member.
If you can help me, please, do this.
The code:
bot.on("message", (msg) => {
if ((msg.content === "!give", role, member))
var role = msg.guild.roles.cache.find((r) => {
return r.name === "convidado astolfofo";
});
var member = msg.mentions.members.first();
member.roles.add(role);
console.log(member);
console.log(role);
});
The errors I encountered:
(node:2364) UnhandledPromiseRejectionWarning: TypeError [INVALID_TYPE]: Supplied roles is not a Role, Snowflake or Array or Collection of Roles or Snowflakes.
TypeError: Cannot read property 'add' of undefined discord.js

There are a couple of errors with your code. I'm not sure what you tried to do with if ((msg.content === "!give", role, member)) -- probably checking if the message starts with !give and if there is a role and a member -- but it won't work like that in JavaScript. You need to check them separately and once these variables are defined.
If you check if msg.content === "!give" but you also want the member to mention a member, it will never be true. If the whole message is just !give, there is no mentioned user. If there is a mentioned user, msg.content will be more than !give. Try to check if the message.content starts with "!give".
Next, if you don't use curly braces following your if statement, only the next line is inside that statement. So you try to check if the command is !give, and if it is, you search for a role, but the following lines where you check where you add the role are outside of this statement. It means, it runs on every incoming message. Try to use curly braces.
It's also a good idea to check permissions and send replies to let the user know if there are any missing ones.
Check the working example below, I've added comments to make it easier to understand:
bot.on('message', async (msg) => {
if (msg.content.startsWith('!give')) {
// check if the message author has the permission to add a role
if (!msg.member.hasPermission('MANAGE_ROLES')) {
return msg.reply('You need `MANAGE_ROLES` permission to add a role');
}
// check if the bot has the permission to add a role
if (!msg.guild.me.hasPermission('MANAGE_ROLES')) {
return msg.reply('I do not have `MANAGE_ROLES` permission to add a role');
}
// check if there is a member mentioned
const member = msg.mentions.members.first();
// if there is none, send a reply
if (!member) {
return msg.reply("Don't forget to mention someone!");
}
// search for the role
// don't forget that it's case-sensitive
const role = msg.guild.roles.cache.find((r) => r.name === 'convidado astolfofo');
// check if the role exists
if (!role) {
return msg.reply("Oh-oh, I can't find the role `convidado astolfofo`");
}
// try to add a role
try {
await member.roles.add(role);
msg.reply(`Role added to ${member}`);
} catch (error) {
console.log(error);
msg.reply('Oops, role not added, there was an error');
}
}
});

You seem to be using return incorrectly. Try this:
bot.on("message", (msg) => {
if ((msg.content === "!give", role, member))
var role = msg.guild.roles.cache.find(r => r.id === "<role id goes here>");
var member = msg.mentions.members.first();
member.roles.add(role);
console.log(member.username);
console.log(role.name);
});
I also changed your console.log statements since your console would get spammed with objects

Related

Discord, Mention someone when gets a role

Is there a way to mention someone immediately after getting a specific role in a specific channel?
For example when I, or any other admin, give someone a specific role the bot mentions them in a specific channel.
Here is my code:
client.on("guildMemberUpdate", (oldMember, newMember) => {
const channel = client.channels.cache.get("channelid");
// If the role(s) are present on the old member object but no longer on the new one (i.e role(s) were removed)
const removedRoles = oldMember.roles.cache.filter((role) => !newMember.roles.cache.has("roleid"));
if (removedRoles.size > 0) console.log(`The roles ${removedRoles.map((r) => r.name)} were removed from ${oldMember.displayName}.`);
// If the role(s) are present on the new member object but are not on the old one (i.e role(s) were added)
const addedRoles = newMember.roles.cache.filter((role) => !oldMember.roles.cache.has("roleid"));
if (addedRoles.size > 0) {
if (newMember.roles.cache.some((role) => role.name === "testing")) {
let embed = new Discord.MessageEmbed().setTitle("♡﹕welcome!").setDescription("lalalala").setColor("#FFB6C1").setThumbnail("https://cdn.discordapp.com/attachments/806974794461216813/817737054745526304/giffy_2.gif");
channel.send(`Welcome ${oldMember.user}`, embed);
}
console.log(`The roles ${addedRoles.map((r) => r.name)} were added to ${oldMember.displayName}.`);
}
});
This is assuming your code is exactly as shown in the question, and not using placeholder strings.
Firstly, "roleid" should be role.id without the "" when you're filtering. This will filter it properly, as should channelId where channel is defined, which I'm guessing are placeholders, but just in case.
Secondly, you'll probably want to check using addedRoles.has("roleIdToSend") as opposed to newMember.roles.cache.some(). This will DM them every time they're updated if they have the role, not if they only just got the role on that update.
Lastly, assuming you're using discord.js v13, you'll need to correct your send() method. It should look something like
channel.send({
content: `Welcome, ${oldMember.toString()}`,
embeds: [embed]
});

Discord.js: How can you check if a specific user has a role?

I'm looking to see if you can check if you can test for a specific user having a role. Only problem is that I'm fairly new to Discord.js and everything I searched up was either outdated, was something I couldn't fully understand or only showed how to test if the author of the message has the role, which is not what I'm trying to find out. What should I change in my current coding?
if (message.member.permissions.has("MANAGE_ROLES")) {
const member = message.mentions.users.first();
const memberTarget = message.guild.members.cache.get(member.id);
const role = message.guild.roles.cache.find(role => role.name === "Awesome Role Name");
if (memberTarget.roles.cache.has(role)) {
message.channel.send(`${memberTarget} has the role!`);
} else {
message.channel.send(`${memberTarget} does not have the role!`);
}
}
}
};
All you have to do is check if the GuildMember.roles.cache has the role. Also, the reason your code isn’t working is because you are using the role object. You need to use the role ID.
if (memberTarget.roles.cache.has(role.id))
More related things:
Getting role by any property
if (memberTarget.roles.cache.some(r => r.name === 'role-name'))
//does not need to be the name
Getting message author's roles
if (message.member.roles.cache.has(role.id))
To check for a role you can do the code:
if (member.roles.cache.has("ROLE_ID"))
If you wanted to check if the sender has the role you could do:
if (message.member.roles.cache.has("ROLE_ID")) {
console.log(true);
} else {
console.log(false);
}
If you wanted to check if someone else has a role you could do:
if (memberTarget.roles.cache.has("ROLE_ID")) {
console.log(true);
} else {
console.log(false);
}
To get a member you could do it in many different ways, one method would be to get them by mentions:
// This will get the first mention who is a member in the server
const memberTarget = message.mentions.members.first()
Read about guild member roles here

How do i make a discord bot that simply gives me a role when i type a certain phrase in Javascript?

I've done tons and tons of searches but they're all super complex codes such as, when i say "!Role (role)" then it gives me the role i specified. However, what i am looking for is something much simpler like if i were to say "Hello", then the bot would give me the role that's in the code.
I also tried a lot of the complex ones but most of them used the "addRole" function but the output didn't like it
Do you think you can help me with this?
Discord JS V12:
client.on("message", (message) => {
// Checking if the message equals to "hello".
// Since we use .toLowerCase() which converts any uppercase letter to lowercase, HeLLo will result in hello.
if (message.content.toLowerCase() == "hello") {
// Trying to find the role by ID.
const Role = message.guild.roles.cache.get("RoleID");
// Checking if the role exists.
if (!Role) { // The role doesn't exist.
message.channel.send(`I'm sorry, the role doesn't exist.`);
} else { // The role exists.
// Adding the role to the user.
message.member.roles.add(Role).catch((error) => {console.error(error)});
message.channel.send(`You received the role ${Role.name}.`);
};
}
});
Discord JS V11:
client.on("message", (message) => {
if (message.content.toLowerCase() == "hello") {
const Role = message.guild.roles.get("RoleID");
if (!Role) {
message.channel.send(`I'm sorry, the role doesn't exist.`);
} else {
message.member.addRole(Role).catch((error) => {console.error(error)})
message.channel.send(`You received the role ${Role.name}.`);
};
}
});

Discord JS // Trying to add role by reacting to the message

bot.on('messageReactionAdd', async (reaction, user) => {
// Define the emoji user add
let role = message.guild.roles.find(role => role.name === 'Alerts');
if (message.channel.name !== 'alerts') return message.reply(':x: You must go to the channel #alerts');
message.member.addRole(role);
});
Thats the part of my bot.js. I want the user to react in a certain channel and receive role Alerts
You haven't really stated what the problem is, what works and what doesn't work but I'll take a wild stab at some parts which catch my eye.
For starters you are calling properties on the variable message whilst in the code you supplied, you didn't create/set a variable named message. My guess is that you want the message to which a reaction has been added. To do that you have to use the MessageReaction parameter which is supplied in the messageReactionAdd event as reaction.
From there you can replace message.<something> with reaction.message.<something> everywhere in the code you supplied.
Something also to note is that you add the role Alerts to message.member. This won't work how you want it to, since it will give the Alerts role to the author of the original message.
What (I think) you want to do, is fetch the user who just reacted with the emoji and assign them the Alerts role. You'll have to find the member in the guild first and then assign them the Alerts role. To do this you'll have to use the User parameter and find the correct Member because you can't add a role to a User object but you can to a Member object. Below is some code which should hopefully put you on the right track.
// Fetch and store the guild (the server) in which the message was send.
const guild = reaction.message.guild;
const memberWhoReacted = guild.members.find(member => member.id === user.id);
memberWhoReacted.addRole(role);
You are using message.member variable despite not defining message.
Any of these methods won't really work in v12 so I updated it for someone else searching.
If you find any mistakes be sure to make me aware of it.
const Discord = require('discord.js');
const client = new Discord.Client({ partials: ['MESSAGE', 'CHANNEL', 'REACTION'] }); //partials arent really needed but I woudld reccomend using them because not every reaction is stored in the cache (it's new in v12)
const prefix = "-";
client.on('messageReactionAdd', async (reaction, user) => {
if (reaction.partial) { //this whole section just checks if the reaction is partial
try {
await reaction.fetch(); //fetches reaction because not every reaction is stored in the cache
} catch (error) {
console.error('Fetching message failed: ', error);
return;
}
}
if (!user.bot) {
if (reaction.emoji.id == yourEmojID) { //if the user reacted with the right emoji
const role = reaction.message.guild.roles.cache.find(r => r.id === yourRoleID); //finds role you want to assign (you could also user .name instead of .id)
const { guild } = reaction.message //store the guild of the reaction in variable
const member = guild.members.cache.find(member => member.id === user.id); //find the member who reacted (because user and member are seperate things)
member.roles.add(role); //assign selected role to member
}
}
})
Here's a quick answer, though way too late. So I'll be updating the answer with Discord.js v.12.x (or the same as Discord.js Master)
bot.on('messageReactionAdd', async (reaction, user) => {
//Filter the reaction
if (reaction.id === '<The ID of the Reaction>') {
// Define the emoji user add
let role = message.guild.roles.cache.find((role) => role.name === 'Alerts');
if (message.channel.name !== 'alerts') {
message.reply(':x: You must go to the channel #alerts');
} else {
message.member.addRole(role.id);
}
}
});

addRole is not a function

I am creating a Discord Bot.
I am trying create a Mute command, but I always get the same error.
What went wrong?
Background information:
Discord.js version: 12.0.0-dev
Klasa with version 0.5.0-dev is used
Code:
const { Command } = require('klasa');
const { MessageEmbed } = require('discord.js');
module.exports = class extends Command {
constructor(...args) {
super(...args, { description: 'Mute an user.' })
}
async run(msg, args) {
if(!msg.member.hasPermission("MANAGE_MEMBERS")) return msg.channel.send("You can't use this command.");
let MuteUser = msg.guild.member(msg.mentions.users.first() || msg.guild.members.get(args[0]))
if(!MuteUser) return msg.channel.send("Can't find user!");
let MuteReason = msg.content.split(" ").slice(2).join(" ");
let MuteRole = msg.guild.roles.find(r => r.name === "Spammer");
if(!MuteRole) return msg.channel.send("Can't find the Spammer role!");
let MuteChannel = msg.guild.channels.find(guild => guild.name === 'bot-logs');
if(!MuteChannel) return msg.channel.send("Can't find the #bot-logs channel.");
if(MuteUser.roles.has(MuteRole)) return msg.channel.send("That user is already muted!.");
MuteUser.addRole(MuteRole.id);
return MuteChannel.send(new MessageEmbed()
.setAuthor("Mute"|| 'Unknown', "http://wolfdevelopment.cf/BotSymbols/info.png")
.setColor("#ff0000")
.addField("Muted User", `${MuteUser}`)
.addField("Muted By", `<#${msg.author.id}>`)
.addField("Muted In", `${msg.channel}`)
.addField("Time", `${msg.createdAt}`)
.addField("Reason", `${MuteReason}`));
}
}
I have checked that MuteUser is a person in this line:
if(!MuteUser) return msg.channel.send("Can't find user!");
So it must be a person. Why doesn't it have an addRole function?
I decided to look at this from another viewpoint and searched the Discord.js documentation for some more information. Sure enough, something is found:
I assume your call to msg.guild.member would result in a GuildMember because that is what the name implies.
Stable (Presumably 11.x): https://discord.js.org/#/docs/main/stable/class/GuildMember
Note that addRole is the first item below Methods.
Now, switching to master (aka Development branch - where you got 12.0.0-dev from)...
https://discord.js.org/#/docs/main/master/class/GuildMember
addRole isn't there anymore.
Clicking the type of roles...
https://discord.js.org/#/docs/main/master/class/GuildMemberRoleStore
add is the first method.
You can probably replace MuteUser.addRole with MuteUser.roles.add.
Note: This does not invalidate any of my words in the comments because you didn't provide enough information in the question itself on what type MuteUser is when the error was thrown.
Note 2: This took one Google search only. How much work did you even put into research?
User don't have addRole : https://discord.js.org/#/docs/main/stable/class/User
But GuildMembers does.
Are you trying to cast to a member in the line where you defined "let MuteUser" ? It could be normal that it does not have the addRole methods if it' a user.
First: users don't have a role. Only members have roles.
Users are a discord user = a real life person (or a bot)
A Member object is a user "attached" to a server. So a member can have roles, because you only have roles within a specific server.
I tried someMember.addRole(someRole) too, and got the same addRole is not a function, error message.
Just try someMember.roles.add(someRole) and it works!!!
Providing I have:
guildID: the server ID
userID: the user ID
roleID: the role ID
memberID: NO !!! haha, got you!!! Members don't have IDs on Discord. A member is defined by a guildID and a userID, but it does not have an ID of it's own.
So, if I want to add a role to a member, here is what I do:
// get the guild
const guild = client.guilds.cache.get(guildID);
if (! guild) return console.error("404: guild with ID", guildID, "not found");
// get the member
const member = guild.members.cache.get(userID);
if (! member) return console.error("404: user with ID", userID, "not found in guild", guild.name);
// we check our bot has role management permission
if (! guild.me.hasPermission('MANAGE_ROLES'))
return console.error("I don't have the right to manage roles !!! :-( ");
// get the role
const role = guild.roles.cache.get(roleID);
if (! role) return console.error("404: role with ID", roleID, "not found in guild", guild.name);
// add role to member
member.roles.add(role)
.then(function() {
console.log("role", role.name, "added to", member.user.name, "on server", guild.name);
// do your stuff
})
.catch(function(err) {
console.error("could not assign role", role.name,
"to", member.user.name,
"on server", guild.name,
"because", error.message);
// cry
});
If that does not work:
Check that the highest role of the member is less powerfull than the highest role of your bot
Check that the role your bot is trying to add, is less powerfull than the highest role of your bot
And also: in the role configuration page of your server configuration, in the role list, make sure the role you are trying to attribute, is listed under the role of your bot (you can drag the roles to re-order them). (that one took me hours to figure out !!!)

Categories