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.

commands.md 11 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  1. # The Command Service
  2. [Discord.Commands](xref:Discord.Commands) provides an Attribute-based
  3. Command Parser.
  4. ## Setup
  5. To use Commands, you must create a [Commands Service] and a
  6. Command Handler.
  7. Included below is a very bare-bones Command Handler. You can extend
  8. your Command Handler as much as you like, however the below is the
  9. bare minimum.
  10. The CommandService optionally will accept a [CommandServiceConfig],
  11. which _does_ set a few default values for you. It is recommended to
  12. look over the properties in [CommandServiceConfig], and their default
  13. values.
  14. [!code-csharp[Command Handler](samples/command_handler.cs)]
  15. [Command Service]: xref:Discord.Commands.CommandService
  16. [CommandServiceConfig]: xref:Discord.Commands.CommandServiceConfig
  17. ## With Attributes
  18. In 1.0, Commands can be defined ahead of time, with attributes, or
  19. at runtime, with builders.
  20. For most bots, ahead-of-time commands should be all you need, and this
  21. is the recommended method of defining commands.
  22. ### Modules
  23. The first step to creating commands is to create a _module_.
  24. Modules are an organizational pattern that allow you to write your
  25. commands in different classes, and have them automatically loaded.
  26. Discord.Net's implementation of Modules is influenced heavily from
  27. ASP.Net Core's Controller pattern. This means that the lifetime of a
  28. module instance is only as long as the command being invoked.
  29. **Avoid using long-running code** in your modules whereever possible.
  30. You should **not** be implementing very much logic into your modules;
  31. outsource to a service for that.
  32. If you are unfamiliar with Inversion of Control, it is recommended to
  33. read the MSDN article on [IoC] and [Dependency Injection].
  34. To begin, create a new class somewhere in your project, and
  35. inherit the class from [ModuleBase]. This class **must** be `public`.
  36. >[!NOTE]
  37. >[ModuleBase] is an _abstract_ class, meaning that you may extend it
  38. >or override it as you see fit. Your module may inherit from any
  39. >extension of ModuleBase.
  40. By now, your module should look like this:
  41. [!code-csharp[Empty Module](samples/empty-module.cs)]
  42. [IoC]: https://msdn.microsoft.com/en-us/library/ff921087.aspx
  43. [Dependency Injection]: https://msdn.microsoft.com/en-us/library/ff921152.aspx
  44. [ModuleBase]: xref:Discord.Commands.ModuleBase
  45. ### Adding Commands
  46. The next step to creating commands, is actually creating commands.
  47. To create a command, add a method to your module of type `Task`.
  48. Typically, you will want to mark his method as `async`, although it is
  49. not required.
  50. Adding parameters to a command is done by adding parameters to the
  51. parent Task.
  52. For example, to take an integer as an argument, add `int arg`. To take
  53. a user as an argument, add `IUser user`. In 1.0, a command can accept
  54. nearly any type of argument; a full list of types that are parsed by
  55. default can be found in the below section on _Type Readers_.
  56. Parameters, by default, are always required. To make a parameter
  57. optional, give it a default value. To accept a comma-separated list,
  58. set the parameter to `params Type[]`.
  59. Should a parameter include spaces, it **must** be wrapped in quotes.
  60. For example, for a command with a parameter `string food`, you would
  61. execute it with `!favoritefood "Key Lime Pie"`.
  62. If you would like a parameter to parse until the end of a command,
  63. flag the parameter with the [RemainderAttribute]. This will allow a
  64. user to invoke a command without wrapping a parameter in quotes.
  65. Finally, flag your command with the [CommandAttribute]. (You must
  66. specify a name for this command, except for when it is part of a
  67. module group - see below).
  68. [RemainderAttribute]: xref:Discord.Commands.RemainderAttribute
  69. [CommandAttribute]: xref:Discord.Commands.CommandAttribute
  70. ### Command Overloads
  71. You may add overloads of your commands, and the command parser will
  72. automatically pick up on it.
  73. If, for whatever reason, you have too commands which are ambiguous to
  74. each other, you may use the @Discord.Commands.PriorityAttribute to
  75. specify which should be tested before the other.
  76. Priority's are sorted in ascending order; the higher priority will be
  77. called first.
  78. ### CommandContext
  79. Every command can access the execution context through the [Context]
  80. property on [ModuleBase]. CommandContext allows you to access the
  81. message, channel, guild, and user that the command was invoked from,
  82. as well as the underlying discord client the command was invoked from.
  83. You may need to cast these objects to their Socket counterparts (see
  84. the terminology section).
  85. To reply to messages, you may also invoke [ReplyAsync], instead of
  86. accessing the channel through the [Context] and sending a message.
  87. ### Example Module
  88. At this point, your module should look comparable to this example:
  89. [!code-csharp[Example Module](samples/module.cs)]
  90. #### Loading Modules Automatically
  91. The Command Service can automatically discover all classes in an
  92. Assembly that inherit [ModuleBase], and load them.
  93. To opt a module out of auto-loading, flag it with
  94. [DontAutoLoadAttribute]
  95. Invoke [CommandService.AddModulesAsync] to discover modules and
  96. install them.
  97. [DontAutoLoadAttribute]: xref:Discord.Commands.DontAutoLoadAttribute
  98. [CommandService.AddModulesAsync]: xref:Discord_Commands_CommandService#AddModulesAsync_System_Reflection_Assembly_
  99. #### Loading Modules Manually
  100. To manually load a module, invoke [CommandService.AddModuleAsync],
  101. by passing in the generic type of your module, and optionally
  102. a dependency map.
  103. [CommandService.AddModuleAsync]: xref:Discord.Commands.CommandService#Discord_Commands_CommandService_AddModuleAsync__1
  104. ### Module Constructors
  105. Modules are constructed using Dependency Injection. Any parameters
  106. that are placed in the constructor must be injected into an
  107. @Discord.Commands.IDependencyMap. Alternatively, you may accept an
  108. IDependencyMap as an argument and extract services yourself.
  109. ### Module Groups
  110. Module Groups allow you to create a module where commands are prefixed.
  111. To create a group, flag a module with the
  112. @Discord.Commands.GroupAttribute
  113. Module groups also allow you to create **nameless commands**, where the
  114. [CommandAttribute] is configured with no name. In this case, the
  115. command will inherit the name of the group it belongs to.
  116. ### Submodules
  117. Submodules are modules that reside within another module. Typically,
  118. submodules are used to create nested groups (although not required to
  119. create nested groups).
  120. [!code-csharp[Groups and Submodules](samples/groups.cs)]
  121. ## With Builders
  122. **TODO**
  123. ## Dependency Injection
  124. The commands service is bundled with a very barebones Dependency
  125. Injection service for your convienence. It is recommended that
  126. you use DI when writing your modules.
  127. ### Setup
  128. First, you need to create an @Discord.Commands.IDependencyMap.
  129. The library includes @Discord.Commands.DependencyMap to help with
  130. this, however you may create your own IDependencyMap if you wish.
  131. Next, add the dependencies your modules will use to the map.
  132. Finally, pass the map into the `LoadAssembly` method.
  133. Your modules will automatically be loaded with this dependency map.
  134. [!code-csharp[DependencyMap Setup](samples/dependency_map_setup.cs)]
  135. ### Usage in Modules
  136. In the constructor of your module, any parameters will be filled in by
  137. the @Discord.Commands.IDependencyMap you pass into `LoadAssembly`.
  138. >[!NOTE]
  139. >If you accept `CommandService` or `IDependencyMap` as a parameter in
  140. your constructor, these parameters will be filled by the
  141. CommandService the module was loaded from, and the DependencyMap passed
  142. into it, respectively.
  143. [!code-csharp[DependencyMap in Modules](samples/dependency_module.cs)]
  144. # Preconditions
  145. Preconditions serve as a permissions system for your commands. Keep in
  146. mind, however, that they are not limited to _just_ permissions, and
  147. can be as complex as you want them to be.
  148. >[!NOTE]
  149. >Preconditions can be applied to Modules, Groups, or Commands.
  150. ## Bundled Preconditions
  151. Commands ships with four bundled preconditions; you may view their
  152. usages on their API page.
  153. - @Discord.Commands.RequireContextAttribute
  154. - @Discord.Commands.RequireOwnerAttribute
  155. - @Discord.Commands.RequireBotPermissionAttribute
  156. - @Discord.Commands.RequireUserPermissionAttribute
  157. ## Custom Preconditions
  158. To write your own preconditions, create a new class that inherits from
  159. @Discord.Commands.PreconditionAttribute
  160. In order for your precondition to function, you will need to override
  161. [CheckPermissions].
  162. Your IDE should provide an option to fill this in for you.
  163. Return [PreconditionResult.FromSuccess] if the context met the
  164. required parameters, otherwise return [PreconditionResult.FromError],
  165. optionally including an error message.
  166. [!code-csharp[Custom Precondition](samples/require_owner.cs)]
  167. [CheckPermissions]: xref:Discord.Commands.PreconditionAttribute#Discord_Commands_PreconditionAttribute_CheckPermissions_Discord_Commands_CommandContext_Discord_Commands_CommandInfo_Discord_Commands_IDependencyMap_
  168. [PreconditionResult.FromSuccess]: xref:Discord.Commands.PreconditionResult#Discord_Commands_PreconditionResult_FromSuccess
  169. [PreconditionResult.FromError]: xref:Discord.Commands.PreconditionResult#Discord_Commands_PreconditionResult_FromError_System_String_
  170. # Type Readers
  171. Type Readers allow you to parse different types of arguments in
  172. your commands.
  173. By default, the following Types are supported arguments:
  174. - bool
  175. - char
  176. - sbyte/byte
  177. - ushort/short
  178. - uint/int
  179. - ulong/long
  180. - float, double, decimal
  181. - string
  182. - DateTime/DateTimeOffset/TimeSpan
  183. - IMessage/IUserMessage
  184. - IChannel/IGuildChannel/ITextChannel/IVoiceChannel/IGroupChannel
  185. - IUser/IGuildUser/IGroupUser
  186. - IRole
  187. ### Creating a Type Readers
  188. To create a TypeReader, create a new class that imports @Discord and
  189. @Discord.Commands. Ensure your class inherits from @Discord.Commands.TypeReader
  190. Next, satisfy the `TypeReader` class by overriding [Read].
  191. >[!NOTE]
  192. >In many cases, Visual Studio can fill this in for you, using the
  193. >"Implement Abstract Class" IntelliSense hint.
  194. Inside this task, add whatever logic you need to parse the input string.
  195. Finally, return a `TypeReaderResult`. If you were able to successfully
  196. parse the input, return `TypeReaderResult.FromSuccess(parsedInput)`.
  197. Otherwise, return `TypeReaderResult.FromError`.
  198. [Read]: xref:Discord.Commands.TypeReader#Discord_Commands_TypeReader_Read_Discord_Commands_CommandContext_System_String_
  199. #### Sample
  200. [!code-csharp[TypeReaders](samples/typereader.cs)]
  201. ### Installing TypeReaders
  202. TypeReaders are not automatically discovered by the Command Service,
  203. and must be explicitly added. To install a TypeReader, invoke [CommandService.AddTypeReader](xref:Discord.Commands.CommandService#Discord_Commands_CommandService_AddTypeReader__1_Discord_Commands_TypeReader_).