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

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