是否没有调用UserJoined事件处理程序?

时间:2018-12-10 02:52:08

标签: c# discord.net

我正在使用Discord.net API构建一个机器人。该机器人的功能之一是欢迎新用户。这是通过挂接到UserJoined事件中的事件处理程序完成的。

public class Program
{
    private DiscordSocketClient client;

    public async Task MainAsync()
    {
        client = new DiscordSocketClient(new DiscordSocketConfig
        {
            LogLevel = LogSeverity.Debug
        });

        client.UserJoined += Client_AnnounceJoinUser;

    }

    public async Task Client_AnnounceJoinUser(SocketGuildUser guildUser)
    {
        Console.WriteLine($"[{DateTime.Now} at AnnounceJoinUser] a new user has joined!");
        var guild = client.GetGuild(//Guild Id);
        var channel = client.GetChannel(//Channel Id) as SocketTextChannel; 
        var rookieRole = guild.GetRole(//Role Id);

        await guildUser.AddRoleAsync(rookieRole);
        await channel.SendMessageAsync($"Hello {guildUser.Mention}, and welcome to {channel.Guild.Name}!/n/n{GetMessage(0)}");
    }

将用户添加到行会时,我收到来自网关确认的日志。

  

[Gateway 12/12/2018 10:01:30 PM]已收到调度(GUILD_MEMBER_ADD)

但是,调用事件处理程序的client.UserJoined行永远不会运行。我试图在此处放置一个断点,但从未触发过该断点。我推测问题可能在于未能指定行会来观察UserJoined事件,但我不确定如何进行。任何建议将不胜感激。

1 个答案:

答案 0 :(得分:0)

我知道了。从我发布的初始代码(哎呀)还不清楚,但是该事件的调用行位于MainAsync任务的底部。通过将此事件(和其他事件)的调用行移到我的行上方以登录僵尸程序,该行运行,事件处理程序被成功调用。我的完整MainAsync如下:

public async Task MainAsync()
    {
        client = new DiscordSocketClient(new DiscordSocketConfig
        {
            LogLevel = LogSeverity.Debug
        });

        Commands = new CommandService(new CommandServiceConfig
        {
            CaseSensitiveCommands = false,
            DefaultRunMode = RunMode.Async,
            LogLevel = LogSeverity.Debug
        });

        client.MessageReceived += Client_MessageReceived;
        await Commands.AddModulesAsync(Assembly.GetEntryAssembly());

        client.Ready += Client_Ready;
        client.Log += Client_Log;
        client.UserJoined += Client_AnnounceJoinUser;
        client.GuildMemberUpdated += Client_AnnounceUpgradeUser;

        string token;
        FileStream stream = new FileStream($"{Directory.GetCurrentDirectory()}/data/token.txt", FileMode.Open, FileAccess.Read);
        StreamReader readToken = new StreamReader(stream);
        token = readToken.ReadToEnd();

        await client.LoginAsync(TokenType.Bot, token);

        await client.StartAsync();

        await Task.Delay(-1);
    }