From 75fe60c1d8014c2613f487799b2d4168493d2979 Mon Sep 17 00:00:00 2001 From: "Alex Pooley (@zuedev)" Date: Sat, 18 Jul 2026 12:21:47 +0100 Subject: build uex cache on start --- 174bg/discord-bot/.gitignore | 3 ++- 174bg/discord-bot/main.js | 51 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 53 insertions(+), 1 deletion(-) diff --git a/174bg/discord-bot/.gitignore b/174bg/discord-bot/.gitignore index 9b6ab89..ae5e1e0 100644 --- a/174bg/discord-bot/.gitignore +++ b/174bg/discord-bot/.gitignore @@ -1,2 +1,3 @@ /.env -/node_modules/ \ No newline at end of file +/node_modules/ +/.cache/ \ No newline at end of file diff --git a/174bg/discord-bot/main.js b/174bg/discord-bot/main.js index fc4da76..02400d6 100644 --- a/174bg/discord-bot/main.js +++ b/174bg/discord-bot/main.js @@ -14,6 +14,8 @@ import { import commands from "./commands/_index.js"; +import fs from "fs"; + const client = new Client({ intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMembers], }); @@ -22,6 +24,8 @@ client.on(Events.ClientReady, async (readyClient) => { console.log(`Logged in as ${readyClient.user.tag}!`); await registerCommands(); + + await buildCache(); }); client.on(Events.InteractionCreate, async (interaction) => { @@ -77,3 +81,50 @@ async function registerCommands() { console.error(error); } } + +async function getUrl(url) { + const response = await fetch(url); + if (!response.ok) return null; + return await response.json(); +} + +async function buildCache() { + if (!fs.existsSync("./.cache")) fs.mkdirSync("./.cache"); + + const uex = {}; + + uex.categories = (await getUrl("https://api.uexcorp.uk/2.0/categories"))?.data; + + for (const category of uex.categories) { + if (category.type === "item") { + if (!uex.items) uex.items = {}; + if (!uex.items[category.section]) uex.items[category.section] = {}; + uex.items[category.section][category.name] = (await getUrl(`https://api.uexcorp.uk/2.0/items?id_category=${category.id}`))?.data; + } + } + + // is there a difference between the current cache and the new cache? + if (fs.existsSync("./.cache/uex.json")) { + const currentCache = JSON.parse(fs.readFileSync("./.cache/uex.json", "utf-8")); + + if (JSON.stringify(currentCache) === JSON.stringify(uex)) { + console.log("No changes detected in UEX cache."); + return; + } + + console.log("Changes detected in UEX cache. Updating cache."); + + // backup the current cache YYMMDDHHMMSS + fs.writeFileSync( + `./.cache/uex.json.bak.${new Date().toISOString().replace(/[-:]/g, "").replace(/\..+/, "")}`, + JSON.stringify(currentCache, null, 2), + ); + } else { + console.log("No existing UEX cache found. Creating new cache."); + } + + fs.writeFileSync( + "./.cache/uex.json", + JSON.stringify(uex, null, 2), + ); +} \ No newline at end of file -- cgit v1.2.3