Discord.NET C#MessageReceived被调用次数过多

时间:2017-08-31 19:09:59

标签: c# discord discord.net

我尝试了这个代码,我从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永远被调用...

1 个答案:

答案 0 :(得分:1)

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

你可以通过这样做让你的机器人忽略它的其他机器人信息:

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

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