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.

03-responding-to-slash-commands.md 2.3 KiB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. # Responding to interactions.
  2. Interactions are the base thing sent over by Discord. Slash commands are one of the interaction types. In order to receive a slash command we have to listen to the `InteractionCreated` event. Let's add this to our code.
  3. ```cs
  4. client.InteractionCreated += Client_InteractionCreated;
  5. ...
  6. private async Task Client_InteractionCreated(SocketInteraction arg)
  7. {
  8. }
  9. ```
  10. Now that we have the interaction event, let's talk about the `SocketInteraction` argument. The interaction can be cast to either a `SocketSlashCommand` or a `SocketMessageComponent`. In our case, we're trying to use slash commands so let's cast it to a `SocketSlashCommand`.
  11. ```cs
  12. private async Task Client_InteractionCreated(SocketInteraction arg)
  13. {
  14. if(arg is SocketSlashCommand command)
  15. {
  16. // we now have an instance of a SocketSlashCommand named command.
  17. }
  18. }
  19. ```
  20. With every type of interaction there is a `Data` field. This is where the relevant information lives about our command that was executed. In our case, `Data` is a `SocketSlashCommandData` instance. In the data class, we can access the name of the command triggered as well as the options if there were any. For this example, we're just going to respond with the name of the command executed.
  21. ```cs
  22. private async Task Client_InteractionCreated(SocketInteraction arg)
  23. {
  24. if(arg is SocketSlashCommand command)
  25. {
  26. await command.RespondAsync($"You executed {command.Data.Name}");
  27. }
  28. }
  29. ```
  30. Let's try this out!
  31. ![slash command picker](images/slashcommand1.png)
  32. ![slash command result](images/slashcommand2.png)
  33. Let's go over the response types quickly, as you would only change them for style points :P
  34. > After receiving an interaction, you must respond to acknowledge it. You can choose to respond with a message immediately using `RespondAsync()` or you can choose to send a deferred response with `DeferAsync()`. If choosing a deferred response, the user will see a loading state for the interaction, and you'll have up to 15 minutes to edit the original deferred response using `ModifyOriginalResponseAsync()`. You can read more about response types [here](https://discord.com/developers/docs/interactions/slash-commands#interaction-response)
  35. This seems to be working! Next, we will look at parameters for slash commands.