Search code examples
c#.netrolesdiscorddiscord.net

How To Get a User's Role with a DiscordSocketClient


I have been locking for a long time on how to get a user's role so I can set permissions for commands. This is my code. I am using Discord.NET in the newer version.

using Discord.Commands;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AmberScript2.Modules
{
    public class Kick : ModuleBase<SocketCommandContext>
    {
        [Command("kick")]
        public async Task KickUser(string userName)
        {
            if (Context.Guild.GetRole(Context.Message.Author.Id).Name == "Administrator")
            {
                await Context.Channel.SendMessageAsync("Success!");
            }
            else
            {
                await Context.Channel.SendMessageAsync("Inadequate permisions.");
            }
        }
    }
}

The error i am getting is object reference not set to an instance of an object. I have been trying to find the source of it and i can't. Thanks.

(And yes i have yet to get rid of excess usings. This code isn't done yet.)


Solution

  • If you want to try to get a role of the user, try using SocketGuildUser instead of a string. (Use var role = (user as IGuildUser).Guild.Roles.FirstOrDefault(x => x.Name == "Role");)

    using Discord.Commands;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace AmberScript2.Modules
    {
        public class Kick : ModuleBase<SocketCommandContext>
        {
            [Command("kick")]
            public async Task KickUser(SocketGuildUser userName)
            {
                 var user = Context.User as SocketGuildUser;
                 var role = (user as IGuildUser).Guild.Roles.FirstOrDefault(x => x.Name == "Role");
                 if (!userName.Roles.Contains(role))
                 {
                // Do Stuff
                if (user.GuildPermissions.KickMembers)
                {
                await userName.KickAsync();
                }
            }
        }
    }
    }
    

    That is most of my code for kicking.