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.

04-select-menus.md 2.1 KiB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. # Select menus
  2. Select menus allow users to select from a range of options, this can be quite useful with configuration commands etc.
  3. ## Creating a select menu
  4. We can use a `SelectMenuBuilder` to create our menu.
  5. ```cs
  6. var menuBuilder = new SelectMenuBuilder()
  7. .WithPlaceholder("Select an option")
  8. .WithCustomId("menu-1")
  9. .WithMinValues(1)
  10. .WithMaxValues(1)
  11. .AddOption("Option A", "opt-a", "Option B is lying!")
  12. .AddOption("Option B", "opt-b", "Option A is telling the truth!");
  13. var builder = new ComponentBuilder()
  14. .WithSelectMenu(menuBuilder);
  15. ```
  16. Lets add this to a command:
  17. ```cs
  18. [Command("spawner")]
  19. public async Task Spawn()
  20. {
  21. var menuBuilder = new SelectMenuBuilder()
  22. .WithPlaceholder("Select an option")
  23. .WithCustomId("menu-1")
  24. .WithMinValues(1)
  25. .WithMaxValues(1)
  26. .AddOption("Option A", "opt-a", "Option B is lying!")
  27. .AddOption("Option B", "opt-b", "Option A is telling the truth!");
  28. var builder = new ComponentBuilder()
  29. .WithSelectMenu(menuBuilder);
  30. await ReplyAsync("Whos really lying?", components: builder.Build());
  31. }
  32. ```
  33. Running this produces this result:
  34. ![](Images/image4.png)
  35. And opening the menu we see:
  36. ![](Images/image5.png)
  37. Lets handle the selection of an option, as before we can hook the `InteractionCreated` event and check the type ourself but for this example im just going to use the `SelectMenuExecuted` event
  38. ```cs
  39. client.SelectMenuExecuted += MyMenuHandler;
  40. ```
  41. The `SelectMenuExecuted` also supplies a `SocketMessageComponent` argument, we can confirm that its a select menu by checking the `ComponentType` inside of the data field if we need, but the library will do that for us and only execute our handler if its a select menu.
  42. The values that the user has selected will be inside of the `Values` collection in the Data field. we can list all of them back to the user for this example.
  43. ```cs
  44. public async Task MyMenuHandler(SocketMessageComponent arg)
  45. {
  46. var text = string.Join(", ", arg.Data.Values);
  47. await arg.RespondAsync($"You have selected {text}");
  48. }
  49. ```
  50. Running this produces this result:
  51. ![](Images/image6.png)