You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

structure.cs 4.7 KiB

8 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128
  1. using System;
  2. using System.Reflection;
  3. using System.Threading.Tasks;
  4. using Discord;
  5. using Discord.Commands;
  6. using Discord.WebSocket;
  7. class Program
  8. {
  9. private readonly DiscordSocketClient _client;
  10. // Keep the CommandService and IDependencyMap around for use with commands.
  11. private readonly IDependencyMap _map = new DependencyMap();
  12. private readonly CommandService _commands = new CommandService();
  13. // Program entry point
  14. static void Main(string[] args)
  15. {
  16. // Call the Program constructor, followed by the
  17. // MainAsync method and wait until it finishes (which should be never).
  18. new Program().MainAsync().GetAwaiter().GetResult();
  19. }
  20. private Program()
  21. {
  22. _client = new DiscordSocketClient(new DiscordSocketConfig
  23. {
  24. // How much logging do you want to see?
  25. LogLevel = LogSeverity.Info,
  26. // If you or another service needs to do anything with messages
  27. // (eg. checking Reactions), you should probably
  28. // set the MessageCacheSize here.
  29. //MessageCacheSize = 50,
  30. // If your platform doesn't have native websockets,
  31. // add Discord.Net.Providers.WS4Net from NuGet,
  32. // add the `using` at the top, and uncomment this line:
  33. //WebSocketProvider = WS4NetProvider.Instance
  34. });
  35. }
  36. // Create a named logging handler, so it can be re-used by addons
  37. // that ask for a Func<LogMessage, Task>.
  38. private static Task Logger(LogMessage message)
  39. {
  40. var cc = Console.ForegroundColor;
  41. switch (message.Severity)
  42. {
  43. case LogSeverity.Critical:
  44. case LogSeverity.Error:
  45. Console.ForegroundColor = ConsoleColor.Red;
  46. break;
  47. case LogSeverity.Warning:
  48. Console.ForegroundColor = ConsoleColor.Yellow;
  49. break;
  50. case LogSeverity.Info:
  51. Console.ForegroundColor = ConsoleColor.White;
  52. break;
  53. case LogSeverity.Verbose:
  54. case LogSeverity.Debug:
  55. Console.ForegroundColor = ConsoleColor.DarkGray;
  56. break;
  57. }
  58. Console.WriteLine($"{DateTime.Now,-19} [{message.Severity,8}] {message.Source}: {message.Message}");
  59. Console.ForegroundColor = cc;
  60. return Task.CompletedTask;
  61. }
  62. private async Task MainAsync()
  63. {
  64. // Subscribe the logging handler.
  65. _client.Log += Logger;
  66. // Centralize the logic for commands into a seperate method.
  67. await InitCommands();
  68. // Login and connect.
  69. await _client.LoginAsync(TokenType.Bot, /* <DON'T HARDCODE YOUR TOKEN> */);
  70. await _client.StartAsync();
  71. // Wait infinitely so your bot actually stays connected.
  72. await Task.Delay(-1);
  73. }
  74. private async Task InitCommands()
  75. {
  76. // Repeat this for all the service classes
  77. // and other dependencies that your commands might need.
  78. _map.Add(new SomeServiceClass());
  79. // Either search the program and add all Module classes that can be found:
  80. await _commands.AddModulesAsync(Assembly.GetEntryAssembly());
  81. // Or add Modules manually if you prefer to be a little more explicit:
  82. await _commands.AddModuleAsync<SomeModule>();
  83. // Subscribe a handler to see if a message invokes a command.
  84. _client.MessageReceived += HandleCommandAsync;
  85. }
  86. private async Task HandleCommandAsync(SocketMessage arg)
  87. {
  88. // Bail out if it's a System Message.
  89. var msg = arg as SocketUserMessage;
  90. if (msg == null) return;
  91. // Create a number to track where the prefix ends and the command begins
  92. int pos = 0;
  93. // Replace the '!' with whatever character
  94. // you want to prefix your commands with.
  95. // Uncomment the second half if you also want
  96. // commands to be invoked by mentioning the bot instead.
  97. if (msg.HasCharPrefix('!', ref pos) /* || msg.HasMentionPrefix(msg.Discord.CurrentUser, ref pos) */)
  98. {
  99. // Create a Command Context
  100. var context = new SocketCommandContext(msg.Discord, msg);
  101. // Execute the command. (result does not indicate a return value,
  102. // rather an object stating if the command executed succesfully).
  103. var result = await _commands.ExecuteAsync(context, pos, _map);
  104. // Uncomment the following lines if you want the bot
  105. // to send a message if it failed (not advised for most situations).
  106. //if (!result.IsSuccess && result.Error != CommandError.UnknownCommand)
  107. // await msg.Channel.SendMessageAsync(result.ErrorReason);
  108. }
  109. }
  110. }