如何在不诉诸Task.Delay的情况下保持Discord Bot的登录状态?

时间:2020-02-04 16:56:08

标签: c# task discord discord.net

我当前正在运行Discord机器人,但是除非将await Task.Delay(-1)添加到用于登录的方法中,否则它不会保持登录状态。我怀疑这会在代码的后续部分引起我一些问题。

这是我的联系方式:

        public override async Task ConnectToClientAsync()
        {
            await this._client.LoginAsync(TokenType.Bot, this.Token);
            await this._client.StartAsync();
            await Task.Delay(-1);
        }

如何不使用Task.Delay(-1)使我的机器人保持在线状态?它只是登录,成功完成后便会终止程序(因为它不会保持登录状态)没有这个延迟)。

主要

    class Program
    {
        static async Task Main(string[] args)
        {
            var newBot = new WelcomeBot(674094599903641628);
            await newBot.LaunchBot();
        }
    }

WelcomeBot

    public class WelcomeBot : BasicBot, IMessageWriter, IMessageReader
    {

        private ulong _channelId;

        public WelcomeBot(ulong channelId) : base()
        {
            this._client = new DiscordSocketClient();
            this._channelId = channelId;

            ConfigureBotFunctionality();

        }

        private void ConfigureBotFunctionality()
        {
            Interact_UserEntryAndExit();
        }

        private void Interact_UserEntryAndExit()
        {
            this._client.UserJoined += AnnounceUserJoiningAsync;
            this._client.UserLeft += AnnounceUserLeavingAsync;
            this._client.Connected += OnConnectAnnouncementAsync;
        }

        public async Task LaunchBot()
        {
            await ConnectToClientAsync();
        }

        public override async Task ConnectToClientAsync()
        {
            await this._client.LoginAsync(TokenType.Bot, this.Token);
            await this._client.StartAsync();
            await Task.Delay(-1);
        }

        private async Task OnConnectAnnouncementAsync()
        {
            // ..
        }

        private async Task AnnounceUserLeavingAsync(SocketGuildUser leavingUser)
        {
            //..
        }

        private async Task AnnounceUserJoiningAsync(SocketGuildUser joinedUser)
        {
            //..
        }

        // Other functions.
   }

1 个答案:

答案 0 :(得分:0)

只需添加一个小的延迟,即300或400左右。