【问题标题】:Discord.NET: UserJoined Event not being calledDiscord.NET:未调用 UserJoined 事件
【发布时间】:2022-01-11 00:29:28
【问题描述】:

我正在使用 Discord.NET 构建一个 Discord 机器人,它应该报告用户加入、离开、被踢和被禁止进入仅限 mod/admin 的审核频道,但我无法获得相关功能当用户加入公会时触发。

我删除了我的消息发送代码并将其替换为控制台输出,以确定问题是事件未触发还是发送消息请求不起作用并发现事件未触发。

我已启用 Bot 管理控制台中的所有意图。

我根据documentation添加了意图:

var socketConfig = new DiscordSocketConfig
{
    GatewayIntents = GatewayIntents.AllUnprivileged | GatewayIntents.GuildMembers | GatewayIntents.GuildBans
};

_client = new DiscordSocketClient(socketConfig);

然后我已经注册了事件:(注意:_client = client;在此之前使用)

client.UserJoined += UserJoined;

最后写了要触发的函数:

public Task UserJoined(SocketGuildUser user)
{
    Console.Write("User ");
    Console.Write(user.Username);
    Console.WriteLine(" joined.");

    return Task.CompletedTask;
}

这里有什么我没有做或做错的吗?我花了大约两天的时间完全不知道问题出在哪里,一切似乎都表明我做的一切都是正确的,但我无法从 Discord 收到这个事件。

我所做的每一项更改都还尝试将机器人删除并重新添加到我的测试服务器。我也没有收到与this 帖子中提到的[12/8/2018 10:01:30 PM at Gateway] Received Dispatch (GUILD_MEMBER_ADD) 类似的任何消息。

我在下面包含了我的完整 Program.cs:

using System;
using Discord;
using Discord.Net;
using Discord.Commands;
using Discord.WebSocket;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.Json;
using Microsoft.Extensions.DependencyInjection;
using BanBot2.Bot.Services;

namespace BanBot2.Bot
{
    class Program
    {
        // setup our fields we assign later
        private readonly IConfiguration _iconfig;
        private DiscordSocketClient _client;

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

        public Program()
        {
            var socketConfig = new DiscordSocketConfig
            {
                GatewayIntents = GatewayIntents.AllUnprivileged | GatewayIntents.GuildMembers | GatewayIntents.GuildBans
            };

            _client = new DiscordSocketClient(socketConfig);
            
            // create the configuration
            var _builder = new ConfigurationBuilder()
                .SetBasePath(AppContext.BaseDirectory)
                .AddJsonFile(path: "application.json");  

            // build the configuration and assign to _config          
            _iconfig = _builder.Build();
        }

        public async Task MainAsync()
        {
            // call ConfigureServices to create the ServiceCollection/Provider for passing around the services
            using (var services = ConfigureServices())
            {
                // get the client and assign to client 
                // you get the services via GetRequiredService<T>
                var client = services.GetRequiredService<DiscordSocketClient>();
                _client = client;

                // setup logging and the ready event
                client.Log += LogAsync;
                client.Ready += ReadyAsync;
                client.UserJoined += UserJoined;
                services.GetRequiredService<CommandService>().Log += LogAsync;

                // this is where we get the Token value from the configuration file, and start the bot
                await client.LoginAsync(TokenType.Bot, _iconfig["Token"]);
                await client.StartAsync();

                // we get the CommandHandler class here and call the InitializeAsync method to start things up for the CommandHandler service
                await services.GetRequiredService<CommandHandler>().InitializeAsync();

                await Task.Delay(-1);
            }
        }

        public Task UserJoined(SocketGuildUser user)
        {
            Console.Write("User @");
            Console.Write(user.Username);
            Console.WriteLine(" joined.");

            return Task.CompletedTask;
        }

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

        private Task ReadyAsync()
        {
            Console.WriteLine($"Connected as -> [{_client.CurrentUser}] :)");
            return Task.CompletedTask;
        }

        // this method handles the ServiceCollection creation/configuration and builds out the service provider we can call on later
        private ServiceProvider ConfigureServices()
        {
            // this returns a ServiceProvider that is used later to call for those services
            // we can add types we have access to here, hence adding the new using statement:
            // using BanBot2.Bot.Services;
            // the config we build is also added, which comes in handy for setting the command prefix!
            return new ServiceCollection()
                .AddSingleton(_iconfig)
                .AddSingleton<DiscordSocketClient>()
                .AddSingleton<CommandService>()
                .AddSingleton<CommandHandler>()
                .BuildServiceProvider();
        }
    }
}

【问题讨论】:

  • 仅供参考,您现在可以拥有从 C# 7.1 及更高版本开始的async Task Main
  • 所以我可以将static void Main(string[] args) =&gt; new Program().MainAsync().GetAwaiter().GetResult();MainAsync() 合并为一个带有async 标志的Main()
  • 是的,public static async Task Main() { /* content of MainAsync here */ } 工作得很好
  • 您有两个单独的clients,并且您正在使用未配置意图的一个。编辑:实际上你用client覆盖_client,而你应该使用_client

标签: c# .net-core discord.net


【解决方案1】:

您创建DiscordSocketClient 的实例并包含适当的DiscordSocketConfig

//good
            var socketConfig = new DiscordSocketConfig
            {
                GatewayIntents = GatewayIntents.AllUnprivileged | GatewayIntents.GuildMembers | GatewayIntents.GuildBans
            };

            _client = new DiscordSocketClient(socketConfig);

但是,在ConfigureServices 中,您应该将之前创建的DiscordSocketClient 添加到ServiceProvider。相反,你这样做

//bad
.AddSingleton<DiscordSocketClient>()

而你应该做的是

//good
.AddSingleton(_client)

由于您没有在配置服务中将客户端实例添加到服务提供者,因此从服务提供者检索客户端实际上会实例化一个新的DiscordSocketClient,因为提供者中尚不存在此DiscordSocketClient

var client = services.GetRequiredService<DiscordSocketClient>();

tl;dr - 确保您只使用DiscordSocketClient 的单个实例。此实例应配置适当的意图。

【讨论】:

  • 我不敢相信我没有怀疑。我看过的几乎所有教程都已过时,足以达到不需要意图的程度,因此无需费心声明它们。那时通过.AddSingleton&lt;DiscordSocketClient&gt;() 创建一个新实例就足够了。
猜你喜欢
  • 2021-02-20
  • 1970-01-01
  • 2017-09-20
  • 2018-07-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-08
  • 2014-03-06
相关资源
最近更新 更多