Files
daily-digest/index.ts
T

112 lines
2.2 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
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 = `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",
Tags: "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);
};