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 KiB

8 years ago
8 years ago
8 years ago
8 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  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`1
  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 this 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. Different types of Contexts may be specified using the generic variant
  84. of [ModuleBase]. When using a [SocketCommandContext], for example,
  85. the properties on this context will already be Socket entities. You
  86. will not need to cast them.
  87. To reply to messages, you may also invoke [ReplyAsync], instead of
  88. accessing the channel through the [Context] and sending a message.
  89. [Context]: xref:Discord.Commands.ModuleBase`1#Discord_Commands_ModuleBase_1_Context
  90. [SocketCommandContext]: xref:Discord.Commands.SocketCommandContext
  91. >![WARNING]
  92. >Contexts should **NOT** be mixed! You cannot have one module that
  93. >uses CommandContext, and another that uses SocketCommandContext.
  94. ### Example Module
  95. At this point, your module should look comparable to this example:
  96. [!code-csharp[Example Module](samples/module.cs)]
  97. #### Loading Modules Automatically
  98. The Command Service can automatically discover all classes in an
  99. Assembly that inherit [ModuleBase], and load them.
  100. To opt a module out of auto-loading, flag it with
  101. [DontAutoLoadAttribute]
  102. Invoke [CommandService.AddModulesAsync] to discover modules and
  103. install them.
  104. [DontAutoLoadAttribute]: xref:Discord.Commands.DontAutoLoadAttribute
  105. [CommandService.AddModulesAsync]: xref:Discord_Commands_CommandService#Discord_Commands_CommandService_AddModulesAsync_Assembly_
  106. #### Loading Modules Manually
  107. To manually load a module, invoke [CommandService.AddModuleAsync],
  108. by passing in the generic type of your module, and optionally
  109. a dependency map.
  110. [CommandService.AddModuleAsync]: xref:Discord.Commands.CommandService#Discord_Commands_CommandService_AddModuleAsync__1
  111. ### Module Constructors
  112. Modules are constructed using Dependency Injection. Any parameters
  113. that are placed in the constructor must be injected into an
  114. @Discord.Commands.IDependencyMap. Alternatively, you may accept an
  115. IDependencyMap as an argument and extract services yourself.
  116. ### Module Properties
  117. Modules with public settable properties will have them injected after module
  118. construction.
  119. ### Module Groups
  120. Module Groups allow you to create a module where commands are prefixed.
  121. To create a group, flag a module with the
  122. @Discord.Commands.GroupAttribute
  123. Module groups also allow you to create **nameless commands**, where the
  124. [CommandAttribute] is configured with no name. In this case, the
  125. command will inherit the name of the group it belongs to.
  126. ### Submodules
  127. Submodules are modules that reside within another module. Typically,
  128. submodules are used to create nested groups (although not required to
  129. create nested groups).
  130. [!code-csharp[Groups and Submodules](samples/groups.cs)]
  131. ## With Builders
  132. **TODO**
  133. ## Dependency Injection
  134. The commands service is bundled with a very barebones Dependency
  135. Injection service for your convienence. It is recommended that
  136. you use DI when writing your modules.
  137. ### Setup
  138. First, you need to create an @Discord.Commands.IDependencyMap.
  139. The library includes @Discord.Commands.DependencyMap to help with
  140. this, however you may create your own IDependencyMap if you wish.
  141. Next, add the dependencies your modules will use to the map.
  142. Finally, pass the map into the `LoadAssembly` method.
  143. Your modules will automatically be loaded with this dependency map.
  144. [!code-csharp[DependencyMap Setup](samples/dependency_map_setup.cs)]
  145. ### Usage in Modules
  146. In the constructor of your module, any parameters will be filled in by
  147. the @Discord.Commands.IDependencyMap you pass into `LoadAssembly`.
  148. Any publicly settable properties will also be filled in the same manner.
  149. >[!NOTE]
  150. > Annotating a property with the [DontInject] attribute will prevent it from
  151. being injected.
  152. >[!NOTE]
  153. >If you accept `CommandService` or `IDependencyMap` as a parameter in
  154. your constructor or as an injectable property, these entries will be filled
  155. by the CommandService the module was loaded from, and the DependencyMap passed
  156. into it, respectively.
  157. [!code-csharp[DependencyMap in Modules](samples/dependency_module.cs)]
  158. # Preconditions
  159. Preconditions serve as a permissions system for your commands. Keep in
  160. mind, however, that they are not limited to _just_ permissions, and
  161. can be as complex as you want them to be.
  162. >[!NOTE]
  163. >Preconditions can be applied to Modules, Groups, or Commands.
  164. ## Bundled Preconditions
  165. Commands ships with four bundled preconditions; you may view their
  166. usages on their API page.
  167. - @Discord.Commands.RequireContextAttribute
  168. - @Discord.Commands.RequireOwnerAttribute
  169. - @Discord.Commands.RequireBotPermissionAttribute
  170. - @Discord.Commands.RequireUserPermissionAttribute
  171. ## Custom Preconditions
  172. To write your own preconditions, create a new class that inherits from
  173. @Discord.Commands.PreconditionAttribute
  174. In order for your precondition to function, you will need to override
  175. [CheckPermissions].
  176. Your IDE should provide an option to fill this in for you.
  177. Return [PreconditionResult.FromSuccess] if the context met the
  178. required parameters, otherwise return [PreconditionResult.FromError],
  179. optionally including an error message.
  180. [!code-csharp[Custom Precondition](samples/require_owner.cs)]
  181. [CheckPermissions]: xref:Discord.Commands.PreconditionAttribute#Discord_Commands_PreconditionAttribute_CheckPermissions_Discord_Commands_CommandContext_Discord_Commands_CommandInfo_Discord_Commands_IDependencyMap_
  182. [PreconditionResult.FromSuccess]: xref:Discord.Commands.PreconditionResult#Discord_Commands_PreconditionResult_FromSuccess
  183. [PreconditionResult.FromError]: xref:Discord.Commands.PreconditionResult#Discord_Commands_PreconditionResult_FromError_System_String_
  184. # Type Readers
  185. Type Readers allow you to parse different types of arguments in
  186. your commands.
  187. By default, the following Types are supported arguments:
  188. - bool
  189. - char
  190. - sbyte/byte
  191. - ushort/short
  192. - uint/int
  193. - ulong/long
  194. - float, double, decimal
  195. - string
  196. - DateTime/DateTimeOffset/TimeSpan
  197. - IMessage/IUserMessage
  198. - IChannel/IGuildChannel/ITextChannel/IVoiceChannel/IGroupChannel
  199. - IUser/IGuildUser/IGroupUser
  200. - IRole
  201. ### Creating a Type Readers
  202. To create a TypeReader, create a new class that imports @Discord and
  203. @Discord.Commands. Ensure your class inherits from @Discord.Commands.TypeReader
  204. Next, satisfy the `TypeReader` class by overriding [Read].
  205. >[!NOTE]
  206. >In many cases, Visual Studio can fill this in for you, using the
  207. >"Implement Abstract Class" IntelliSense hint.
  208. Inside this task, add whatever logic you need to parse the input string.
  209. Finally, return a `TypeReaderResult`. If you were able to successfully
  210. parse the input, return `TypeReaderResult.FromSuccess(parsedInput)`.
  211. Otherwise, return `TypeReaderResult.FromError`.
  212. [Read]: xref:Discord.Commands.TypeReader#Discord_Commands_TypeReader_Read_Discord_Commands_CommandContext_System_String_
  213. #### Sample
  214. [!code-csharp[TypeReaders](samples/typereader.cs)]
  215. ### Installing TypeReaders
  216. TypeReaders are not automatically discovered by the Command Service,
  217. and must be explicitly added. To install a TypeReader, invoke [CommandService.AddTypeReader](xref:Discord.Commands.CommandService#Discord_Commands_CommandService_AddTypeReader__1_Discord_Commands_TypeReader_).