C# Discord Bot Coding:创建一个发送垃圾邮件然后用另一个命令停止的命令

C# Discord Bot Coding: Creating a command that spams messages then stops with another command

我只需要一行代码,它每五秒发送一次垃圾邮件,然后在输入另一个命令后停止。例如,如果用户输入“~raid”,则机器人将每五秒发送一次垃圾邮件 "RAID RAID",并在用户输入“~stop”时停止。如果有人能提供帮助那就太好了。

这是我目前得到的: class 我的机器人 { DiscordClient 不和谐; 命令服务命令;

    public MyBot()
    {
        discord = new DiscordClient(x =>
        {
            x.LogLevel = LogSeverity.Info;
            x.LogHandler = Log;
        });

        discord.UsingCommands(x =>
        {
            x.PrefixChar = '~';
            x.AllowMentionPrefix = true;
        });

        commands = discord.GetService<CommandService>();

        commands.CreateCommand("checked")
            .Do(async (e) =>
            {

        commands.CreateCommand("weewoo")
            .Do(async (e) =>
            {
                await e.Channel.SendMessage("**WEE WOO**");
            });

        discord.ExecuteAndWait(async () =>
        {
            await discord.Connect("discordkeyhere", TokenType.Bot);
        });
    }

    public void Log(object sender, LogMessageEventArgs e)
    {
        Console.WriteLine(e.Message);
    }
}

}

这是一个小例子,你可以如何做到这一点。 在这种情况下,您可以使用 Start 和 Stop 方法从外部启动和停止您的机器人。

class MyBot
{
    public MyBot()
    {
    }

    CancellationTokenSource cts;

    public void Start()
    {
        cts = new CancellationTokenSource();
        Task t = Task.Run(() =>
        {
            while (!cts.IsCancellationRequested)
            {
                Console.WriteLine("RAID RAID");
                Task.Delay(5000).Wait();
            }
        }, cts.Token);
    }

    public void Stop()
    {
        cts?.Cancel();
    }
}

这是测试 MyBot 的代码class

static void Main(string[] args)
    {
        try
        {
            var b = new MyBot();

            while (true)
            {
                var input = Console.ReadLine();
                if (input.Equals("~raid", StringComparison.OrdinalIgnoreCase))
                    b.Start();
                else if (input.Equals("~stop", StringComparison.OrdinalIgnoreCase))
                    b.Stop();
                else if (input.Equals("exit", StringComparison.OrdinalIgnoreCase))
                    break;
                Task.Delay(1000);
            }

        }
        catch (Exception)
        {

            throw;
        }
    }