skip to Main Content

How can I delete all the messages in a channel without the 100 message limit?
Remember, bulkdelete can only delete a maximum of 100 messages.
Do you have any ideas?

I’ve tried fetching the messages in the channel and then deleting them, but I get the impression that the bot can’t if it wasn’t open before the messages were sent.

2

Answers


  1. You are correct that the bulkDelete method in Discord.js has a limit of deleting a maximum of 100 messages at a time. To delete more than 100 messages in a channel, you would need to implement pagination and fetch messages in smaller chunks.
    I am providing a code snippet from my old project hope you found it helpful.

    const deleteMessages = async (channel) => {
      let messages = await channel.messages.fetch({ limit: 100 });
    
      while (messages.size > 0) {
        await channel.bulkDelete(messages);
        messages = await channel.messages.fetch({ limit: 100 });
      }
    };
    
    
    const channelId = "YOUR_CHANNEL_ID"; 
    
    const channel = client.channels.cache.get(channelId);
    if (channel && channel.type === "text") {
      deleteMessages(channel)
        .then(() => {
          console.log("All messages deleted successfully.");
        })
        .catch((error) => {
          console.error("Error deleting messages:", error);
        });
    } else {
      console.error("Channel not found or not a text channel.");
    }
    

    This code uses the messages.fetch method to fetch messages in chunks of 100. It then uses bulkDelete to delete each batch of messages. The loop continues until there are no more messages to delete in the channel.
    Please note that this operation can be resource-intensive and may take a significant amount of time, especially if the channel has a large number of messages. It’s also important to consider the rate limits imposed by Discord’s API, which may restrict the number of requests you can make within a certain time frame. It’s recommended to implement appropriate rate limiting and error handling in your code to avoid exceeding these limits.

    Login or Signup to reply.
  2. An alternative would be to clone the channel using TextChannel.clone(), then delete the original. Additionally, use .setPosition().

    const originalChannel = /* The channel */
    
    try {
       const cloneChannel = await originalChannel.clone();
    
       await originalChannel.delete();
       await cloneChannel.setPosition(originalChannel.position);
    } catch (err) {
       console.error(err);
    }
    

    source: https://stackoverflow.com/a/66930796/12464931

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search