HiddenPhox/src/modules/privateReminders.js

115 lines
2.6 KiB
JavaScript

/*
private_reminders.json example:
[
{
"user": "user id",
"tz": "Etc/UTC",
"hour": 0,
"message": "it midnight"
}
]
*/
const fs = require("fs");
const {resolve} = require("path");
const timer = require("../lib/timer");
const logger = require("../lib/logger");
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 TEXT NOT NULL PRIMARY KEY, last_run TEXT 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?.last_run);
} else {
reject(err);
}
}
);
});
}
hf.bot.once("ready", () => {
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 channel = dmCache[data.user];
const now = Date.now();
const [date, time] = tzFormatterCache[data.tz].format(now).split(", ");
let [hour, minutes] = time.split(":");
hour = parseInt(hour);
minutes = parseInt(minutes);
const lastRan = new Date(await getLastRun(data.user)).getTime();
if (now > lastRan && hour == data.hour && minutes == 0) {
logger.verbose(
"privateReminders",
`attempting to send reminder to ${data.user}`
);
if (channel != null) {
await channel.createMessage({
content: ":alarm_clock: " + data.message,
});
await setLastRun(data.user, date);
}
}
}
},
1000
);
});