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.2 kB

4 years ago
4 years ago
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. ---
  2. uid: Guides.MessageComponents.SelectMenus
  3. title: Select Menus
  4. ---
  5. # Select menus
  6. Select menus allow users to select from a range of options, this can be quite useful with configuration commands etc.
  7. ## Creating a select menu
  8. We can use a `SelectMenuBuilder` to create our menu.
  9. ```cs
  10. var menuBuilder = new SelectMenuBuilder()
  11. .WithPlaceholder("Select an option")
  12. .WithCustomId("menu-1")
  13. .WithMinValues(1)
  14. .WithMaxValues(1)
  15. .AddOption("Option A", "opt-a", "Option B is lying!")
  16. .AddOption("Option B", "opt-b", "Option A is telling the truth!");
  17. var builder = new ComponentBuilder()
  18. .WithSelectMenu(menuBuilder);
  19. ```
  20. Lets add this to a command:
  21. ```cs
  22. [Command("spawner")]
  23. public async Task Spawn()
  24. {
  25. var menuBuilder = new SelectMenuBuilder()
  26. .WithPlaceholder("Select an option")
  27. .WithCustomId("menu-1")
  28. .WithMinValues(1)
  29. .WithMaxValues(1)
  30. .AddOption("Option A", "opt-a", "Option B is lying!")
  31. .AddOption("Option B", "opt-b", "Option A is telling the truth!");
  32. var builder = new ComponentBuilder()
  33. .WithSelectMenu(menuBuilder);
  34. await ReplyAsync("Whos really lying?", components: builder.Build());
  35. }
  36. ```
  37. Running this produces this result:
  38. ![](Images/image4.png)
  39. And opening the menu we see:
  40. ![](Images/image5.png)
  41. Lets handle the selection of an option, We can hook the `SelectMenuExecuted` event to handle our select menu:
  42. ```cs
  43. client.SelectMenuExecuted += MyMenuHandler;
  44. ```
  45. 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.
  46. 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.
  47. ```cs
  48. public async Task MyMenuHandler(SocketMessageComponent arg)
  49. {
  50. var text = string.Join(", ", arg.Data.Values);
  51. await arg.RespondAsync($"You have selected {text}");
  52. }
  53. ```
  54. Running this produces this result:
  55. ![](Images/image6.png)