Add role to user by ID - discord.js

I try to add a role to a user by ID, but I always receive this error
user.roles.add(role)
^
TypeError: Cannot read properties of undefined (reading 'add')
Here is my code
let role = Guild.roles.cache.find((r) => r.name === dataobj.Guild.name);
client.users.fetch(useritem).then((user) => {
user.roles.add(role)
.catch(error => { })
});
dataobj.Guild.name is the name of the role.
useritem is the ID of the user.
var role is correct and output the right role.
Var user is correct and output the right user.
I tried many things, but nothing works.
Thank for your help.

You should fetch guild.members instead of client.users and to add role by its ID you should use role.id instead of role

Related

How do I check if a user has a specific role? | discord.js v13

How do I check if a user has a specific role? However, not by mentioning the user but through their ID. so, obviously this wouldn't work:
message.member.roles.cache.some(role => role.name === 'ROLE')
neither does client.users.cache.get('ID'); have a property allowing me to access their roles. neither does client.users.fetch. So how can I do it?
client.users.fetch() and client.users.cache.get() both return Users which don't have roles. You need to get a GuildMember from a guild
let member = guild.members.cache.get("id")
let hasRole = member.roles.cache.some(role => role.name === 'ROLE')

How can a bot add roles to a user? (Discord.js)

I have a discord bot that I'm attempting to assign a user a role with. From some searching around, I've discovered that the code
let role = message.guild.roles.cache.get("[role_id]")
message.author.roles.add(role)
is supposed to work.
The issue is that message.author.roles doesn't exist. Is there a new way to do this for discord.js v13, or am I missing something?
As per the discord.js docs, Message#author is a User object, which doesn't have the .roles property. What you want is Message#member, which is a GuildMember and has the property you want in order to give and remove roles.
Give this a shot:
let role = message.guild.roles.cache.get("[role_id]")
message.member.roles.add(role)
I use another method and it works as good as this, try it out
let role = message.guild.roles.cache.find((role) => role.name === "[role name here]")
message.member.roles.add(role)
const mention = (await message.mentions.members.first()) || message.guild.members.cache.get(args[0]) || message.guild.members.cache.find((r) => r.user.username.toLowerCase().includes() === args.join(" ").toLocaleLowerCase()) || message.guild.members.cache.find((r) => r.displayName.toLowerCase().includes() === args.join(" ").toLocaleLowerCase()); // get member on mention
const role = message.mentions.roles.first(); // get role on mention
await mention.roles.add(role)
{prefix} {command} {mention a user} {mention a role}
Don't forget, this is in async function

How do I check what roles my bot has? [Discord.js]

I am trying to find if my bot has a specific role so it can do something else. For example:
client.user.roles.cache.find(r => r.name === 'specific role');
My error:
TypeError: Cannot read property 'cache' of undefined
Let's start of by stating that users do not have roles, therefore you have to fetch the guildMember.
Fetching the guild member is easy;
First of all, you will have to fetch the guild the user is in. For example:
var guild = client.guilds.cache.get('guild-id');
Secondly, you will have to find the user in that guild. For example:
var member = guild.members.cache.get('user-id');
Then you will be able to move forward and fetch the roles
member.roles.cache.find(r => r.name === 'role-name');
The full example:
const Discord = require('discord.js'); //Define discord.js
const client = new Discord.Client(); //Define the client
client.on('message' message => { //Event listener
//Do something here
var guild = client.guilds.cache.get(message.guild.id);
var member = guild.members.cache.get(client.user.id);
member.roles.cache.find(r => r.name === 'role-name');
});
client.login('token'); //Login
So maybe I didnt explain my problem very well but here is what I found working for me message.guild.me.roles.cache.find(r=> r.name === 'a role') thanks to everyone for helping me !!!
You need to resolve the user into a GuildMember, since users don't have roles.
To do that you need a Guild class,after that you can use the guild.member() method to convert it to a member
const guild = client.guilds.cache.get('id of the guild'),
member = guild.member(client.user.id);
member.roles.cache.find(r=> r.name === 'name')
Another issue you might run into here is, the member constant being undefined, this can be solved by using guild.members.fetch(id) or enabling the Privileged Member intent in the Discord Developer Portal

identifying admins from mentions discordjs

I want to find out if there are mentions in a message which I am doing using if(message.mentions.users.first()) but now among all the mentions I also want to filter out mentions of the admin team and not those of the community members. How to achieve that?
I tried filtering users based on roles like this
let r = [];
message.mentions.users.forEach( user => {
console.log('user' + user)
user.roles.forEach(role => {
console.log('role' + role)
r.push(role);
})
console.log('roles' + r);
var member = false;
for (i in r) {
if (i == 'admin') {
member = true;
}
}
})
This doesn't seem to work.
const adminName = ['<role name>'];
const adminId = ['<role ID>'];
client.on('message', (msg) => {
let admins = msg.mentions.members.filter( (user) => {
return adminId.some(id => user.roles.has(id)) || user.roles.some(r => adminName.includes(r.name));
});
console.log(admins.map(d => d.user.username));
});
There, I created 2 arrays, one with the role ID and another with the role name. You can use both, or only one (I prefer to use the id, because you can change a role name, but you can't change an id, except if you delete the role).
Then, I iterate through the members in the mentions of the messages. Why the members and not the users? Because the GuildMember is a type linked to a guild, which is an instance of an user in a guild, and so it has the role of the user.
Then I check if one of the id of my admins roles is in the roles of the user or if one of the roles name is inside my adminName.
The variable admins is a collection of GuildMember.
You can change the function inside the some to match whatever condition make someone an admin for you.

Add a role to people that react with a certain emoji in a certain channel

I'm trying to make a discord.js bot for my server I made for people in my school. I'm trying to make a #classes channel and if you react to certain messages it gives you a role (which gives you access to the text channel for that class).
client.on('messageReactionAdd', (reaction, user) => {
console.log("client.on completed.")
if (message.channel.name === 'classes') {
console.log("if(message) completed.")
if (reaction.emoji.name === "reminder_ribbon") {
console.log("emoji test completed.")
const guildMember = reaction.message.guild.members.get(user.id);
const role = reaction.message.guild.roles.find(role => role.name === "FACS");
guildMember.addRole(role);
}
}
});
This is what I have tried so far, however, it does not give me/the other people reacted to it the role nor does it return an error message.
P.S. Also, how would I be able to make it so when they unreact it removes the role?
Edit: It seems it only gets reactions from cached messages/messages sent after bot startup. Also, message is not defined on the first if(message.channel.id) message.
Try to use the following code:
client.on('messageReactionAdd', (reaction, user) => {
if (reaction.message.channel.id === '552708152232116224') {
if (reaction.emoji.name === "reminder_ribbon") {
const guildMember = reaction.message.guild.members.get(user.id);
const role = reaction.message.guild.roles.get('552709290427940875');
guildMember.addRole(role);
}
}
});
First of all, reaction.users is an Object with all the users that reacted on the message, so you first have to define to which user you want to assign the role. I fixed this fetching the guildMember with user.id.
The second mistake was that you tried to assign a role ID to a guildMember although you first have to fetch the role and then assign the role Object to the guildMember.

Resources