115 lines
2.4 KiB
TypeScript
115 lines
2.4 KiB
TypeScript
import cron from "node-cron"
|
|
import dayjs from "dayjs"
|
|
import "dayjs/locale/es"
|
|
import { getUSD, getUsage, getWeather } from "./fx"
|
|
import { EventSource } from "eventsource"
|
|
|
|
const NTFY_URL = process.env.NTFY_URL
|
|
const TOPIC = process.env.NTFY_TOPIC
|
|
const TOKEN = process.env.NTFY_TOKEN
|
|
|
|
const isBirthday = dayjs().format("MM-DD") === "09-23"
|
|
|
|
if (!TOKEN || !NTFY_URL || !TOPIC) {
|
|
console.error("ntfy token, url or topic not set")
|
|
process.exit(1)
|
|
}
|
|
|
|
|
|
|
|
async function main() {
|
|
const [usd, usage, weather] = await Promise.all([
|
|
getUSD(),
|
|
getUsage(),
|
|
getWeather()
|
|
])
|
|
|
|
const message = `${isBirthday ? `Happy Birthday, SilicoFlare! You are now ${dayjs().diff(dayjs("2003-09-23"), "years")} years old.` : "Good Morning, SilicoFlare!"}
|
|
|
|
Today is **${dayjs().format("dddd, DD MMMM YYYY")}**.
|
|
Hoy es **${dayjs().locale("es").format("dddd, D [de] MMMM [de] YYYY")}**.
|
|
|
|
${weather}
|
|
|
|
${usd}
|
|
|
|
${usage}
|
|
|
|
Have a great day!`
|
|
|
|
const ntfy = await fetch(
|
|
`${NTFY_URL}/${TOPIC}`,
|
|
{
|
|
method: "POST",
|
|
headers: {
|
|
Authorization: `Bearer ${TOKEN}`,
|
|
Title: `Daily Digest for ${dayjs().format("YYYY-MM-DD")}`,
|
|
Markdown: "yes",
|
|
// if date is september 23rd, change the tag to "tada"
|
|
Tags: isBirthday ? "tada" : "calendar"
|
|
},
|
|
body: message,
|
|
},
|
|
)
|
|
|
|
if (!ntfy.ok) {
|
|
throw new Error(`ntfy failed: ${ntfy.status}`)
|
|
}
|
|
|
|
console.log("Notification sent at " + dayjs().format("YYYY-MM-dd HH:mm:ss"))
|
|
}
|
|
|
|
async function runMain() {
|
|
try {
|
|
await main()
|
|
} catch (err) {
|
|
console.error(err)
|
|
fetch(
|
|
`${NTFY_URL}/${TOPIC}`,
|
|
{
|
|
method: "POST",
|
|
headers: {
|
|
Authorization: `Bearer ${TOKEN}`,
|
|
Title: `Daily Digest for ${dayjs().format("YYYY-MM-DD")}: Error`,
|
|
Markdown: "yes",
|
|
Tags: "calendar",
|
|
Priority: "max"
|
|
},
|
|
body: `Error sending daily digest: ${(err as Error).message}`,
|
|
},
|
|
)
|
|
}
|
|
}
|
|
|
|
cron.schedule("0 7 * * *", () => {
|
|
runMain().catch((err) => {
|
|
console.error(err)
|
|
})
|
|
})
|
|
|
|
|
|
const es = new EventSource(`${NTFY_URL}/${TOPIC}/sse`, {
|
|
fetch: (input, init) =>
|
|
fetch(input, {
|
|
...init,
|
|
headers: {
|
|
...init?.headers,
|
|
Authorization: `Bearer ${TOKEN}`,
|
|
},
|
|
}),
|
|
});
|
|
|
|
es.onmessage = (e) => {
|
|
const msg = JSON.parse(e.data).message as string
|
|
|
|
if (msg === "/digest") {
|
|
runMain().catch((err) => {
|
|
console.error(err)
|
|
})
|
|
}
|
|
};
|
|
|
|
es.onerror = (e) => {
|
|
console.error(e);
|
|
};
|