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.8 KiB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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 paramMessage)
  29. {
  30. // Cast paramMessage to an IUserMessage, return if the message was a System message.
  31. var msg = paramMessage as IUserMessage;
  32. if (msg == null) return;
  33. // Internal integer, marks where the command begins
  34. int argPos = 0;
  35. // Get the current user (used for Mention parsing)
  36. var currentUser = await client.GetCurrentUserAsync();
  37. // Determine if the message is a command, based on if it starts with '!' or a mention prefix
  38. if (msg.HasCharPrefix('!', ref argPos) || msg.HasMentionPrefix(currentUser, ref argPos))
  39. {
  40. // Execute the command. (result does not indicate a return value,
  41. // rather an object stating if the command executed succesfully)
  42. var result = await _commands.Execute(msg, argPos);
  43. if (!result.IsSuccess)
  44. await msg.Channel.SendMessageAsync(result.ErrorReason);
  45. }
  46. }
  47. }