Zonies-Bot/functions/checkPolls.js
2025-05-12 15:20:40 -05:00

70 lines
2.2 KiB
JavaScript

const path = require("path");
const db = require(path.join(__dirname, "../models/polls"));
const Polls = require(path.join(__dirname, "./poll"));
/**
* Checks and processes all active polls in the database
* @param {Object} client - The Discord client instance
* @returns {Promise<void>}
*/
async function checkPolls(client) {
try {
const polls = await db.find();
if (!polls?.length) return;
// Process polls concurrently with a small delay between each
await Promise.all(polls.map(async (poll, index) => {
try {
// Add small delay between processing each poll to prevent rate limiting
await new Promise(resolve => setTimeout(resolve, index * 700));
const {
now,
time,
users,
avatars,
votes,
desc,
name,
options: names,
owner,
lang,
channelId,
messageId
} = poll;
const timeRemaining = now - (Date.now() - time);
const newPoll = new Polls({
time: timeRemaining,
client,
name: { name, description: desc },
options: names,
votes,
users,
avatars,
owner,
lang
});
// Attempt to fetch and process the message
const channel = client.channels.get(channelId);
if (!channel) return;
const message = await channel.fetchMessage(messageId).catch(() => null);
if (message) {
await newPoll.start(message, newPoll);
}
// Clean up the poll from database
await poll.deleteOne({ messageId });
} catch (error) {
console.error(`Error processing poll ${poll.messageId}:`, error);
}
}));
} catch (error) {
console.error('Error in checkPolls:', error);
}
}
module.exports = checkPolls;