检查用户是否有Discord.net角色

3

我正在尝试使用Discord.net,但是我无法使这段代码工作...

我的代码

using System;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Discord;
using Discord.WebSocket;

namespace NetflixManager
{
    class Program
    {
        private readonly DiscordSocketClient _client;

        static void Main(string[] args)
        {
            new Program().MainAsync().GetAwaiter().GetResult();
        }

        public Program()
        {
            _client = new DiscordSocketClient();

            _client.Log += LogAsync;
            _client.Ready += ReadyAsync;
            _client.MessageReceived += MessageReceivedAsync;
        }

        public async Task MainAsync()
        {
            await _client.LoginAsync(TokenType.Bot, File.ReadAllText("Token.txt"));
            await _client.StartAsync();

            await Task.Delay(-1);
        }

        private Task LogAsync(LogMessage log)
        {
            Console.WriteLine(log.ToString());
            return Task.CompletedTask;
        }

        private Task ReadyAsync()
        {
            Console.WriteLine($"{_client.CurrentUser} is connected!");

            return Task.CompletedTask;
        }

        private async Task MessageReceivedAsync(SocketMessage message)
        {
            // The bot should never respond to itself.
            if (message.Author.Id == _client.CurrentUser.Id)
                return;
            // The bot should not reply to private messages
            if (message.Channel.Name.StartsWith("@"))
                return;
            // The bot should not reply to bots
            if (message.Author.IsBot)
                return;
            // The bot should not reply to a webhook
            if (message.Author.IsWebhook)
                return;
            // Commands
            if (message.Content.StartsWith("!create"))
            {
                if (message.Author is SocketGuildUser socketUser)
                {
                    SocketGuild socketGuild = socketUser.Guild;
                    SocketRole socketRole = socketGuild.GetRole(772788208500211724);
                    if (socketUser.Roles.Any(r => r.Id == socketRole.Id))
                    {
                        await message.Channel.SendMessageAsync("The user '" + socketUser.Username + "' already has the role '" + socketRole.Name + "'!");
                    }
                    else
                    {
                        await socketUser.AddRoleAsync(socketRole);
                        await message.Channel.SendMessageAsync("Added Role '" + socketRole.Name + "' to '" + socketUser.Username + "'!");
                    }
                }
            }

            if (message.Content == "!ping")
                await message.Channel.SendMessageAsync("pong!");
        }
    }
}

我的目标

我想监测是否有人在服务器的任何聊天中写入“!create”,然后检查发送消息的人是否拥有名为“Game Notify”(Id:772788208500211724)的角色。 如果这个人确实拥有这个角色,它应该将此输出到原始消息所在的频道中:

"The user '<Username>' already has the role '<RoleName>'!"

如果用户没有该角色,则将其添加到该用户,并在原始消息所在的频道输出此信息:
"Added Role '<RoleName>' to '<Username>'!"

我的问题

如果我在没有该角色的情况下启动机器人,并写入!create one chat时,它会成功地给我分配该角色。当我执行命令第二次时,它再次给我分配该角色。它不会说我已经有该角色。

它也可以反过来使用: 如果我在启动机器人时拥有该角色并执行命令,则正确地指出我拥有该角色。当我现在手动将该角色从自己身上删除并再次执行命令时,它仍然说我有该角色

如何解决这个问题?

使用Discord.net Nu-Get包v2.2.0

1个回答

2
首先,与您目前的方法不同,您应该使用 内置命令服务。但是,这样做并不能解决您的问题。
如果您注意到与用户相关的奇怪行为,那么最有可能是由于最近的特权意图更新。Discord.NET会缓存(下载)用户,并使用诸如GuildUserUpdated之类的事件在后台更新此缓存。如果没有公会成员意向,Discord.NET无法及时更新其用户缓存,从而导致此类问题。
要解决问题,请在Discord开发者门户网站上的Bot选项卡上启用公会成员特权意图。
如果那样不起作用,那么使用 Discord.NET 的夜间版本,并在 DiscordSocketConfig 中指定您需要的所有意图。要使用夜间版本,请将 https://www.myget.org/F/discord-net/api/v3/index.json 添加为 NuGet 包管理器上的软件包源。
这是我的 DiscordSocketConfig,它指定了网关意图(仅在夜间版本中可用):
new DiscordSocketConfig 
{
    TotalShards = _totalShards,
    MessageCacheSize = 0,
    ExclusiveBulkDelete = true,
    AlwaysDownloadUsers = _config.FillUserCache,
    LogLevel = Discord.LogSeverity.Info,

    GatewayIntents = 
        GatewayIntents.Guilds |
        GatewayIntents.GuildMembers |
        GatewayIntents.GuildMessageReactions | 
        GatewayIntents.GuildMessages | 
        GatewayIntents.GuildVoiceStates
});

如果您需要更多帮助,我建议加入非官方Discord API服务器并在#dotnet-discord-net频道中提问。

非常感谢!我完全忽略了Discord开发者门户网站中的选项!感谢您的努力,亲切的陌生人! - SebiAi
1
没问题 @SebiAi :). 问题中有很多努力,回答中也有很多努力。 - 230Daniel

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接