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.

02-responding-to-buttons.md 1.6 KiB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. # Responding to button clicks
  2. Responding to buttons is pretty simple, there are a couple ways of doing it and we can cover both.
  3. ### Method 1: Hooking the InteractionCreated Event
  4. We can hook the `InteractionCreated` event since button clicks are a form of interactions:
  5. ```cs
  6. client.IntreactionCreated += MyInteractionHandler;
  7. ```
  8. Now, lets write our handler.
  9. ```cs
  10. public async Task MyInteractionHandler(SocketInteraction arg)
  11. {
  12. // first we check the type of the interaction, this can be done with a switch statement
  13. switch(arg)
  14. {
  15. case SocketMessageComponent component:
  16. // we now have a variable defined as 'component' which contains our component data, lets pass it to a different handler.
  17. break;
  18. }
  19. }
  20. public async Task MyButtonHandler(SocketMessageComponent component)
  21. {
  22. // We can now check for our custom id
  23. switch(component.Data.CustomId)
  24. {
  25. // Since we set our buttons custom id as 'custom-id', we can check for it like this:
  26. case "custom-id":
  27. // Lets respond by sending a message saying they clicked the button
  28. await component.RespondAsync($"{component.User.Mention} has clicked the button!");
  29. break;
  30. }
  31. }
  32. ```
  33. Running it and clicking the button:
  34. ![](Images/image2.png)
  35. ### Method 2: Hooking the ButtonExecuted Event
  36. This method skips the first switch statement because the `ButtonExecuted` event is only fired when a button is clicked, meaning we dont have to check the type of the interaction.
  37. ```cs
  38. client.ButtonExecuted += MyButtonHandler;
  39. ```
  40. The rest of the code is the same and produces the same result.