会员加入频道的Discord Bot活动

时间:2018-06-24 20:10:32

标签: c# discord discord.net

我希望我的Discord机器人在加入频道时向他们致意。我一直找不到发生这种情况时会触发的事件。我尝试了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事件,该事件似乎仅在新成员加入频道时触发。我需要能够在任何人登录到该频道(甚至是现有成员)时触发的内容。

1 个答案:

答案 0 :(得分:0)

从编辑的角度来看,我认为您可能对渠道的运作方式有误解。

用户加入公会后,他们便成为公会的一部分。
加入行会后,他们就是行会的一部分,并允许他们看到频道。因此,不再需要登录频道

现在,我认为您想要实现的是每当用户从 offline 状态切换到 online 状态时,在频道/中向用户发送消息。

为此,您可以使用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!");
   }
}
相关问题