Search code examples
c#dsharp+

How to make a mute command in dSharpPlus


I want to create a command for a discord bot with which you can mute the user, but when the command is processed, the bot answers "The application is not responding"

internal class SlashCommandModule : ApplicationCommandModule
    {
        [SlashCommand("mute", "Mute user")]
        public async Task Mute(InteractionContext ctx, [Option("user", "User for mute")] DiscordUser user)
        {
            var member = (DiscordMember)user;
            await member.SetMuteAsync(true);
            await ctx.CreateResponseAsync(InteractionResponseType.ChannelMessageWithSource, new DiscordInteractionResponseBuilder().WithContent($"Muted {user.Username}"));
        }
    }

Solution

  • I think the issue here might be with using the DiscordUser type as your input for user. DiscordUser is not a string but rather a snowflake object, so you cannot directly cast a string into a DiscordUser and then cast this into a DiscordMember.

    Instead, you can try getting the username as a string and then finding the user with ctx.Guild.SearchMembersAsync(). This will return all results that are similar to the username you enter and will capture the most likely result for us to cast into a DiscordMember using ctx.Guild.GetMemberAsync().

    internal class SlashCommandModule : ApplicationCommandModule
        {
            [SlashCommand("mute", "Mute user")]
            public async Task Mute(InteractionContext ctx,
              [Option("user", "User for mute")] string user) //user becomes a string
            {
                ulong userIdForMute = ctx.Guild.SearchMembersAsync(user).Result[0].Id;
                DiscordMember memberForMute = ctx.Guild.GetMemberAsync(userIdForMute);
                await memberForMute.SetMuteAsync(true);
                await ctx.CreateResponseAsync(InteractionResponseType.ChannelMessageWithSource,
                 new DiscordInteractionResponseBuilder().WithContent($"Muted <@{userIdForMute}>"));
                 //@ them using their ID by using <@id>
            }
        }
    

    This may inadvertently capture the wrong user if someone enters only a partial username, so another way you can do this would be to require user IDs (accepted as a string) and try to cast that to a ulong.