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.3 kB

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