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.

command_handler.cs 2.4 kB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. using System;
  2. using System.Threading.Tasks;
  3. using System.Reflection;
  4. using Discord;
  5. using Discord.WebSocket;
  6. using Discord.Commands;
  7. using Microsoft.Extensions.DependencyInjection;
  8. public class Program
  9. {
  10. private CommandService _commands;
  11. private DiscordSocketClient _client;
  12. private IServiceProvider _services;
  13. // Async Main is a C#7.1 feature.
  14. // Use "static void Main(string[] args) => new Program().StartAsync().GetAwaiter().GetResult();" for C#7 and prior.
  15. static Task Main(string[] args) => new Program().StartAsync();
  16. public async Task StartAsync()
  17. {
  18. _client = new DiscordSocketClient();
  19. _commands = new CommandService();
  20. string token = "bot token here";
  21. _services = new ServiceCollection()
  22. .AddSingleton(_client)
  23. .AddSingleton(_commands)
  24. .BuildServiceProvider();
  25. await InstallCommandsAsync();
  26. await _client.LoginAsync(TokenType.Bot, token);
  27. await _client.StartAsync();
  28. await Task.Delay(-1);
  29. }
  30. public async Task InstallCommandsAsync()
  31. {
  32. // Hook the MessageReceived Event into our Command Handler
  33. _client.MessageReceived += HandleCommandAsync;
  34. // Discover all of the commands in this assembly and load them.
  35. await _commands.AddModulesAsync(Assembly.GetEntryAssembly());
  36. }
  37. public async Task HandleCommandAsync(SocketMessage messageParam)
  38. {
  39. // Don't process the command if it was a System Message
  40. var message = messageParam as SocketUserMessage;
  41. if (message == null) return;
  42. // Create a number to track where the prefix ends and the command begins
  43. int argPos = 0;
  44. // Determine if the message is a command, based on if it starts with '!' or a mention prefix
  45. if (!(message.HasCharPrefix('!', ref argPos) || message.HasMentionPrefix(_client.CurrentUser, ref argPos))) return;
  46. // Create a Command Context
  47. var context = new SocketCommandContext(_client, message);
  48. // Execute the command. (result does not indicate a return value,
  49. // rather an object stating if the command executed successfully)
  50. var result = await _commands.ExecuteAsync(context, argPos, _services);
  51. if (!result.IsSuccess)
  52. await context.Channel.SendMessageAsync(result.ErrorReason);
  53. }
  54. }