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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  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 Groups
  117. Module Groups allow you to create a module where commands are prefixed.
  118. To create a group, flag a module with the
  119. @Discord.Commands.GroupAttribute
  120. Module groups also allow you to create **nameless commands**, where the
  121. [CommandAttribute] is configured with no name. In this case, the
  122. command will inherit the name of the group it belongs to.
  123. ### Submodules
  124. Submodules are modules that reside within another module. Typically,
  125. submodules are used to create nested groups (although not required to
  126. create nested groups).
  127. [!code-csharp[Groups and Submodules](samples/groups.cs)]
  128. ## With Builders
  129. **TODO**
  130. ## Dependency Injection
  131. The commands service is bundled with a very barebones Dependency
  132. Injection service for your convienence. It is recommended that
  133. you use DI when writing your modules.
  134. ### Setup
  135. First, you need to create an @Discord.Commands.IDependencyMap.
  136. The library includes @Discord.Commands.DependencyMap to help with
  137. this, however you may create your own IDependencyMap if you wish.
  138. Next, add the dependencies your modules will use to the map.
  139. Finally, pass the map into the `LoadAssembly` method.
  140. Your modules will automatically be loaded with this dependency map.
  141. [!code-csharp[DependencyMap Setup](samples/dependency_map_setup.cs)]
  142. ### Usage in Modules
  143. In the constructor of your module, any parameters will be filled in by
  144. the @Discord.Commands.IDependencyMap you pass into `LoadAssembly`.
  145. >[!NOTE]
  146. >If you accept `CommandService` or `IDependencyMap` as a parameter in
  147. your constructor, these parameters will be filled by the
  148. CommandService the module was loaded from, and the DependencyMap passed
  149. into it, respectively.
  150. [!code-csharp[DependencyMap in Modules](samples/dependency_module.cs)]
  151. # Preconditions
  152. Preconditions serve as a permissions system for your commands. Keep in
  153. mind, however, that they are not limited to _just_ permissions, and
  154. can be as complex as you want them to be.
  155. >[!NOTE]
  156. >Preconditions can be applied to Modules, Groups, or Commands.
  157. ## Bundled Preconditions
  158. Commands ships with four bundled preconditions; you may view their
  159. usages on their API page.
  160. - @Discord.Commands.RequireContextAttribute
  161. - @Discord.Commands.RequireOwnerAttribute
  162. - @Discord.Commands.RequireBotPermissionAttribute
  163. - @Discord.Commands.RequireUserPermissionAttribute
  164. ## Custom Preconditions
  165. To write your own preconditions, create a new class that inherits from
  166. @Discord.Commands.PreconditionAttribute
  167. In order for your precondition to function, you will need to override
  168. [CheckPermissions].
  169. Your IDE should provide an option to fill this in for you.
  170. Return [PreconditionResult.FromSuccess] if the context met the
  171. required parameters, otherwise return [PreconditionResult.FromError],
  172. optionally including an error message.
  173. [!code-csharp[Custom Precondition](samples/require_owner.cs)]
  174. [CheckPermissions]: xref:Discord.Commands.PreconditionAttribute#Discord_Commands_PreconditionAttribute_CheckPermissions_Discord_Commands_CommandContext_Discord_Commands_CommandInfo_Discord_Commands_IDependencyMap_
  175. [PreconditionResult.FromSuccess]: xref:Discord.Commands.PreconditionResult#Discord_Commands_PreconditionResult_FromSuccess
  176. [PreconditionResult.FromError]: xref:Discord.Commands.PreconditionResult#Discord_Commands_PreconditionResult_FromError_System_String_
  177. # Type Readers
  178. Type Readers allow you to parse different types of arguments in
  179. your commands.
  180. By default, the following Types are supported arguments:
  181. - bool
  182. - char
  183. - sbyte/byte
  184. - ushort/short
  185. - uint/int
  186. - ulong/long
  187. - float, double, decimal
  188. - string
  189. - DateTime/DateTimeOffset/TimeSpan
  190. - IMessage/IUserMessage
  191. - IChannel/IGuildChannel/ITextChannel/IVoiceChannel/IGroupChannel
  192. - IUser/IGuildUser/IGroupUser
  193. - IRole
  194. ### Creating a Type Readers
  195. To create a TypeReader, create a new class that imports @Discord and
  196. @Discord.Commands. Ensure your class inherits from @Discord.Commands.TypeReader
  197. Next, satisfy the `TypeReader` class by overriding [Read].
  198. >[!NOTE]
  199. >In many cases, Visual Studio can fill this in for you, using the
  200. >"Implement Abstract Class" IntelliSense hint.
  201. Inside this task, add whatever logic you need to parse the input string.
  202. Finally, return a `TypeReaderResult`. If you were able to successfully
  203. parse the input, return `TypeReaderResult.FromSuccess(parsedInput)`.
  204. Otherwise, return `TypeReaderResult.FromError`.
  205. [Read]: xref:Discord.Commands.TypeReader#Discord_Commands_TypeReader_Read_Discord_Commands_CommandContext_System_String_
  206. #### Sample
  207. [!code-csharp[TypeReaders](samples/typereader.cs)]
  208. ### Installing TypeReaders
  209. TypeReaders are not automatically discovered by the Command Service,
  210. and must be explicitly added. To install a TypeReader, invoke [CommandService.AddTypeReader](xref:Discord.Commands.CommandService#Discord_Commands_CommandService_AddTypeReader__1_Discord_Commands_TypeReader_).