require("dotenv").config() const cron = require("node-cron"); const os = require("os") const Discord = require('discord.js'); const { connect } = require("http2"); const mysql = require('mysql'); const fs = require('fs').promises; const hook = new Discord.WebhookClient({ url: process.env.DISCORD_WEBHOOK_URL }) const JSON_FILE = process.env.JSON_FILE || "records.json"; function getStartOfYesterdayTimestamp() { const today = new Date(); // Set the date to yesterday today.setDate(today.getDate() - 1); // Create a new Date object for the start of yesterday const startOfYesterday = new Date(today.getFullYear(), today.getMonth(), today.getDate()); return startOfYesterday.getTime(); // Returns the timestamp in milliseconds } async function loadRecords() { try { const data = await fs.readFile(JSON_FILE, 'utf-8'); return JSON.parse(data); } catch (error) { if (error.code === 'ENOENT') { return { records: {} }; // Return empty records if file doesn't exist } throw error; } } async function saveRecords(root) { const json = JSON.stringify(root, null, 2); await fs.writeFile(JSON_FILE, json); } async function getPreviousDayData() { return new Promise(async (resolve, reject) => { const previousDay = new Date(getStartOfYesterdayTimestamp()) // 24 hours ago const startTime = new Date(previousDay.setHours(0, 0, 0, 0)); const endTime = new Date(previousDay.setHours(23, 59, 59, 999)); const connection = await mysql.createConnection({ host: process.env.DATABASE_HOST, user: process.env.DATABASE_USER, password: process.env.DATABASE_PASSWORD, database: process.env.DATABASE_NAME, multipleStatements: true }); await connection.connect(); let callsMade; let recordForToday; let monthlyTotal; let totalCalls; await connection.query(` SELECT COUNT(DISTINCT uniqueid) AS call_count FROM cdr WHERE calldate BETWEEN ? AND ?; SELECT COUNT(DISTINCT uniqueid) AS call_count FROM cdr WHERE MONTH(calldate) = MONTH(?) AND YEAR(calldate) = YEAR(?); SELECT COUNT(DISTINCT uniqueid) AS call_count FROM cdr; `, [startTime, endTime, previousDay, previousDay], (err, res) => { if (err) { reject(err) } connection.end(); let output = { "Calls Made": res[0][0].call_count, "Monthly Total": res[1][0].call_count, "Total Calls Ever Placed": res[2][0].call_count, "System Uptime": getSystemUptime(), "All Time Record": null, // Placeholder } console.log(output) resolve(output); }); }) } function getSystemUptime() { const uptime = os.uptime(); const days = Math.floor(uptime / 86400); const hours = Math.floor((uptime % 86400) / 3600); const minutes = Math.floor((uptime % 3600) / 60); const seconds = Math.floor(uptime % 60); return `${days} days, ${hours} hours, ${minutes} minutes, ${seconds} seconds`; } function updateRecords(data, root) { const currentDate = new Date(getStartOfYesterdayTimestamp()).toISOString().split('T')[0]; const month = currentDate.slice(0, 7); let isNewRecord = false; // Update all-time record const allTimeRecord = root.records.record_calls || { date: currentDate, count: 0 }; if (!root.records.record_calls) { root.records.record_calls = { date: currentDate, count: data["Calls Made"] }; isNewRecord = true; } else if (parseInt(allTimeRecord.count) < data["Calls Made"]) { allTimeRecord.count = data["Calls Made"]; isNewRecord = true; } data["All Time Record"] = `${allTimeRecord.count} calls on ${allTimeRecord.date}`; // Update total calls ever placed root.records.total_calls_ever_placed = data["Total Calls Ever Placed"]; // Update monthly total root.records[`monthly_total_${month}`] = data["Monthly Total"]; if (isNewRecord) { data["NEW RECORD"] = true; } return data; } async function sendSummary() { console.log("Preparing summary.") const data = await getPreviousDayData(); console.log("Loading records.") const root = await loadRecords(); console.log("Updating records...") const updatedData = await updateRecords(data, root); console.log("Saving.") await saveRecords(root); const previousDayStart = new Date(getStartOfYesterdayTimestamp()); const previousDayEnd = new Date(previousDayStart); previousDayEnd.setHours(23, 59, 59, 999); let embed = { title: `Summary from to `, color: 0x1E90FF, fields: [], timestamp: new Date(), footer: { } } for (const [key, value] of Object.entries(updatedData)) { if (key === "NEW RECORD") { embed.fields.push({ name: "NEW RECORD!", value: "A new record has been set!", inline: false }); } else { embed.fields.push({ name: key, value: value, inline: false }); } } console.log("Sending message.") await hook.send({ embeds: [embed] }); } console.log("Scheduling...") const schedule = cron.schedule("0 1 * * *", sendSummary)