Creating a bulk message deletion command for Discord bot using C#

Hey everyone! I’m working on a Discord bot project in C# and running into some issues with implementing a bulk message deletion feature. I’m pretty new to coding but wanted to build something custom for my friend group’s server.

I’ve got two versions of code but neither is working how I want. Here’s what I’m trying to achieve: when I type !clear 5 it should delete the last 5 messages, or !clear 15 should remove 15 messages, etc.

SetupClearCommand();
private void SetupClearCommand()
{
   botCommands.CreateCommand("clear")
   .Parameter("MessageCount")
   .Do(async (context) =>
   {
      var targetMessages = await context.Channel.DownloadMessages(Int32.Parse(context.GetArg("MessageCount")));
      await context.Channel.DeleteMessages(targetMessages);
      await context.Channel.SendMessage(context.GetArg("MessageCount") + " messages removed.");
   });
}

This version attempts to use a parameter but doesn’t seem to work at all. My previous attempt was simpler but had a fixed number:

SetupClearCommand();
private void SetupClearCommand()
{
   botCommands.CreateCommand("clear")
      .Do(async (context) =>
{
   Message[] targetMessages;
   targetMessages = await context.Channel.DownloadMessages(50);
   await context.Channel.DeleteMessages(targetMessages);
});
}

This second version worked but always deleted exactly 50 messages regardless of what I wanted.

Can someone help me figure out where I’m going wrong? I feel like I’m missing something obvious here. Thanks in advance!

Your first code snippet has a parameter definition problem. Change .Parameter("MessageCount") to .Parameter("MessageCount", ParameterType.Required) - you need to specify the type and make it required. Also add validation for Discord’s limits. You can only bulk delete 100 messages max, and nothing older than 14 days. Throw in something like if (messageCount > 100) messageCount = 100; after you parse it. Your second version works because there’s no user input to parse, but the parameterized approach is definitely better once you fix the syntax.

I ran into the same issues with my first moderation bot. Your parsing and error checking is the main problem here. The first approach works, but you’ve got to validate that Int32.Parse() properly since users will definitely input garbage or leave it blank. Check if the argument exists first with something like if (string.IsNullOrEmpty(context.GetArg("MessageCount"))) before you try parsing it. Discord rate limits message deletions too, so throw a small delay between bulk operations or you’ll hit API limits fast. Don’t forget your bot needs “Manage Messages” permission in whatever channel it’s working in.

hey, you might wanna make sure your bot has the right permissions set up. also, using a try-catch block could help handle any API errors you’re running into. good luck with your project! :grinning_face_with_smiling_eyes: