wsb-bot / src /commands /clearDrops.js
APRK01
feat: add clear drops command to wipe WSB messages in channels
c8f3880
const { ChannelType } = require('discord.js');
const { successEmbed, errorEmbed, warnEmbed } = require('../utils/embeds');
module.exports = {
async execute(client, message, args) {
// Usage: `clear <channel_id>`
const channelIdStr = args[0]?.replace(/[<#>]/g, '');
if (!channelIdStr || !/^\d{17,20}$/.test(channelIdStr)) {
return message.reply({
embeds: [errorEmbed('Invalid Channel', 'Usage: `clear <channel_id>`\nExample: `clear 1234567890` or `clear #resources`')],
});
}
const guild = await client.guilds.fetch(process.env.GUILD_ID);
const channel = await guild.channels.fetch(channelIdStr).catch(() => null);
if (!channel || channel.type !== ChannelType.GuildText) {
return message.reply({
embeds: [errorEmbed('Channel Not Found', 'Could not find a valid text channel with that ID.')],
});
}
await message.reply({
embeds: [warnEmbed('⏳ Clearing Drops', `Fetching and deleting messages posted by WSB in <#${channel.id}>...\nThis might take a moment.`)],
});
try {
let deletedCount = 0;
let lastId = null;
let fetched;
// Loop to fetch and delete messages in batches of 100
do {
const fetchOptions = { limit: 100 };
if (lastId) fetchOptions.before = lastId;
fetched = await channel.messages.fetch(fetchOptions);
if (fetched.size === 0) break;
// Filter for messages sent by the bot
const botMessages = fetched.filter(m => m.author.id === client.user.id);
if (botMessages.size > 0) {
// Bulk delete is faster for messages under 14 days old
// For safety and to handle old messages, we'll delete one by one if bulk fails
try {
await channel.bulkDelete(botMessages, true); // true = filter out 14+ day old ones
deletedCount += botMessages.size;
} catch (bulkErr) {
console.warn('[Clear] Bulk delete failed or partially failed, falling back to manual deletion');
// Fallback manual deletion for older messages
for (const msg of botMessages.values()) {
await msg.delete().catch(() => { });
deletedCount++;
}
}
}
lastId = fetched.last().id;
} while (fetched.size === 100);
await message.reply({
embeds: [successEmbed('βœ… Clear Complete', `Successfully deleted **${deletedCount}** WSB messages from <#${channel.id}>.`)],
});
} catch (err) {
console.error('[Clear Error]', err);
await message.reply({
embeds: [errorEmbed('❌ Clear Failed', `An error occurred while clearing messages: \`${err.message}\``)],
});
}
},
};