【问题标题】:Give role when a user add reaction (C# Discord.net)当用户添加反应时赋予角色(C# Discord.net)
【发布时间】:2021-08-04 06:14:01
【问题描述】:

我想在有人单击“确定”反应时使用不和谐 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 != "✅") return;
    var role = (arg2 as SocketGuildChannel).Guild.GetRole(842522201881837585);
    await (arg3.User.Value as SocketGuildUser).AddRoleAsync(role); //This is line 43
}

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

【问题讨论】:

  • 不熟悉 discord API,但错误告诉我 SocketReaction.User 未设置或在 arg3 中传递。您可以通过测试if (arg3.User==Null) throw someException 来确认这一点
  • 我强烈建议调试并检查 arg3.User 的样子。 Github 上有一些建议,在这样的 API 方法中,全新的服务器用户可能为 null。

标签: c# discord discord.net


【解决方案1】:

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

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

截图:Bot Configuration

【讨论】:

    猜你喜欢
    • 2019-09-22
    • 2019-02-12
    • 2021-08-26
    • 2019-05-31
    • 1970-01-01
    • 2017-05-31
    • 2018-07-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多