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.

CommandHandler.cs 5.3 KiB

Interaction Command Service (#52) * init * attribute rename * added docs * Revert "added docs" This reverts commit 30aa0c4ef7e190a726ec2cb3a183da5e2f9b07d9. * added basic docs * Switched to nested modules for method grouping, changed command traversal method * interface now declares the helper methods * added new method with predicate parameter * added config option for deleting the "thinking" state of unhandled commands * Slash Module Base now exposes helper methods for interacting with the underlying Interaction * Revert "interface now declares the helper methods" This reverts commit 541b0be93530e880c482962d41cd6e0cefa4e771. * IDiscordInteraction now declares the helper methods * new cancelable wait interaction method * added support for user created command types * added option type 'number', added write method to typereaders * added enum and timespan typereaders * revert * added interface method declarations * inline docs * revert interface changes * current user id assignment in sharded client * added wildcards to interactions, tweaks * tweaks on interaction wild card pattern * Pre-app menu * fixed CurrentUserId and added application command events * made event listener persistent * Sharded Client Application Command Events and CurrentUserId Issue (#105) * added interface method declarations * inline docs * current user id assignment in sharded client * fixed CurrentUserId and added application command events * made event listener persistent * removed option type converter, task offloaded to typereaders * added "deleteOGResponse" method to module base * Upstream fetch for Discord-Net-Labs/release/3.x * solved merge conflicts * removed merge artifacts * added new Context Command attributes * added Conxtext Command info classes and changed the naming scheme for the existing classes * added IgnoreGroupNames prop to command attributes * added ContextCommand builder * moved command builders to internal * added ContextCommand methods to the command service * command service now uses InteractionHelper to register commands * bug fixes and refactorings * docs update * added inline docs to public members * added inline docs * added method name property to command infos * added inline docs * changed the execution callback to a declared delegate * createInstance delegate is now created only once per module * declared the ExecuteCallback delegate * introduced a way to modify the command permissions * changed method names * added optional compiled lambda module builder * added the missing sync execution option * moved run mode selection to the base class * info class refactorings * switched to compiled lambda based method invoke * command refactorings * added docs * removed untended class * bug fixes * minor refactorings * reflection changes * bug fix for interaction parameters * commands and modules now groups the preconditons on building * added default permission to context commands * added DontAutoRegister attribute * renamed TypeReader to TypeConverter * added docs to TypeConverterResult, made ISlashModuleBase public * namespace and project change * added inline docs file * renamed ExecuteComponentCommand method * added scoped service support to the dependency injection model * fixed premature disposal of scoped services * extended the scope to cover the precondition checking methods * removed slash command related preconditions from core lib * added sample application * precondition checks are now executed according to the command RunMode * reverting the conflicting changes * reverted SocketInteraction * reverting more conflicts * added indentations to inline docs * implemented change requests * updated the sample app * moved builders to public * added indentations to typeconverter docs * renamed old componentCommandExecuted event * bug fix for generic typeconverters * Revert "bug fix for generic typeconverters" This reverts commit fcc61957deb5dfc17c41367f1c7c72d27024b0ee. * bug fix for context commands * code cleanup * removed public module build method * modev OnModuleBuilding execution inside the module build method * added try-catch blocks encapsulating arg generation * fixed parameter preconditions not raising commandExecuted event * removed OnModuleBuilding execution from ModuleClassBuilder * removed setters from Precondition ErrorMessages * added methods to interaction service for creating user defined modules * added IParameterInfo parameter to TypeConverter.Write * changed the target frameworks * DefaultValueConverter bug fix * GenerateArgs refactorings * WaitForMessageComponent now relies message id * added ChannelTypes support * added ChannelTypes support * fix build error for new lib version * added ToString method to CommandInfo * added ToString method to CommandInfo * Fix index out of bounds error for new non-null slash command option collection * enum converter rework * added user extendable types to command context and module base * added regex anchors to ensure pattern matches the whole string * incomplete guides * add missing ignoreGroupNames assignment for ComponentInteraction * typeconverters now seperate pascal casing parameter names * fix missing IServiceScopefactory ? * Revert "typeconverters now seperate pascal casing parameter names" This reverts commit 141300f3d2c244fc6795999d910462939d16a2e1. * moved the option name pascal casing seperator to RestUtils * fix component command arg generation * removed , from default command delimiters * updated the regex to match every non whitespace value * added Autocomplete interaction support and updated the regex to match every non whitespace value * replaced the posix class with range exps in pascal casing seperator * added inline docs to autocompleter related classes * added regex metacharacter escape to wildcard patterns * added null check to Regex EscapeExcluding * added .net5.0 support and updated the project package * added .net5.0 support and updated the project package * add dependency injection to autocompleters * add net6.0 * bump versions * bug fix: pascal casing parameters are not assigned * rework autocomplete commands to accept command and parameter names seperatly * rename *InteractionCommandContext to *InteractionContext * add max-min value support to number type slash command options * add hide attribute to deafult enum converter * add inline docs * guides update: min/max value and autocomplete interactions * remove net6.0 support * add inline doc to Config.EnableAutocompleters * add autocompleters guide * added attribute usage to min/max value * implement rest based interactions * add handling logic for rest based interactions * update default TypeConverters to accommodate rest based interactions * added interaction specific interfaces * fix build error * implement change requests * bump metapackage version * replace concrete interface types with interfaces in command execution logic * fix min/max value attribute target * add rest specific interaction module for creating interaction responses for rest based interactions within the module * update rest callback to accept an interaction context parameter * clean up RestResponseCallback implementation artifacts * fix command registration bug when using the sharded socket client * update docs * fix build errors * fix slash command depth check * implement requested changes * fix build error * the grand finale * the grand finale Co-authored-by: quin lynch <lynchquin@gmail.com>
3 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146
  1. using Discord;
  2. using Discord.Interactions;
  3. using Discord.WebSocket;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Linq;
  7. using System.Reflection;
  8. using System.Text;
  9. using System.Threading.Tasks;
  10. namespace _04_interactions_framework
  11. {
  12. public class CommandHandler
  13. {
  14. private readonly DiscordSocketClient _client;
  15. private readonly InteractionService _commands;
  16. private readonly IServiceProvider _services;
  17. public CommandHandler(DiscordSocketClient client, InteractionService commands, IServiceProvider services)
  18. {
  19. _client = client;
  20. _commands = commands;
  21. _services = services;
  22. }
  23. public async Task InitializeAsync ( )
  24. {
  25. // Add the public modules that inherit InteractionModuleBase<T> to the InteractionService
  26. await _commands.AddModulesAsync(Assembly.GetEntryAssembly(), _services);
  27. // Process the InteractionCreated payloads to execute Interactions commands
  28. _client.InteractionCreated += HandleInteraction;
  29. // Process the command execution results
  30. _commands.SlashCommandExecuted += SlashCommandExecuted;
  31. _commands.ContextCommandExecuted += ContextCommandExecuted;
  32. _commands.ComponentCommandExecuted += ComponentCommandExecuted;
  33. }
  34. private Task ComponentCommandExecuted (ComponentCommandInfo arg1, Discord.IInteractionContext arg2, IResult arg3)
  35. {
  36. if (!arg3.IsSuccess)
  37. {
  38. switch (arg3.Error)
  39. {
  40. case InteractionCommandError.UnmetPrecondition:
  41. // implement
  42. break;
  43. case InteractionCommandError.UnknownCommand:
  44. // implement
  45. break;
  46. case InteractionCommandError.BadArgs:
  47. // implement
  48. break;
  49. case InteractionCommandError.Exception:
  50. // implement
  51. break;
  52. case InteractionCommandError.Unsuccessful:
  53. // implement
  54. break;
  55. default:
  56. break;
  57. }
  58. }
  59. return Task.CompletedTask;
  60. }
  61. private Task ContextCommandExecuted (ContextCommandInfo arg1, Discord.IInteractionContext arg2, IResult arg3)
  62. {
  63. if (!arg3.IsSuccess)
  64. {
  65. switch (arg3.Error)
  66. {
  67. case InteractionCommandError.UnmetPrecondition:
  68. // implement
  69. break;
  70. case InteractionCommandError.UnknownCommand:
  71. // implement
  72. break;
  73. case InteractionCommandError.BadArgs:
  74. // implement
  75. break;
  76. case InteractionCommandError.Exception:
  77. // implement
  78. break;
  79. case InteractionCommandError.Unsuccessful:
  80. // implement
  81. break;
  82. default:
  83. break;
  84. }
  85. }
  86. return Task.CompletedTask;
  87. }
  88. private Task SlashCommandExecuted (SlashCommandInfo arg1, Discord.IInteractionContext arg2, IResult arg3)
  89. {
  90. if (!arg3.IsSuccess)
  91. {
  92. switch (arg3.Error)
  93. {
  94. case InteractionCommandError.UnmetPrecondition:
  95. // implement
  96. break;
  97. case InteractionCommandError.UnknownCommand:
  98. // implement
  99. break;
  100. case InteractionCommandError.BadArgs:
  101. // implement
  102. break;
  103. case InteractionCommandError.Exception:
  104. // implement
  105. break;
  106. case InteractionCommandError.Unsuccessful:
  107. // implement
  108. break;
  109. default:
  110. break;
  111. }
  112. }
  113. return Task.CompletedTask;
  114. }
  115. private async Task HandleInteraction (SocketInteraction arg)
  116. {
  117. try
  118. {
  119. // Create an execution context that matches the generic type parameter of your InteractionModuleBase<T> modules
  120. var ctx = new SocketInteractionContext(_client, arg);
  121. await _commands.ExecuteCommandAsync(ctx, _services);
  122. }
  123. catch (Exception ex)
  124. {
  125. Console.WriteLine(ex);
  126. // If a Slash Command execution fails it is most likely that the original interaction acknowledgement will persist. It is a good idea to delete the original
  127. // response, or at least let the user know that something went wrong during the command execution.
  128. if(arg.Type == InteractionType.ApplicationCommand)
  129. await arg.GetOriginalResponseAsync().ContinueWith(async (msg) => await msg.Result.DeleteAsync());
  130. }
  131. }
  132. }
  133. }