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

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