简体   繁体   中英

Is there is a way to add role to someone who has mentioned in a message in discord.js?

This is my current code

let person = message.mentions.users.first()
if (person === null) {
 message.channel.send('Please mention someone')
 return
}
let role = message.guild.roles.cache.some(role => role.name === "Muted")
person.roles.add(role)
message.channel.send(`${person.username} has been muted`)
person.send('You has been muted in DoGame')

it's not working for some reason.

person returns a User object of the first mentioned user. You cannot add roles to a user, but only to a GuildMember - This can be done using message.mentions.members.first() .

Final Code

const person = message.mentions.members.first()
if (person === null) {
 message.channel.send('Please mention someone')
 return
}
const role = message.guild.roles.cache.some(role => role.name === "Muted")
person.roles.add(role)
message.channel.send(`${person.user.username} has been muted`)
person.send('You has been muted in DoGame')

There is difference between GuildMember and User .

GuildMember :

  • Represents a member of a guild on Discord
  • Properties: guild , joinedAt , user .. that are guild specific.
  • You can access User from GuildMember by <GuildMember>.user

User :

  • Represents a user on Discord
  • Properties: id , username , createdAt ... that are not guild specific.

And you're getting User from mentions and trying to add role to User instead of GuildMember .

const person = message.mentions.members.first();

This ^^^ will give you GuildMember and If you want to access User - person.user

Example: for username You can do like person.user.username .

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM