Search code examples
c#dsharp+

Discord modal in DSharpPlus


In my discord bot it is necessary to implement the Modals system. Having searched for information on this matter, I realized that in the DSharpPlus library there is no possibility to use modal. As a result, I found the XeroxDev.DSharpPlus.ModalCommands library. After reading its instructions, I still didn’t understand how to work with it and got stuck at the stage of sending the modal to the user.

               DiscordInteractionResponseBuilder modal = ModalBuilder.Create("test_modal")
                    .WithTitle("Test Modal Title")
                    .AddComponents(new TextInputComponent("TextImput1", "ti1", "..."));
                await e.Interaction.CreateResponseAsync(InteractionResponseType.UpdateMessage, modal);

When running the code, the console reports an error...


Solution

  • DSharpPlus supports modal windows, the code will be almost identical to XeroxDev

    Based on the code you posted, you need to change the response type to the modal window

    DiscordInteractionResponseBuilder modal = ModalBuilder.Create("test_modal")
                        .WithTitle("Test Modal Title")
                        .AddComponents(new TextInputComponent("TextImput1", "ti1", "..."));
    await e.Interaction.CreateResponseAsync(InteractionResponseType.Modal, modal);
    

    To get the user's response, you need to subscribe to the ModalSubmitted event and send a response to discord that everything is fine

    DiscordClient.ModalSubmitted += Discord_ModalSubmitted;
    
    public static async Task Discord_ModalSubmitted(DiscordClient sender, ModalSubmitEventArgs e)
    {
        await e.Interaction.CreateResponseAsync(InteractionResponseType.DeferredMessageUpdate);
    }
    

    Well, to get data from the window, we wait for the user’s response and take the necessary data from the returned dictionary

    DiscordInteractionResponseBuilder modal = ModalBuilder.Create("test_modal")
                                .WithTitle("Test Modal Title")
                                .AddComponents(new TextInputComponent("TextImput1", "ti1", "..."));
    await e.Interaction.CreateResponseAsync(InteractionResponseType.Modal, modal);
                        
    var response = await e.Client.GetInteractivity().WaitForModalAsync("test_modal");                                             
        
    string TextInput1 = response.Result.Values["ti1"];