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 1.6 KiB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. using System.Threading.Tasks;
  2. using System.Reflection;
  3. using Discord;
  4. using Discord.Commands;
  5. public class Program
  6. {
  7. private CommandService commands;
  8. private DiscordSocketClient client;
  9. static void Main(string[] args) => new Program().Start().GetAwaiter().GetResult();
  10. public async Task Start()
  11. {
  12. client = new DiscordSocketClient();
  13. commands = new CommandService();
  14. string token = "bot token here";
  15. await InstallCommands();
  16. await client.LoginAsync(TokenType.Bot, token);
  17. await client.ConnectAsync();
  18. await Task.Delay(-1);
  19. }
  20. public async Task InstallCommands()
  21. {
  22. // Hook the MessageReceived Event into our Command Handler
  23. client.MessageReceived += HandleCommand;
  24. // Discover all of the commands in this assembly and load them.
  25. await commands.LoadAssembly(Assembly.GetEntryAssembly());
  26. }
  27. public async Task HandleCommand(IMessage msg)
  28. {
  29. // Internal integer, marks where the command begins
  30. int argPos = 0;
  31. // Get the current user (used for Mention parsing)
  32. var currentUser = await client.GetCurrentUserAsync();
  33. // Determine if the message is a command, based on if it starts with '!' or a mention prefix
  34. if (msg.HasCharPrefix('!', ref argPos) || msg.HasMentionPrefix(currentUser, ref argPos))
  35. {
  36. // Execute the command. (result does not indicate a return value,
  37. // rather an object stating if the command executed succesfully)
  38. var result = await _commands.Execute(msg, argPos);
  39. if (!result.IsSuccess)
  40. await msg.Channel.SendMessageAsync(result.ErrorReason);
  41. }
  42. }
  43. }