Discord-Net-Labs / Discord.Net-Labs

An experimental fork of Discord.Net that implements the newest discord features for testing and development to eventually get merged into Discord.Net
https://labs.discordnet.dev
MIT License
156 stars 42 forks source link

Implement Modals #428

Closed CottageDwellingCat closed 2 years ago

CottageDwellingCat commented 2 years ago

How It Works

Without the interaction service

var mb = new ModalBuilder()
    .WithTitle("Fav Food")
    .WithCustomId("food_menu")
    .AddTextInput("What??", "food_name", placeholder:"Pizza")
    .AddTextInput("Why??", "food_reason", TextInputStyle.Paragraph, "Kus it's so tasty");

await command.RespondWithModalAsync(mb.Build());
client.ModalSubmitted += async modal => 
{
    List<SocketMessageComponentData> components =
        modal.Data.Components.ToList();
    string food = components
        .Where(x => x.CustomId == "food_name").First().Value;
    string reason = components
        .Where(x => x.CustomId == "food_reason").First().Value;

    string message = "hey @everyone; I just learned " + 
        $"{modal.User.Mention}'s favorite food is " +
        $"{food} because {reason}.";

    AllowedMentions mentions = new AllowedMentions();
    mentions.AllowedTypes = AllowedMentionTypes.Users;

    await modal.RespondAsync(message, allowedMentions:mentions);
}

With the interaction service (sample from cenngo)

[SlashCommand("food", "Tell us about your favorite food.")]
public async Task Command()
    => await Context.Interaction.RespondWithModalAsync<FoodModal>("food_menu");

[ModalInteraction("food_menu")]
public async Task ModalResponce(FoodModal modal)
{
    // Build the message to send.
    string message = "hey @everyone, I just learned " +
        $"{Context.User.Mention}'s favorite food is " +
        $"{modal.Food} because {modal.Reason}.";

    // Specify the AllowedMentions so we don't actually ping everyone.
    AllowedMentions mentions = new();
    mentions.AllowedTypes = AllowedMentionTypes.Users;

    // Respond to the modal.
    await RespondAsync(message, allowedMentions: mentions, ephemeral:true);
}

public class FoodModal : IModal
{
    public string Title => "Fav Food";
    // Strings with the ModalTextInput attribute will automatically 
    [InputLabel("What??")]
    [ModalTextInput("food_name", placeholder:"Pizza", maxLength:20)]
    public string Food { get; set; }

    // Additional paremeters can be specified to further customize the input.
    [InputLabel("Why??")]
    [ModalTextInput("food_reason", TextInputStyle.Paragraph, "Kuz it's tasty", maxLength:500)]
    public string Reason { get; set; } 
}

How It Looks

image3 image4

SylveonDeko commented 2 years ago

pog