Rishav
Rishav

Reputation: 4068

Bulk delete messages on discord.net 2.x

    [Command("purge")]
    [Summary("Deletes the specified amount of messages.")]
    [RequireUserPermission(GuildPermission.Administrator)]
    [RequireBotPermission(ChannelPermission.ManageMessages)]
    public async Task PurgeChat(int amount)
    {
        var messages = Context.Channel.GetMessagesAsync(amount + 1).Flatten();
        await ((ITextChannel)Context.Channel).DeleteMessagesAsync(messages);
    }

I want to delete last amount messages and came up with this code. But apparently I get an error saying

Severity Code Description Project File Line Suppression State Error CS1503 Argument 1: cannot convert from 'System.Collections.Generic.IAsyncEnumerable' to 'System.Collections.Generic.IEnumerable'

I am using Discord.net 2.x. How can I fix the error and why did it happen?

Upvotes: 0

Views: 3954

Answers (2)

Rishav
Rishav

Reputation: 4068

I took some help from the Discord-api unofficial server and they told me that I have to await the method and also use FlattenAsync() and not Flatten() in discord.net 2.x.

So I summed up to

IEnumerable<IMessage> messages = await Context.Channel.GetMessagesAsync(amount + 1).FlattenAsync();
await ((ITextChannel) Context.Channel).DeleteMessagesAsync(messages);
const int delay = 3000;
IUserMessage m = await ReplyAsync($"I have deleted {amount} messages for ya. :)");
await Task.Delay(delay);
await m.DeleteAsync();

and this is working perfect.

Upvotes: 1

WQYeo
WQYeo

Reputation: 4056

You forgot the await keyword,

var messages = (await Context.Channel.GetMessagesAsync(amount + 1)).Flatten();

If you need these to execute in parallel to another task in this method (which I doubt so), you can use ContinueWith() method instead.

Upvotes: 0

Related Questions