2017-07-19 25 views
1

我只需要一個工作線程的代碼,每五秒傳遞一條消息,然後停止後,另一個命令輸入。就像一個例子,如果用戶輸入「〜raid」,那麼機器人將每隔5秒發送一次「RAID RAID」並在用戶停止時停止。如果任何人都可以提供幫助,那就太棒了。C#不一致的Bot編碼:創建一個命令,垃圾郵件,然後停止與另一個命令

這是我到目前爲止: class MyBot { DiscordClient discord; CommandService命令;

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); 
    } 
} 

}

+0

問題是執行停止命令的代碼? –

+0

是的,以及如何使它每隔5秒重複自己的消息 – user8328934

回答

0

這裏是一個小例子,你如何能做到這一點。 在這種情況下,您可以使用Start和Stop方法從外部啓動和停止您的bot。

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類

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; 
     } 
    } 
+0

這將與Discord一起工作?如果確實如此,你可以使用代碼工作嗎?我不想把它搞砸xD – user8328934

+0

我正在使用visual studio btw – user8328934

+0

該代碼僅僅是一個例子。您必須調整代碼才能使其在特定應用程序中運行。你只需要從用戶那裏得到命令並對它們做出反應。希望有所幫助。 – Ben