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(SocketMessage messageParam)
  29. {
  30. // Don't process the command if it was a System Message
  31. var message = messageParam as SocketUserMessage;
  32. if (message == null) return;
  33. // Create a number to track where the prefix ends and the command begins
  34. int argPos = 0;
  35. // Determine if the message is a command, based on if it starts with '!' or a mention prefix
  36. if (message.HasCharPrefix('!', ref argPos) || message.HasMentionPrefix(client.CurrentUser, ref argPos))
  37. {
  38. // Create a Command Context
  39. var context = new CommandContext(client, message);
  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(context, argPos);
  43. if (!result.IsSuccess)
  44. await msg.Channel.SendMessageAsync(result.ErrorReason);
  45. }
  46. }
  47. }