Search code examples
c#discorddiscord.net

How to get a role in SocketMessage in discord.net to check whether the user has this role


private async Task checkMessage(SocketMessage arg)
{
 IGuildUser user = (IGuildUser)arg.Author;
 if (!user.IsBot)
 {
  if (arg.Author.Role == "pop")
  { 
   var emoji = new Emoji("\ud83d\udca9");
   await arg.AddReactionAsync(emoji);
   }
  }   
}

I want to check the role of the user who wrote the message, if there is a certain role, then perform a certain action, but I don't understand how to check the role of the user. Even reading the documentation I didn't understand anything.

I tried to get roles through SocketGuildUser, but nothing came out.


Solution

  • if (arg.Author.Role == "pop") There is no role property on IGuildUser, possibly this is a typo, and you meant to say .Roles
    In that case, .Roles returns a collection of the users roles, so matching that against "pop" will never return true.
    I've edited your code to function properly by using linq to query the collection of roles on the users, looking for a role with the name "pop"\

        private async Task checkMessage(SocketMessage arg)
        {
            if (arg.Author.IsBot) return;
            
            if (arg.Author is SocketGuildUser user)
            {
                if (user.Roles.Any(r => r.Name == "pop"))
                {
                    var emoji = new Emoji("\ud83d\udca9");
                    await arg.AddReactionAsync(emoji);
                }
            }
        }