在第二次使用任何Async api后再次发生故障

我把我的Discord机器人放在Rasberry Pi上,但现在我遇到了问题 . 当我尝试使用命令时,它第一次工作 . 但是第二次使用它,而不是工作它只是说“MessageReceived处理程序正在阻止网关任务 . ” . 不久后,它说

System.Exception:Server错过了System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()[0x0000c]中的最后一次心跳:在System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(System.Threading.Tasks.Task任务)中的0:[0x0003e] in:0 at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(System.Threading.Tasks.Task task)[0x00028] in:0 at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(System.Threading.Tasks.Task task)[ 0x00008] in:0 at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1 ConfiguredTaskAwaiter [TResult] .GetResult()[0x00000] in:0 at Discord.ConnectionManager <> c__DisplayClass28_0 <b__0> d.MoveNext()[0x0014b] in:0

和断开连接,尝试重新连接一些但每次都出错 . 我没有使用命令界面,但我使用的是async / await . 它在我的普通电脑上运行得非常好,只能打破我的Pi .

using Discord;
using Discord.WebSocket;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace GlurrrBotDiscord
{
    public class Program
    {
        DiscordSocketClient client;

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

        public async Task MainAsync()
        {
            client = new DiscordSocketClient();

            try
            {
                using(StreamReader sr = new StreamReader("botcode.txt"))
                {
                    string code = sr.ReadLine();
                    await client.LoginAsync(TokenType.Bot, code);
                }
            }
            catch(Exception e)
            {
                Console.WriteLine("Code not found");
                Console.WriteLine(e.Message);
            }

            await client.StartAsync();
            await client.SetGameAsync("praise");

            client.MessageReceived += handleMessage;

            await Task.Delay(-1);
        }

        private async Task handleMessage(SocketMessage msg)
        {
            Console.WriteLine(msg.Author + " : " + msg.Content);

            if(msg.Content.Contains("/leave"))
            {
                var embed = new EmbedBuilder() {
                    Title = msg.Author + " has left",
                    Description = msg.Author + " has left the Discord and would like everyone to know they did. They are very triggered.",
                    Color = Color.DarkRed,
                };

                await msg.Channel.SendMessageAsync("", false, embed);
            }
        }
    }
}

完整代码位于https://github.com/Silthreent/Glurrr-Discord-Bot

回答(2)

2 years ago

Server missed last heartbeat atA MessageReceived handler is blocking the gateway task 的结果,这意味着您正在运行的命令之一使用网关,并使其占用足够长的时间以使连接超时(~30秒) .

要解决此问题,您必须实现a command handler,这是基本机器人实现的一部分 . 这将允许您运行命令async,防止线程阻塞 . 您还可以查看bot sample以查看实施情况

2 years ago

我通过切换到DiscordSharpPlus而不是使用DiscordNet来修复它,但实际上并不知道问题是什么 .