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.

first-steps.cs 4.5 KiB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123
  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. // AsyncMain method and wait until it finishes (which should be never).
  18. new Program().AsyncMain().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 your platform doesn't have native websockets,
  27. // add Discord.Net.Providers.WS4Net from NuGet,
  28. // add the `using` at the top, and uncomment this line:
  29. //WebSocketProvider = WS4NetProvider.Instance
  30. });
  31. }
  32. // Create a named logging handler, so it can be re-used by addons
  33. // that ask for a Func<LogMessage, Task>.
  34. private static Task Logger(LogMessage message)
  35. {
  36. var cc = Console.ForegroundColor;
  37. switch (message.Severity)
  38. {
  39. case LogSeverity.Critical:
  40. case LogSeverity.Error:
  41. Console.ForegroundColor = ConsoleColor.Red;
  42. break;
  43. case LogSeverity.Warning:
  44. Console.ForegroundColor = ConsoleColor.Yellow;
  45. break;
  46. case LogSeverity.Info:
  47. Console.ForegroundColor = ConsoleColor.White;
  48. break;
  49. case LogSeverity.Verbose:
  50. case LogSeverity.Debug:
  51. Console.ForegroundColor = ConsoleColor.DarkGray;
  52. break;
  53. }
  54. Console.WriteLine($"{DateTime.Now,-19} [{message.Severity,8}] {message.Source}: {message.Message}");
  55. Console.ForegroundColor = cc;
  56. return Task.CompletedTask;
  57. }
  58. private async Task AsyncMain()
  59. {
  60. // Subscribe the logging handler.
  61. _client.Log += Logger;
  62. // Centralize the logic for commands into a seperate method.
  63. await InitCommands();
  64. // Login and connect.
  65. await _client.LoginAsync(TokenType.Bot, /* <DON'T HARDCODE YOUR TOKEN> */);
  66. await _client.ConnectAsync();
  67. // Wait infinitely so your bot actually stays connected.
  68. await Task.Delay(-1);
  69. }
  70. private async Task InitCommands()
  71. {
  72. // Repeat this for all the service classes
  73. // and other dependencies that your commands might need.
  74. _map.Add(new SomeServiceClass());
  75. // Either search the program and add all Module classes that can be found:
  76. await _commands.AddModulesAsync(Assembly.GetEntryAssembly());
  77. // Or add Modules manually if you prefer to be a little more explicit:
  78. await _commands.AddModuleAsync<SomeModule>();
  79. // Subscribe a handler to see if a message invokes a command.
  80. _client.MessageReceived += CmdHandler;
  81. }
  82. private async Task CmdHandler(SocketMessage arg)
  83. {
  84. // Bail out if it's a System Message.
  85. var msg = arg as SocketUserMessage;
  86. if (msg == null) return;
  87. // Create a number to track where the prefix ends and the command begins
  88. int pos = 0;
  89. // Replace the '!' with whatever character
  90. // you want to prefix your commands with.
  91. // Uncomment the second half if you also want
  92. // commands to be invoked by mentioning the bot instead.
  93. if (msg.HasCharPrefix('!', ref pos) /* || msg.HasMentionPrefix(msg.Discord.CurrentUser, ref pos) */)
  94. {
  95. // Create a Command Context
  96. var context = new SocketCommandContext(msg.Discord, msg);
  97. // Execute the command. (result does not indicate a return value,
  98. // rather an object stating if the command executed succesfully).
  99. var result = await _commands.ExecuteAsync(context, pos, _map);
  100. // Uncomment the following lines if you want the bot
  101. // to send a message if it failed (not advised for most situations).
  102. //if (!result.IsSuccess && result.Error != CommandError.UnknownCommand)
  103. // await msg.Channel.SendMessageAsync(result.ErrorReason);
  104. }
  105. }
  106. }