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

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