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.9 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. private DependencyMap map;
  11. static void Main(string[] args) => new Program().Start().GetAwaiter().GetResult();
  12. public async Task Start()
  13. {
  14. client = new DiscordSocketClient();
  15. commands = new CommandService();
  16. string token = "bot token here";
  17. map = new DependencyMap();
  18. await InstallCommands();
  19. await client.LoginAsync(TokenType.Bot, token);
  20. await client.ConnectAsync();
  21. await Task.Delay(-1);
  22. }
  23. public async Task InstallCommands()
  24. {
  25. // Hook the MessageReceived Event into our Command Handler
  26. client.MessageReceived += HandleCommand;
  27. // Discover all of the commands in this assembly and load them.
  28. await commands.AddModulesAsync(Assembly.GetEntryAssembly());
  29. }
  30. public async Task HandleCommand(SocketMessage messageParam)
  31. {
  32. // Don't process the command if it was a System Message
  33. var message = messageParam as SocketUserMessage;
  34. if (message == null) return;
  35. // Create a number to track where the prefix ends and the command begins
  36. int argPos = 0;
  37. // Determine if the message is a command, based on if it starts with '!' or a mention prefix
  38. if (!(message.HasCharPrefix('!', ref argPos) || message.HasMentionPrefix(client.CurrentUser, ref argPos))) return;
  39. // Create a Command Context
  40. var context = new CommandContext(client, message);
  41. // Execute the command. (result does not indicate a return value,
  42. // rather an object stating if the command executed succesfully)
  43. var result = await commands.ExecuteAsync(context, argPos, map);
  44. if (!result.IsSuccess)
  45. await context.Channel.SendMessageAsync(result.ErrorReason);
  46. }
  47. }