From 733c690ec78223351152b4e3d6f55175ba9bef52 Mon Sep 17 00:00:00 2001 From: Cynthia Foxwell Date: Mon, 26 Jul 2021 13:31:46 -0600 Subject: [PATCH] make private daily reminders system maybe one day ill make a full remind system, who knows --- .gitignore | 3 +- src/modules/private_reminders.js | 103 +++++++++++++++++++++++++++++++ 2 files changed, 105 insertions(+), 1 deletion(-) create mode 100644 src/modules/private_reminders.js diff --git a/.gitignore b/.gitignore index 3dc96c7..71700cd 100644 --- a/.gitignore +++ b/.gitignore @@ -4,4 +4,5 @@ config.json config.prod.json config.testing.json apikeys.json -database.db \ No newline at end of file +database.db +private_reminders.json \ No newline at end of file diff --git a/src/modules/private_reminders.js b/src/modules/private_reminders.js new file mode 100644 index 0000000..d4681d8 --- /dev/null +++ b/src/modules/private_reminders.js @@ -0,0 +1,103 @@ +/* +private_reminders.json example: +[ + { + "user": "user id", + "tz": "Etc/UTC", + "hour": 0, + "message": "it midnight" + } +] +*/ + +const timer = require("../lib/timer"); +const fs = require("fs"); +const {resolve} = require("path"); + +if (!fs.existsSync(resolve(__dirname, "..", "..", "private_reminders.json"))) + return; + +const tzFormatterCache = {}; +const dmCache = {}; + +const reminderData = require(resolve( + __dirname, + "..", + "..", + "private_reminders.json" +)); + +hf.database.run( + "CREATE TABLE IF NOT EXISTS private_reminders (user STRING NOT NULL PRIMARY KEY, last_run STRING NOT NULL) WITHOUT ROWID" +); + +function setLastRun(id, date) { + return new Promise((resolve, reject) => { + hf.database.run( + "REPLACE INTO private_reminders VALUES ($key,$value)", + { + $value: date, + $key: id, + }, + (err) => { + if (err == null) { + resolve(true); + } else { + reject(err); + } + } + ); + }); +} + +function getLastRun(id) { + return new Promise((resolve, reject) => { + hf.database.get( + "SELECT last_run FROM private_reminders WHERE user = $key", + { + $key: id, + }, + (err, row) => { + if (err == null) { + resolve(row?.value); + } else { + reject(err); + } + } + ); + }); +} + +timer.add( + "private_reminders", + async () => { + for (const data of reminderData) { + if (!tzFormatterCache[data.tz]) { + tzFormatterCache[data.tz] = Intl.DateTimeFormat("en-US", { + dateStyle: "short", + timeStyle: "short", + hour12: false, + timeZone: data.tz, + }); + } + + if (!dmCache[data.user]) { + dmCache[data.user] = await hf.bot.getDMChannel(data.user); + } + + const [date, time] = tzFormatterCache[data.tz] + .format(Date.now()) + .split(", "); + let [hour, minutes] = time.split(":"); + hour = parseInt(hour); + minutes = parseInt(minutes); + const lastRan = await getLastRun(data.user); + + if (date != lastRan && hour == data.hour && minutes == 0) { + dmCache[data.user].createMessage(":alarm_clock: " + data.message); + await setLastRun(data.user, date); + } + } + }, + 1000 +);