Discord.NET C# MessageReceived 被调用太多次

Discord.NET C# MessageReceived getting called too many times

我尝试了这段代码,它是我从 discord.net 的 github 页面复制的,这段代码工作得很好:

using Discord;
using Discord.WebSocket;
using System;
using System.Threading.Tasks;


namespace Adivisor
{
public class Program
{
    private DiscordSocketClient _client;
    public static void Main(string[] args) => new Program().MainAsync().GetAwaiter().GetResult();

    public async Task MainAsync()
    {
        _client = new DiscordSocketClient();
        _client.Log += Log;
        _client.MessageReceived += MessageReceived;

        string token = ":P"; 

        await _client.LoginAsync(TokenType.Bot, token);
        await _client.StartAsync();
        await Task.Delay(-1);

    }

    private async Task MessageReceived(SocketMessage message)
    {
        if (message.Content == "!hi")
        {
            await message.Channel.SendMessageAsync("Hello!");
        }
    }

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

   }
}

在我对 MessageReceived 进行了一些编辑后,它现在看起来像这样:

private async Task MessageReceived(SocketMessage message)
{
    await message.Channel.SendMessageAsync("Hello!");
}

实际上我只是删除了 if,但是有一个巨大的差异,似乎没有 if MessageReceived 会被永远调用...

就像Xiaoy312所说的,每当你的机器人发送消息时,它也会收到它自己的消息。
(这同样适用于您自己的用户帐户!尝试在聊天中执行 @everyone ping,您会看到它被突出显示,即使它是您发送的。)

您可以通过这样做让您的机器人忽略其他机器人消息:

//Ignores all bots messages
//Where message is your received SocketMessage
if (message.Author.IsBot) { return; }

或者您可以让它检查消息的作者 ID 是否等于机器人的 ID。您可以查看文档 here.