hachem.wtf
aboutsummaryrefslogtreecommitdiff
path: root/src/app.js
blob: 2a67f0b65a8830ecbe131e0e1aecb3aedc6c9d73 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
const { Client, Events, GatewayIntentBits } = require("discord.js")
const axios = require("axios")
const fs = require("fs-extra")
const path = require("path")
const config = require("../config.json")

const {
  token,
  channel_id,
  minecraft_version,
  modrinth_mods,
} = config

const cacheFile = path.join(__dirname, "../cache/mod_versions.json")

const client = new Client({ intents: [GatewayIntentBits.Guilds] })
const strictVersionMatch = true

const LoadCache = async () =>
{
  try
  {
    if (await fs.pathExists(cacheFile))
      return JSON.parse(await fs.readFile(cacheFile, "utf8"))
  }
  catch (err)
  {
    console.error("[Cache] Failed to read cache:", err)
  }
  return {}
}

const SaveCache = async (cache) =>
{
  try
  {
    await fs.ensureDir(path.dirname(cacheFile))
    await fs.writeFile(cacheFile, JSON.stringify(cache, null, 2))
  }
  catch (err)
  {
    console.error("[Cache] Failed to save cache:", err)
  }
}

const GetLatestFabricVersion = async (slug) =>
{
  try
  {
    const res = await axios.get(`https://api.modrinth.com/v2/project/${slug}/version`)
    const versions = res.data.filter(v => v.loaders.includes("fabric"))
    if (versions.length === 0) return null

    return versions.sort(
      (a, b) => new Date(b.date_published) - new Date(a.date_published)
    )[0]
  }
  catch (err)
  {
    console.error(`[Modrinth] Error fetching ${slug}:`, err.message)
    return null
  }
}

const IsVersionCompatible = (modVersionList, targetVersion) =>
{
  if (strictVersionMatch)
    return modVersionList.includes(targetVersion)
  else
    return modVersionList.some(v => targetVersion.startsWith(v))
}

const CheckModUpdates = async () =>
{
  console.log("[Check] Checking for mod updates...")
  const cache = await LoadCache()
  const newCache = { ...cache }
  const updates = []
  const upToDate = []
  const waitingUpdate = []

  for (const slug of modrinth_mods)
  {
    const latest = await GetLatestFabricVersion(slug)
    if (!latest) continue

    const compatible = IsVersionCompatible(latest.game_versions, minecraft_version)
    const latestId = latest.id
    const cachedId = cache[slug]

    if (compatible)
    {
      if (cachedId !== latestId)
      {
        newCache[slug] = latestId
        updates.push({
          slug,
          version: latest.version_number,
          url: `https://modrinth.com/mod/${slug}/version/${latestId}`,
        })
      }
      else
      {
        upToDate.push({
          slug,
          version: latest.version_number,
          url: `https://modrinth.com/mod/${slug}/version/${latestId}`,
        })
        console.log(`[Check] ${slug} is up to date.`)
      }
    }
    else
    {
      waitingUpdate.push({
        slug,
        version: latest.version_number,
        url: `https://modrinth.com/mod/${slug}/version/${latestId}`,
      })
      console.log(`[Check] ${slug} waiting for update — not compatible with ${minecraft_version}`)
    }
  }

  await SaveCache(newCache)
  return { updates, upToDate, waitingUpdate }
}

const SendUpdateMessages = async (channel, updates, upToDate, waitingUpdate) =>
{
  if (updates.length === 0)
  {
    console.log("[Update]: No new updates.");
    return;
  }

  let message = ""
  message += `**Mod Update Check — Minecraft ${minecraft_version}**\n\n`

  if (updates.length > 0)
  {
    message += `**🟢 Updated Mods:**\n`
    for (const { slug, url } of updates)
      message += `✅ [${slug}](${url}) updated\n`
    message += `\n`
  }

  if (upToDate.lengt     > 0)
  {
    message += `**⚪ Up-to-Date Mods:**\n`
    for (const { slug, url } of upToDate)
      message += `✅ [${slug}](${url})\n`
    message += `\n`
  }

  if (waitingUpdate.length > 0)
  {
    message += `**⏳ Mods Waiting for Update:**\n`
    for (const { slug, url } of waitingUpdate)
      message += `❌ [${slug}](${url})\n`
  }
  
  await channel.send(
{ 
    content: message, 
    allowedMentions: { parse: [] }, 
    flags: 4
  })
  console.log(`[Discord] Sent update summary (${updates.length} updated, ${upToDate.length} up-to-date, ${waitingUpdate.length} waiting).`)
}

client.once(Events.ClientReady, async readyClient =>
{
  console.log(`[OK] Logged in as ${readyClient.user.tag}`)

  const channel = await client.channels.fetch(channel_id).catch(() => null)
  if (!channel)
  {
    console.error("❌ Could not find channel ID:", channel_id)
    return
  }

  const { updates, upToDate, waitingUpdate } = await CheckModUpdates()
  await SendUpdateMessages(channel, updates, upToDate, waitingUpdate)

  // ⏰ Check every hour (3600000 ms)
  setInterval(async () =>
  {
    const { updates, upToDate, waitingUpdate } = await CheckModUpdates()
    await SendUpdateMessages(channel, updates, upToDate, waitingUpdate)
  }, 60 * 60 * 1000)
})

client.login(token)