如何使用DiscordSocketClient获得用户的角色 [英] How To Get a User's Role with a DiscordSocketClient

查看:109
本文介绍了如何使用DiscordSocketClient获得用户的角色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在如何获得用户角色上锁定了很长时间,因此可以为命令设置权限。这是我的代码。我在较新版本中使用Discord.NET。

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.)

推荐答案

如果要尝试获得用户角色,请尝试使用SocketGuildUser而不是字符串。 (使用var role =(用户为IGuildUser).Guild.Roles.FirstOrDefault(x => x.Name ==角色);)

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.

这篇关于如何使用DiscordSocketClient获得用户的角色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆