Small fix

This commit is contained in:
2026-01-26 12:15:25 +01:00
parent 41d8c11a40
commit 10b33a79b3
2 changed files with 39 additions and 27 deletions
View File
+33 -21
View File
@@ -7,38 +7,50 @@ module.exports = {
const dbClient = await connectToDatabase();
const db = dbClient.db('discord');
const tempBanCollection = db.collection('tempban');
// 2) Define a function to schedule unbans
async function scheduleUnban(banData) {
const delay = banData.banTime - Date.now();
if (delay <= 0) {
return;
}
setTimeout(async () => {
const scheduled = new Map();
async function unbanNow(banData) {
try {
const guild = await client.guilds.fetch(banData.guildId);
await guild.bans.remove(banData.userId);
await tempBanCollection.deleteOne({_id: banData._id});
} catch (err) {
console.error('Error unbanning member:', err);
} finally {
scheduled.delete(String(banData._id));
}
}, delay);
}
function scheduleUnban(banData) {
const id = String(banData._id);
if (scheduled.has(id)) return;
const delay = banData.banTime - Date.now(); // assumes banTime is a future timestamp (ms)
if (delay <= 0) {
// already expired -> unban immediately
void unbanNow(banData);
return;
}
const timeoutId = setTimeout(() => void unbanNow(banData), delay);
scheduled.set(id, timeoutId);
}
async function scanAndSchedule() {
try {
const allBans = await tempBanCollection.find({}).toArray();
allBans.forEach(scheduleUnban);
tempBanCollection.watch().on('change', (change) => {
if (change.operationType === 'insert') {
const newBan = change.fullDocument;
scheduleUnban(newBan);
}
});
const now = Date.now();
const futureBans = await tempBanCollection.find({banTime: {$gt: now}}).toArray();
futureBans.forEach(scheduleUnban);
const expired = await tempBanCollection.find({banTime: {$lte: now}}).toArray();
expired.forEach((b) => void unbanNow(b));
} catch (err) {
console.error('Error setting up unban system:', err);
console.error('Error scanning tempbans:', err);
}
}
// Initial load
await scanAndSchedule();
// Poll every 10 seconds for newly inserted bans
setInterval(scanAndSchedule, 10_000);
},
};