const path = require("path"); const db = require(path.join(__dirname, "../models/guilds")); /** * Checks and validates role reaction messages across all guilds * @param {Object} client - Discord client instance * @returns {Promise} */ async function checkRoles(client) { try { // Find all guilds with role reactions const guildsWithRoles = await db.find({ $expr: { $gt: [{ $size: "$roles" }, 0] } }); if (!guildsWithRoles?.length) return; // Process each guild sequentially to avoid rate limits for (const guild of guildsWithRoles) { try { await processGuildRoles(client, guild); } catch (error) { console.error(`Error processing guild ${guild.id}:`, error); } } } catch (error) { console.error('Error in checkRoles:', error); } } /** * Process role reactions for a single guild * @param {Object} client - Discord client instance * @param {Object} guild - Guild data from database * @returns {Promise} */ async function processGuildRoles(client, guild) { const validRoles = []; const invalidRoles = []; // Process each role reaction message for (const role of guild.roles) { try { const channel = client.channels.get(role.chanId); // Skip if channel doesn't exist or role array is empty if (!channel || !role.roles?.length) { invalidRoles.push(role); continue; } // Verify message exists const message = await channel.fetchMessage(role.msgId).catch(() => null); if (message) { validRoles.push(role); } else { invalidRoles.push(role); } } catch (error) { console.error(`Error processing role ${role.msgId} in guild ${guild.id}:`, error); invalidRoles.push(role); } } // Update guild with only valid roles if there were any invalid ones if (invalidRoles.length > 0) { await client.database.updateGuild(guild.id, { roles: validRoles }); } } module.exports = checkRoles;