成员加入 Channels 的Discord Bot活动

我希望我的Discord机器人在加入 Channels 时向成员致意 . 发生这种情况时,我无法找到发生的事件 . 我曾尝试过 myClient.UserJoined += MyMethod; 和其他人,但我们希望他们永远不会被解雇 . 这是我的主要代码:

public class Program
{
    private DiscordSocketClient _client;
    private CommandService _commands;
    private IServiceProvider _services;

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

    public async Task RunBotAsync()
    {
        _client = new DiscordSocketClient();
        _commands = new CommandService();
        _services = new ServiceCollection()
            .AddSingleton(_client)
            .AddSingleton(_commands)
            .BuildServiceProvider();

        string botToken = // removed

        _client.Log += Log;

        await RegisterCommandsAsync();
        await _client.LoginAsync(TokenType.Bot, botToken);
        await _client.StartAsync();
        await Task.Delay(-1);
    }

    private Task Log(LogMessage arg)
    {
        Console.WriteLine(arg);
        return Task.CompletedTask;
    }

    public async Task RegisterCommandsAsync()
    {
        _client.MessageReceived += HandleCommandAsync;
        _client.UserJoined += JoinedAsync; // Something like this to notify bot when someone has joined chat?

        await _commands.AddModulesAsync(Assembly.GetEntryAssembly());
    }

    private Task JoinedAsync(SocketGuildUser arg)
    {
        throw new NotImplementedException();
    }

    private async Task HandleCommandAsync(SocketMessage arg)
    {
        var message = arg as SocketUserMessage;

        if(message is null || message.Author.IsBot)
        {
            return;
        }

        int argPos = 0;

        if (message.HasStringPrefix("!", ref argPos))
        {
            var context = new SocketCommandContext(_client, message);
            await _commands.ExecuteAsync(context, argPos);
        }
    }
}

谢谢,如果我能提供更多信息,请告诉我 .

编辑:建议的链接实现UserJoined事件,该事件似乎仅在新成员加入 Channels 时触发 . 我需要每当有人登录 Channels 时触发的内容,甚至是现有成员 .

回答(1)

2 years ago

从编辑来看,我认为你可能对这些 Channels 如何运作有一点误解 .

用户加入公会,之后,他们已成为公会的一部分 .
他们加入公会之后,他们就是其中的一部分,以及他们被允许看到的 Channels . 因此,不再需要登录 Channels .

现在我想你想要实现的是当他们从离线状态切换到在线状态时,在 Channels /用户中发送消息 .

为此,您可以使用 UserUpdated 事件 . 您可以在哪里检查用户的上一个和当前状态,并相应地发送消息 .

_client.UserUpdated += async (before, after) =>
{
   // Check if the user was offline, and now no longer is
   if(before.Status == UserStatus.Offline && after.Status != UserStatus.Offline)
   {
      // Find some channel to send the message to
      var channel = e.Server.FindChannels("Hello-World", ChannelType.Text);
      // Send the message you wish to send
      await channel.SendMessage(after.Name + " has come online!");
   }
}