I am trying to use the discord API to make a bot that its going to create a role and add a person to it. I'm not sure why my code isn't working.
async function role(message){
try {
let guild = client.guild.get(236824834066219009);
guild.roles.create({
data:{
name:"asd",
color:"grey",
},
reason:"asd",
})
let role = message.guild.roles.find(r => r.name === "asd");
let user = 236824834066219009;
await user.addrole(role).catch(console.error);
} catch (error) {
console.log(error);
}
}
The reason why your code is not working is because since discord.js
v12 there have been a lot of changes.
You can't use .find()
on roles
anymore you have to access their cache
first so you need to replace let role = message.guild.roles.find(r => r.name === "asd");
with let role = message.guild.roles.cache.find(r => r.name === "asd");
You also can't add roles using addrole()
, you need to use roles.add()
so you need to replace user.addrole(role)
with user.roles.add(role)
You can also make your code more efficient by not having to find the role
, you can just use .then()
to add the role to the user
, which you can also pass through as a parameter in your function along with the guild
, like so:
async function role(message, user, guild){
try {
guild.roles.create({
data:{
name:"asd",
color:"grey",
},
reason:"asd",
}).then((role) => user.roles.add(role)).catch(console.error);
} catch (error) {
console.log(error);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.