module.exports = { timeout: 1000, immediate: false, name: 'Receipt Day Announcements', data: { channelId: '1462060674766344370', targetHour: 0, targetMinute: 1 }, async tick(client, timer) { try { // 1. Send the message const currentDate = new Date().toLocaleDateString('en-GB', { weekday: 'long', day: '2-digit', month: '2-digit', year: 'numeric' }); const channel = await client.channels.fetch(timer.data.channelId); await channel.send(`${currentDate}`); if (currentDate.startsWith('Sunday')) { const response = await fetch(`https://api.frankfurter.dev/v1/latest?amount=1&from=EUR&to=SEK`); if (!response.ok) await channel.send(`Failed to fetch exchange rate:\n${response.statusText}`); let db = await client.localDB; const data = await response.json(); db.prepare(`UPDATE bot_config SET exchange_rate_eur_kr = ? WHERE id = 1`).run(data.rates.SEK); let weeklyBudget = await (await db.prepare(`SELECT weekly_budget FROM bot_config`).get()).weekly_budget; await channel.send(`Fetched new exchange rate:\n${JSON.stringify(data)}`); db.prepare(`UPDATE grocery_budgets SET budget_spent = 0`).run(); await channel.send(`Reset weekly budget to ${weeklyBudget}EUR / ${weeklyBudget*data.rates.SEK}SEK`); } } catch (error) { console.error('[TIMER] Error:', error); } finally { // 2. Schedule the NEXT tick manually await this.scheduleNext(client, timer); } }, async scheduleNext(client, timer) { const now = new Date(); const next = new Date(); next.setHours(timer.data.targetHour, timer.data.targetMinute, 0, 0); if (next <= now) { next.setDate(next.getDate() + 1); } const delay = next.getTime() - now.getTime(); if (timer.instance) clearTimeout(timer.instance); timer.instance = setTimeout(() => { this.tick(client, timer); }, delay); const channel = await client.channels.fetch(timer.data.channelId); if (channel) await channel.send(`Next message scheduled for: ${next.toLocaleString()} with ms delta of ${delay} / ${delay/3600000}`); console.log(`[TIMER] Next message scheduled for: ${next.toLocaleString()}`); } };