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.

Program.cs 3.5 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
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. using Discord;
  2. using Discord.Interactions;
  3. using Discord.WebSocket;
  4. using Microsoft.Extensions.Configuration;
  5. using Microsoft.Extensions.DependencyInjection;
  6. using System;
  7. using System.Reflection;
  8. using System.Threading;
  9. using System.Threading.Tasks;
  10. namespace _04_interactions_framework
  11. {
  12. class Program
  13. {
  14. static void Main ( string[] args )
  15. {
  16. // One of the more flexable ways to access the configuration data is to use the Microsoft's Configuration model,
  17. // this way we can avoid hard coding the environment secrets. I opted to use the Json and environment variable providers here.
  18. IConfiguration config = new ConfigurationBuilder()
  19. .AddEnvironmentVariables(prefix: "DC_")
  20. .AddJsonFile("appsettings.json", optional: true)
  21. .Build();
  22. RunAsync(config).GetAwaiter().GetResult();
  23. }
  24. static async Task RunAsync (IConfiguration configuration )
  25. {
  26. // Dependency injection is a key part of the Interactions framework but it needs to be disposed at the end of the app's lifetime.
  27. using var services = ConfigureServices(configuration);
  28. var client = services.GetRequiredService<DiscordSocketClient>();
  29. var commands = services.GetRequiredService<InteractionService>();
  30. client.Log += LogAsync;
  31. commands.Log += LogAsync;
  32. // Slash Commands and Context Commands are can be automatically registered, but this process needs to happen after the client enters the READY state.
  33. // Since Global Commands take around 1 hour to register, we should use a test guild to instantly update and test our commands. To determine the method we should
  34. // register the commands with, we can check whether we are in a DEBUG environment and if we are, we can register the commands to a predetermined test guild.
  35. client.Ready += async ( ) =>
  36. {
  37. if (IsDebug())
  38. // Id of the test guild can be provided from the Configuration object
  39. await commands.RegisterCommandsToGuildAsync(configuration.GetValue<ulong>("testGuild"), true);
  40. else
  41. await commands.RegisterCommandsGloballyAsync(true);
  42. };
  43. // Here we can initialize the service that will register and execute our commands
  44. await services.GetRequiredService<CommandHandler>().InitializeAsync();
  45. // Bot token can be provided from the Configuration object we set up earlier
  46. await client.LoginAsync(TokenType.Bot, configuration["token"]);
  47. await client.StartAsync();
  48. await Task.Delay(Timeout.Infinite);
  49. }
  50. static Task LogAsync(LogMessage message)
  51. {
  52. Console.WriteLine(message.ToString());
  53. return Task.CompletedTask;
  54. }
  55. static ServiceProvider ConfigureServices ( IConfiguration configuration )
  56. {
  57. return new ServiceCollection()
  58. .AddSingleton(configuration)
  59. .AddSingleton<DiscordSocketClient>()
  60. .AddSingleton(x => new InteractionService(x.GetRequiredService<DiscordSocketClient>()))
  61. .AddSingleton<CommandHandler>()
  62. .BuildServiceProvider();
  63. }
  64. static bool IsDebug ( )
  65. {
  66. #if DEBUG
  67. return true;
  68. #else
  69. return false;
  70. #endif
  71. }
  72. }
  73. }