Spaces:
Sleeping
Sleeping
Upload 16 files
Browse files- src/bot.js +144 -14
src/bot.js
CHANGED
|
@@ -3,13 +3,20 @@ import { Agent } from 'undici'
|
|
| 3 |
import { readdirSync } from 'node:fs'
|
| 4 |
import { resolve, dirname } from 'node:path'
|
| 5 |
import { fileURLToPath, pathToFileURL } from 'node:url'
|
|
|
|
| 6 |
|
| 7 |
const __dirname = dirname(fileURLToPath(import.meta.url))
|
| 8 |
|
| 9 |
-
const RACE_CONCURRENCY
|
| 10 |
-
const MAX_RETRIES
|
| 11 |
-
const RETRY_DELAY_MS
|
| 12 |
-
const CONNECT_TIMEOUT
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
|
| 14 |
// Passing a custom undici Agent via the `rest` option is the only way to
|
| 15 |
// override discord.js's hardcoded 10 s connect timeout β env vars and
|
|
@@ -87,11 +94,138 @@ function raceConnections(token, round) {
|
|
| 87 |
// Exported client reference β populated once connected
|
| 88 |
export let client = null
|
| 89 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 90 |
export async function startBot() {
|
| 91 |
const token = process.env.DISCORD_TOKEN
|
| 92 |
if (!token) throw new Error('Missing required environment variable: DISCORD_TOKEN')
|
| 93 |
|
| 94 |
-
// Load events once β registered on whichever client wins
|
| 95 |
const eventsDir = resolve(__dirname, 'events')
|
| 96 |
const eventFiles = readdirSync(eventsDir).filter((f) => f.endsWith('.js'))
|
| 97 |
const events = await Promise.all(
|
|
@@ -106,16 +240,12 @@ export async function startBot() {
|
|
| 106 |
|
| 107 |
try {
|
| 108 |
const winner = await raceConnections(token, round)
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
if (event.once) {
|
| 112 |
-
winner.once(event.name, (...args) => event.execute(...args))
|
| 113 |
-
} else {
|
| 114 |
-
winner.on(event.name, (...args) => event.execute(...args))
|
| 115 |
-
}
|
| 116 |
-
}
|
| 117 |
-
|
| 118 |
client = winner
|
|
|
|
|
|
|
|
|
|
| 119 |
return
|
| 120 |
} catch (err) {
|
| 121 |
console.error(`[bot] Round ${round} failed: ${err.message}`)
|
|
|
|
| 3 |
import { readdirSync } from 'node:fs'
|
| 4 |
import { resolve, dirname } from 'node:path'
|
| 5 |
import { fileURLToPath, pathToFileURL } from 'node:url'
|
| 6 |
+
import { loadGuildConfig } from './storage/cache.js'
|
| 7 |
|
| 8 |
const __dirname = dirname(fileURLToPath(import.meta.url))
|
| 9 |
|
| 10 |
+
const RACE_CONCURRENCY = 5 // parallel attempts per round
|
| 11 |
+
const MAX_RETRIES = -1 // rounds before giving up (-1 = infinite)
|
| 12 |
+
const RETRY_DELAY_MS = 5_000 // wait between rounds (ms)
|
| 13 |
+
const CONNECT_TIMEOUT = 60_000 // undici connect timeout per attempt (ms)
|
| 14 |
+
|
| 15 |
+
// How often to ping Discord's gateway to confirm the connection is alive.
|
| 16 |
+
// discord.js already sends its own heartbeats, but this lets US detect a
|
| 17 |
+
// zombie connection independently and trigger a reconnect if needed.
|
| 18 |
+
const KEEPALIVE_INTERVAL_MS = 30_000 // ping every 30 s
|
| 19 |
+
const KEEPALIVE_TIMEOUT_MS = 10_000 // if no pong within 10 s β reconnect
|
| 20 |
|
| 21 |
// Passing a custom undici Agent via the `rest` option is the only way to
|
| 22 |
// override discord.js's hardcoded 10 s connect timeout β env vars and
|
|
|
|
| 94 |
// Exported client reference β populated once connected
|
| 95 |
export let client = null
|
| 96 |
|
| 97 |
+
// -------------------------------------------------------------------
|
| 98 |
+
// Load guild configs for all guilds the client is currently in.
|
| 99 |
+
// Called after every successful connection or reconnect so the cache
|
| 100 |
+
// is always warm regardless of whether the ready event re-fires.
|
| 101 |
+
// -------------------------------------------------------------------
|
| 102 |
+
export async function loadAllGuildConfigs(c) {
|
| 103 |
+
for (const [guildId, guild] of c.guilds.cache) {
|
| 104 |
+
try {
|
| 105 |
+
await loadGuildConfig(guild)
|
| 106 |
+
console.log(`[bot] Loaded guild config for ${guild.name} (${guildId})`)
|
| 107 |
+
} catch (err) {
|
| 108 |
+
console.error(`[bot] Failed to load guild config for ${guildId}: ${err.message}`)
|
| 109 |
+
}
|
| 110 |
+
}
|
| 111 |
+
}
|
| 112 |
+
|
| 113 |
+
// -------------------------------------------------------------------
|
| 114 |
+
// Keepalive: ping the gateway WS every KEEPALIVE_INTERVAL_MS.
|
| 115 |
+
// If we don't get a response within KEEPALIVE_TIMEOUT_MS we consider
|
| 116 |
+
// the connection zombie and force a full reconnect.
|
| 117 |
+
// -------------------------------------------------------------------
|
| 118 |
+
let keepaliveTimer = null
|
| 119 |
+
let reconnectPending = false
|
| 120 |
+
|
| 121 |
+
function startKeepalive(c, onZombie) {
|
| 122 |
+
stopKeepalive()
|
| 123 |
+
|
| 124 |
+
keepaliveTimer = setInterval(async () => {
|
| 125 |
+
if (reconnectPending) return
|
| 126 |
+
|
| 127 |
+
try {
|
| 128 |
+
const shard = c.ws?.shards?.first?.() ?? c.ws
|
| 129 |
+
if (!shard) return
|
| 130 |
+
const latency = shard.ping
|
| 131 |
+
if (latency === -1 || latency === null || latency === undefined) {
|
| 132 |
+
throw new Error('gateway ping is -1, connection likely dead')
|
| 133 |
+
}
|
| 134 |
+
console.log('[bot] Keepalive ping OK β gateway latency ' + latency + ' ms')
|
| 135 |
+
} catch (err) {
|
| 136 |
+
console.warn(`[bot] Keepalive ping FAILED: ${err.message} β triggering reconnect`)
|
| 137 |
+
reconnectPending = true
|
| 138 |
+
stopKeepalive()
|
| 139 |
+
onZombie()
|
| 140 |
+
}
|
| 141 |
+
}, KEEPALIVE_INTERVAL_MS)
|
| 142 |
+
}
|
| 143 |
+
|
| 144 |
+
function stopKeepalive() {
|
| 145 |
+
if (keepaliveTimer) {
|
| 146 |
+
clearInterval(keepaliveTimer)
|
| 147 |
+
keepaliveTimer = null
|
| 148 |
+
}
|
| 149 |
+
}
|
| 150 |
+
|
| 151 |
+
// -------------------------------------------------------------------
|
| 152 |
+
// Wire up disconnect/error listeners so we reconnect automatically.
|
| 153 |
+
// -------------------------------------------------------------------
|
| 154 |
+
function attachReconnectListeners(c, events, token) {
|
| 155 |
+
// discord.js fires this when the gateway WS closes unexpectedly
|
| 156 |
+
c.on('shardDisconnect', async (closeEvent, shardId) => {
|
| 157 |
+
if (reconnectPending) return
|
| 158 |
+
reconnectPending = true
|
| 159 |
+
console.warn(`[bot] Shard ${shardId} disconnected (code ${closeEvent.code}) β reconnecting...`)
|
| 160 |
+
stopKeepalive()
|
| 161 |
+
await reconnect(events, token)
|
| 162 |
+
})
|
| 163 |
+
|
| 164 |
+
// Gateway-level errors (network drop, TLS failure, etc.)
|
| 165 |
+
c.on('shardError', async (err, shardId) => {
|
| 166 |
+
if (reconnectPending) return
|
| 167 |
+
reconnectPending = true
|
| 168 |
+
console.warn(`[bot] Shard ${shardId} error: ${err.message} β reconnecting...`)
|
| 169 |
+
stopKeepalive()
|
| 170 |
+
// Small delay so any in-flight cleanup can finish
|
| 171 |
+
await new Promise((r) => setTimeout(r, 1_000))
|
| 172 |
+
await reconnect(events, token)
|
| 173 |
+
})
|
| 174 |
+
}
|
| 175 |
+
|
| 176 |
+
// -------------------------------------------------------------------
|
| 177 |
+
// Reconnect β tear down current client, race new connections.
|
| 178 |
+
// -------------------------------------------------------------------
|
| 179 |
+
async function reconnect(events, token) {
|
| 180 |
+
console.log('[bot] Attempting reconnect...')
|
| 181 |
+
|
| 182 |
+
// Gracefully destroy the old client if it's still around
|
| 183 |
+
try { client?.destroy() } catch (_) {}
|
| 184 |
+
client = null
|
| 185 |
+
|
| 186 |
+
let round = 0
|
| 187 |
+
while (MAX_RETRIES === -1 || round < MAX_RETRIES) {
|
| 188 |
+
round++
|
| 189 |
+
console.log(`[bot] Reconnect round ${round}/${MAX_RETRIES === -1 ? 'β' : MAX_RETRIES}`)
|
| 190 |
+
|
| 191 |
+
try {
|
| 192 |
+
const winner = await raceConnections(token, round)
|
| 193 |
+
registerEvents(winner, events)
|
| 194 |
+
attachReconnectListeners(winner, events, token)
|
| 195 |
+
client = winner
|
| 196 |
+
reconnectPending = false
|
| 197 |
+
await loadAllGuildConfigs(winner)
|
| 198 |
+
startKeepalive(winner, () => reconnect(events, token))
|
| 199 |
+
console.log('[bot] Reconnect successful')
|
| 200 |
+
return
|
| 201 |
+
} catch (err) {
|
| 202 |
+
console.error(`[bot] Reconnect round ${round} failed: ${err.message}`)
|
| 203 |
+
if (MAX_RETRIES !== -1 && round >= MAX_RETRIES) {
|
| 204 |
+
console.error('[bot] Giving up β process will exit')
|
| 205 |
+
process.exit(1)
|
| 206 |
+
}
|
| 207 |
+
console.log(`[bot] Retrying reconnect in ${RETRY_DELAY_MS / 1000}s...`)
|
| 208 |
+
await new Promise((r) => setTimeout(r, RETRY_DELAY_MS))
|
| 209 |
+
}
|
| 210 |
+
}
|
| 211 |
+
}
|
| 212 |
+
|
| 213 |
+
// Register loaded event modules on a client instance
|
| 214 |
+
function registerEvents(c, events) {
|
| 215 |
+
for (const event of events) {
|
| 216 |
+
if (event.once) {
|
| 217 |
+
c.once(event.name, (...args) => event.execute(...args))
|
| 218 |
+
} else {
|
| 219 |
+
c.on(event.name, (...args) => event.execute(...args))
|
| 220 |
+
}
|
| 221 |
+
}
|
| 222 |
+
}
|
| 223 |
+
|
| 224 |
export async function startBot() {
|
| 225 |
const token = process.env.DISCORD_TOKEN
|
| 226 |
if (!token) throw new Error('Missing required environment variable: DISCORD_TOKEN')
|
| 227 |
|
| 228 |
+
// Load events once β registered on whichever client wins each race
|
| 229 |
const eventsDir = resolve(__dirname, 'events')
|
| 230 |
const eventFiles = readdirSync(eventsDir).filter((f) => f.endsWith('.js'))
|
| 231 |
const events = await Promise.all(
|
|
|
|
| 240 |
|
| 241 |
try {
|
| 242 |
const winner = await raceConnections(token, round)
|
| 243 |
+
registerEvents(winner, events)
|
| 244 |
+
attachReconnectListeners(winner, events, token)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 245 |
client = winner
|
| 246 |
+
reconnectPending = false
|
| 247 |
+
await loadAllGuildConfigs(winner)
|
| 248 |
+
startKeepalive(winner, () => reconnect(events, token))
|
| 249 |
return
|
| 250 |
} catch (err) {
|
| 251 |
console.error(`[bot] Round ${round} failed: ${err.message}`)
|