Count messages from a channel

Viewed 112

I would like to clean all my channels and and I'm getting there. The problem is, it's very, very long ...

message.guild.channels.cache.forEach(c => {
                if (c.isText()) {
                    let CompteurMessage = 0;
                    let CompteurSuppression;
                    c.messages.fetch().then(messages => {
                        messages.forEach(msg => {
                            msg.delete();
                        });
                    });

                    c.send(`Your server is the best, ${message.author}.`);
                }
            });

Do you have any idea how to go much faster, for example counting the number of messages in a channel ?

EDIT : Now, I clone the channels but they change places ...

c.clone().then((clone) => {
                        clone.send(`Love ${message.author}.`);
                        const originalPosition = c.position;

                        c.delete();
                        clone.setPosition(originalPosition);
                    });

Channels n°3 and 4 change their place.

Thank you

1 Answers

Two ways to do this.

Cloning

You can clone the TextChannel using TextChannel.clone. This stops you having the 14 day limitation using BulkDelete.

const newChannel = await message.channel.clone();
message.channel.delete();

newChannel.send('The channel has been purged.');

BulkDelete

You can delete all the messages in the last 14 days very easily.

await message.channel.messages.fetch();
const messageCount = message.channel.messages.cache.map(x => x).length;
message.channel.bulkDelete(messageCount, true);

Note: Not the most elegant solutions since it's late at night but this should help you out.

Related