首页 > 解决方案 > 当用户添加反应时赋予角色(C# Discord.net)

问题描述

我想在有人单击“确定”反应时使用不和谐 API 为用户分配角色。但是,我的代码第 43 行出现错误(如下所示)。

控制台日志:

 Discord.WebSocket.DiscordSocketClient[0]
  Gateway: A ReactionAdded handler has thrown an unhandled exception.
  System.InvalidOperationException: This property has no value set.
     at Discord.Optional`1.get_Value()
     at Template.Services.CommandHandler.OnReactionAdded(Cacheable`2 arg1, ISocketMessageChannel arg2, SocketReaction arg3) in C:\Users\Paul\Source\Repos\Discord.NET-Template\Template\Services\CommandHandler.cs:line 43
     at Discord.EventExtensions.InvokeAsync[T1,T2,T3](AsyncEvent`1 eventHandler, T1 arg1, T2 arg2, T3 arg3)

我的代码:

public override async Task InitializeAsync(CancellationToken cancellationToken)
{
    _client.MessageReceived += OnMessageReceived;
    _service.CommandExecuted += OnCommandExecuted;
    _client.ReactionAdded += OnReactionAdded;
    await _service.AddModulesAsync(Assembly.GetEntryAssembly(), _provider);
}
private async Task OnReactionAdded(Cacheable<IUserMessage, ulong> arg1, ISocketMessageChannel arg2, SocketReaction arg3)
{
    if (arg3.MessageId != 842517264716136469) return;
    if (arg3.Emote.Name != "✅&quot;) return;
    var role = (arg2 as SocketGuildChannel).Guild.GetRole(842522201881837585);
    await (arg3.User.Value as SocketGuildUser).AddRoleAsync(role); //This is line 43
}

这个arg3.User.Value表达有问题。我很乐意在这个问题上得到任何帮助。

标签: c#discorddiscord.net

解决方案


代码是正确的。有必要在机器人配置中启用网关意图。

这些,在https://discord.com/developers/applications/的 bot 选项卡下

截图:机器人配置


推荐阅读