簡體   English   中英

如何檢查用戶是否在 discord.NET 中具有角色?

[英]How could I check if a user has a role in discord.NET?

我正在嘗試找到一種方法來檢查用戶是否具有 X 角色,如果沒有,則執行某些操作,類似於如果您使用[RequireUserPermission(GuildPermission.Administrator)]將其記錄到控制台的方式,只是我沒有不想讓它登錄到控制台,EX:

if (has role)
{
    // do stuff
} else
{
    // do stuff
}

我試圖將其實施到的命令

[Command("clear")]
[RequireUserPermission(GuildPermission.ManageRoles)]
public async Task Clear(int amount)
{

    IEnumerable<IMessage> messages = await Context.Channel.GetMessagesAsync(amount + 1).FlattenAsync();
    await ((ITextChannel)Context.Channel).DeleteMessagesAsync(messages);

    const int delay = 3000;
    IUserMessage m = await ReplyAsync($"I have deleted {amount} messages");

    await Task.Delay(delay);
    await m.DeleteAsync();

    Console.Write(amount + " was cleared in a channel");
}

正如 akac 指出的那樣,您提到的前提條件[RequireUserPermission(...)]檢查分配給用戶的任何角色是否授予他們執行特定任務的權限。 考慮以下示例。 您創建一個名為“版主”的角色並啟用“管理消息”權限。 然后將前置條件[RequireUserPermission(ChannelPermission.ManageMessages)]添加到Clear()方法中。 您的Clear()方法現在適用於“版主”角色中的任何人,因為他們有權管理消息。 它還將允許具有相同權限的任何其他角色的任何人使用它。

但是,如果您稍后決定不希望“版主”能夠管理消息並刪除該角色的權限,那么您的前提條件將自動阻止該角色中的任何人使用Clear命令。

如果您檢查用戶角色而不是他們的權限,則具有“版主”角色的用戶仍然可以使用Clear命令刪除消息,即使您已從該角色刪除管理消息的權限。

如果您要檢查角色而不是使用前提條件來檢查其權限的唯一原因是因為您不希望它登錄到控制台,那么這對您來說可能是錯誤的方法。 相反,您應該考慮堅持前提條件並查看您如何處理日志記錄以防止該消息被記錄到控制台。

如果您仍想檢查用戶的角色,那么這里有一個示例,說明如何在您提供的Clear()方法中執行此操作。 您需要using System.Linq; 到文件頂部,並將第二個if語句中的"RoleName"替換為您要檢查的角色的名稱。

public async Task Clear(int amount)
{
    // Get the user that executed the command cast it to SocketGuildUser
    // so we can access the Roles property
    if (Context.User is SocketGuildUser user)
    {
        // Check if the user has the requried role
        if (user.Roles.Any(r => r.Name == "RoleName"))
        {
            IEnumerable<IMessage> messages = await Context.Channel.GetMessagesAsync(amount + 1).FlattenAsync();
            await((ITextChannel) Context.Channel).DeleteMessagesAsync(messages);

            const int delay = 3000;
            IUserMessage m = await ReplyAsync($"I have deleted {amount} messages");

            await Task.Delay(delay);
            await m.DeleteAsync();

            Console.Write(amount + " was cleared in a channel");
        }
        else
        {
            await Context.Channel.SendMessageAsync("Sorry, you don't have permission to do that.");
        }
    }
}

幾天前我遇到了這個問題,我的解決方案是創建一個繼承自Discord.Commands.PreconditionAttribute的自定義屬性

當我在我的 Visual Studio 安裝中使用 dotPeek 來反編譯和閱讀命令服務的實際工作方式時,我發現了這一點,因為我想知道它們的屬性是如何工作的。 作為命令服務執行命令的一部分,它檢查每個命令的所有先決條件,並且只有在滿足每個先決條件時才會執行 function。

這個 class 有一個名為 CheckPermissionsAsync 的CheckPermissionsAsync

這是一個適合您的示例:

public class RequiresRoleAttribute : PreconditionAttribute
{
    private string m_role;

    public RequiresRoleAttribute (string role)
    {
        m_role = role;
    }

    public override async Task<PreconditionResult> CheckPermissionsAsync(ICommandContext context, CommandInfo command, IServiceProvider services)
    {
        if (context.User is SocketGuildUser sgu)
        {
            if (sgu.Roles.Select(x => x.Name == m_name).Contains(m_name)
            {
                return PreconditionResult.FromSuccess();
            }
        }

        return PreconditionResult.FromError($"The user doesn't have the role '{m_name}'");
    }
}

以及用途:

[Command("clear")]
[RequiresRole("RoleName")]
public async Task Clear(int amount)
{

    IEnumerable<IMessage> messages = await Context.Channel.GetMessagesAsync(amount + 1).FlattenAsync();
    await ((ITextChannel)Context.Channel).DeleteMessagesAsync(messages);

    const int delay = 3000;
    IUserMessage m = await ReplyAsync($"I have deleted {amount} messages");

    await Task.Delay(delay);
    await m.DeleteAsync();

    Console.Write(amount + " was cleared in a channel");
}

這是你要做的:

您使用 RequireRoles 屬性。

它有 4 種不同的方式:全部、任意、僅指定、無

假設您想發出禁令命令,但只希望管理員和模組能夠使用它。 你會這樣做:

    public class Moderation : BaseCommandModule
{
    [Command("ban")]
    [RequireRoles(RoleCheckMode.Any, "admin", "mod")]
    public async Task BanCommand(CommandContext ctx, DiscordMember name, [RemainingText] string reason)
    {
        
    }
}

你在這里做什么基本上是使用前置條件來檢查用戶的任何角色是否具有ManageRoles權限,描述令人困惑。

據我所知,Discord.net 不會記錄此類錯誤,只會將默認錯誤消息放入命令的Result中,然后通常將其作為響應發送到通道。 顯然,您的代碼必須在某個地方記錄此類錯誤。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM