I'm making a discord bot using c# with a library called DSharpPlus (if that helps a bit), and I'm trying to make a purge command but I keep getting a
Bad Request: 400
error and I don't know how to fix it. I've tried looking for it online and couldn't find any, plus I'm also kinda new to C# and have done so much on it already that I can't go back. Here's my code:
[Command("purge")]
[Description("Deleted A Certain Number Of Messages. (Max = 1000)")]
[RequireBotPermissions(Permissions.Administrator)]
[RequireUserPermissions(Permissions.Administrator)]
public async Task Purge(CommandContext ctx, [Description("Number Of Messages To Be Deleted.")]int num)
{
int limit = 1000;
if (num > limit)
await ctx.Channel.SendMessageAsync("Too Many Arguments. Limit: 1000").ConfigureAwait(false);
await ctx.Message.DeleteAsync().ConfigureAwait(false);
var messages = await ctx.Channel.GetMessagesAsync(num).ConfigureAwait(false);
await ctx.Channel.DeleteMessagesAsync(messages).ConfigureAwait(false);
var embed = new DiscordEmbedBuilder
{
Title = $"{num} Messages Deleted!",
Color = DiscordColor.Aquamarine
};
var deletedMessage = await ctx.Channel.SendMessageAsync(embed: embed).ConfigureAwait(false);
Thread.Sleep(4300);
await ctx.Channel.DeleteMessageAsync(deletedMessage).ConfigureAwait(false);
}
If it looks bad, again I'm new to C# so I don't know much. Please help because I've tried so many times that I just need to find help now. Thanks!
EDIT: basically the command dose indeed work but then it gives me a error for Bad Request: 400
and I don't really know why.
Here's what I keep getting if that also helps:
Nitro7256 tried executing 'purge' but it errorred: DSharpPlus.Exceptions.BadRequestException: Bad request: 400
(Late to the party)
If you read the discord documentation, it tells you the reasons for it sending back 400 error.
The message limit on bulk delete is 100, not 1,000. This is also the case with getting messages
If the messages are too old, it will also return a 400 error.
From the bulk delete docs itself:
This endpoint will not delete messages older than 2 weeks, and will fail with a 400 BAD REQUEST if any message provided is older than that or if any duplicate message IDs are provided.
Get Messages docs: https://discord.com/developers/docs/resources/channel#get-channel-messages
Bulk Delete docs: https://discord.com/developers/docs/resources/channel#bulk-delete-messages
Obviously you dont need to manually send the request. This is just showing you the reasons for 400 Error Response.
Side Note:
Use await Task.Delay(4300)
instead of Thread.Sleep(4300)
. Thread.Sleep()
blocks the main thread.