I searched all of Stack Overflow and the internet and found nothing helpful. I tried everything and it tells me the same thing. I'm making a Discord bot and trying to add a role to a user, but it keeps telling me I have an error. I have tried copying exactly what tutorials on YouTube and blogs did, but it tells me the same error. I'm being driven insane; I've tried to debug this error for over a week now. Here's my code:
const targetUser = message.mentions.users.first()
if(!targetUser) {
message.reply('ya gotta specify someone to give the role to ya idiot')
return
}
//gets the user's username. For example: someone#0001
args.shift()
//takes user out of the arguments array
const roleName = args[0]
//finds the name of the role. For example: Mod.
const { guild } = message
//not sure what this does. I copied it from a tutorial on YouTube. I think it just makes saying guild the same thing as saying message
const rool = guild.roles.cache.find((role)=>{
return role.name === roleName
})
const role = rool.toString().replace("<", "").replace(">", "").replace("@", "").replace("&", "")
//this gets the role id: for example: 912345678901234567
if(!role) {
message.reply(`There is no role with the name ${roleName}. btw, you might want to put the person you're adding the role to first, *and then* the role name.`)
//checks if role exists
}
const member = targetUser.id
//gets user id. For example: 812345678901234567
try{
member.role.add(role)//THIS IS THE ONE I HAVE TROUBLE WITH. THE ONE LINE! ALL THE OTHERS WORK PERFECTLY FINE. I HAVE NO IDEA WHAT'S WRONG.
} catch(bad){
message.channel.send("i have bad bad error: " bad ". Please try again later. Much, much later.")
message.channel.send(`btw, member = ${member} and the role is ${role}`)
message.channel.send(typeof role)
message.channel.send(typeof member)
//the role is a string. the member is a string. I checked, and they are right. I've seen other people do the exact same thing as me and it DOESN'T WORK.
}
Feel free to ask for more code if you need it. Whenever I run the code, because I have a catch, it tells me:
i have bad bad error: TypeError: Cannot read properties of undefined (reading 'add'). Please try again later. Much, much later.
btw, member = 768522095071985746 and the role is 925077346170585138
string
string
Maybe something is wrong with my compiler or runtime environment or all those other weird words programmers use?
CodePudding user response:
You are trying to access to a role
property on an id which is not possible since it's not an object, the right way to access to the roles of a GuildMember
instance is <GuildMember>.roles
, role
one doesn't exists and even less on a <User>
.
const member = message.mentions.members.first();
const roleName = args[0];
const role = message.guild.roles.cache.find(role => role.name === roleName);
try {
member.roles.add(role);
} catch(error) {
message.channel.send('Error');
}