now-updater/index.js

62 lines
1.4 KiB
JavaScript
Raw Normal View History

import 'dotenv/config'
2025-12-18 01:57:14 +00:00
import { items } from './config.js'
2025-12-18 01:57:14 +00:00
const OMGLOL_API = `https://api.omg.lol/address/${process.env.OMGLOL_USERNAME}/now`
2025-12-18 01:57:14 +00:00
export async function getNow() {
const res = await fetch(OMGLOL_API)
const data = await res.json()
return data.response.now.content
2025-12-18 01:57:14 +00:00
}
export async function setNow(newNow) {
const res = await fetch(OMGLOL_API, {
method: 'POST',
2025-12-18 01:57:14 +00:00
headers: {
'Content-Type': 'application/json',
2025-12-18 01:57:14 +00:00
Authorization: `Bearer ${process.env.OMGLOL_KEY}`,
},
body: JSON.stringify({
content: newNow,
listed: 1,
}),
})
const data = await res.json()
console.log(`\n${data.response.message}`)
2025-12-18 01:57:14 +00:00
}
export default async function now() {
const now = await getNow()
let newNow = now
2025-12-18 01:57:14 +00:00
await Promise.all(
items.map(async ({ id, regex, getLatest }) => {
try {
const latest = await getLatest()
console.log(`${id}: ${latest.text}`)
if (latest && latest.text && latest.url) {
newNow = newNow.replace(regex, (match, openTag, closeTag) => {
// Replace href in opening tag
const updatedOpenTag = openTag.replace(
/href=["'][^"']*["']/,
`href="${latest.url}"`,
)
return `${updatedOpenTag}${latest.text}${closeTag}`
})
}
} catch (e) {
console.warn(`⚠️ Failed to fetch ${id}`, e)
2025-12-18 01:57:14 +00:00
}
}),
)
2025-12-18 01:57:14 +00:00
if (now === newNow) {
console.log('\nNow page has no changes')
2025-12-18 01:57:14 +00:00
} else {
await setNow(newNow)
2025-12-18 01:57:14 +00:00
}
}
await now()