Advertisement
Guest User

Untitled

a guest
Mar 29th, 2017
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.27 KB | None | 0 0
  1. using System.Threading.Tasks;
  2. using System.Reflection;
  3. using Discord.Commands;
  4. using Discord.WebSocket;
  5. using Discord;
  6.  
  7. namespace MyBot
  8. {
  9. public class CommandHandler
  10. {
  11. private CommandService commands;
  12. private DiscordSocketClient client;
  13. private IDependencyMap map;
  14.  
  15. public async Task Install(IDependencyMap _map)
  16. {
  17. //Create Command Service, Inject it into Dependency Map
  18. client = _map.Get<DiscordSocketClient>();
  19. commands = new CommandService();
  20. _map.Add(commands);
  21. map = _map;
  22.  
  23. await commands.AddModulesAsync(Assembly.GetEntryAssembly());
  24.  
  25. //Send user message to get handled
  26. client.MessageReceived += HandleCommand;
  27.  
  28. client.UserJoined += AnnounceJoinUser;
  29. client.UserLeft += AnnounceLeftUser;
  30. }
  31.  
  32. public async Task AnnounceLeftUser(SocketGuildUser user)
  33. {
  34. var channel = client.GetChannel() as SocketTextChannel;
  35.  
  36. await channel.SendMessageAsync("");
  37. }
  38.  
  39. public async Task AnnounceJoinUser(SocketGuildUser user)
  40. {
  41. var channel = client.GetChannel() as SocketTextChannel;
  42.  
  43. await channel.SendMessageAsync("");
  44. }
  45.  
  46. public async Task HandleCommand(SocketMessage parameterMessage)
  47. {
  48. //Don't handle the command if it is a system message
  49. var message = parameterMessage as SocketUserMessage;
  50. if (message == null) return;
  51.  
  52. //Mark where the prefix ends and the command begins
  53. int argPos = 0;
  54. //Determine if the message has a valid prefix, adjust argPos
  55. if (!(message.HasMentionPrefix(client.CurrentUser, ref argPos) || message.HasCharPrefix('!', ref argPos))) return;
  56.  
  57. //Create a Command Context
  58. var context = new CommandContext(client, message);
  59. //Execute the command, store the result
  60. var result = await commands.ExecuteAsync(context, argPos, map);
  61.  
  62. //If the command failed, notify the user
  63. if (!result.IsSuccess)
  64. await message.Channel.SendMessageAsync($"**Error:** {result.ErrorReason}");
  65. }
  66.  
  67. }
  68. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement