46 lines
1.5 KiB
TypeScript
46 lines
1.5 KiB
TypeScript
import { Client, TextChannel } from 'discord.js';
|
|
import { withConn } from '../db/pool.js';
|
|
import { generateQOTD } from '../ai/gemini.js';
|
|
|
|
export function startQotdScheduler(client: Client): void {
|
|
const run = async () => {
|
|
const today = new Date();
|
|
const yyyyMmDd = today.toISOString().slice(0, 10);
|
|
|
|
const guilds = await withConn(async (conn) => {
|
|
return conn.query(
|
|
'SELECT guild_id, qotd_channel_id, qotd_last_sent FROM guild_config WHERE qotd_enabled = 1 AND qotd_channel_id IS NOT NULL'
|
|
);
|
|
});
|
|
|
|
for (const row of guilds as any[]) {
|
|
if (row.qotd_last_sent && row.qotd_last_sent.toISOString().slice(0, 10) === yyyyMmDd) continue;
|
|
const channel = client.channels.cache.get(row.qotd_channel_id) as TextChannel | undefined;
|
|
if (!channel) continue;
|
|
try {
|
|
const question = await generateQOTD();
|
|
await channel.send(`QOTD: ${question}`);
|
|
await withConn((conn) => conn.query('UPDATE guild_config SET qotd_last_sent = ? WHERE guild_id = ?', [yyyyMmDd, row.guild_id]));
|
|
} catch (err) {
|
|
// ignore individual failures
|
|
}
|
|
}
|
|
};
|
|
|
|
// Run daily at 09:00 UTC
|
|
const scheduleNext = () => {
|
|
const now = new Date();
|
|
const next = new Date();
|
|
next.setUTCHours(9, 0, 0, 0);
|
|
if (next <= now) next.setUTCDate(next.getUTCDate() + 1);
|
|
setTimeout(async () => {
|
|
await run();
|
|
scheduleNext();
|
|
}, next.getTime() - now.getTime());
|
|
};
|
|
|
|
scheduleNext();
|
|
}
|
|
|
|
|