Spaces:
Sleeping
Sleeping
Update src/bot.js
Browse files- src/bot.js +93 -56
src/bot.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
| 1 |
-
import { Client, GatewayIntentBits, Partials } from 'discord.js'
|
| 2 |
import { Agent } from 'undici'
|
| 3 |
import { readdirSync } from 'node:fs'
|
| 4 |
import { resolve, dirname } from 'node:path'
|
|
@@ -6,14 +6,23 @@ 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
|
| 12 |
-
const
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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
|
| 16 |
-
// top-level Client options are ignored by undici entirely.
|
| 17 |
function createClient() {
|
| 18 |
return new Client({
|
| 19 |
intents: [
|
|
@@ -23,31 +32,50 @@ function createClient() {
|
|
| 23 |
GatewayIntentBits.MessageContent,
|
| 24 |
],
|
| 25 |
partials: [Partials.GuildMember],
|
|
|
|
|
|
|
| 26 |
rest: {
|
| 27 |
-
agent: new Agent({
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 28 |
},
|
| 29 |
})
|
| 30 |
}
|
| 31 |
|
| 32 |
// Single connection attempt β resolves with the ready client or rejects on failure
|
| 33 |
-
function attemptLogin(token,
|
| 34 |
return new Promise((resolve, reject) => {
|
| 35 |
const c = createClient()
|
| 36 |
|
| 37 |
-
|
| 38 |
-
// undici error surfaces first with a meaningful message when possible.
|
| 39 |
-
const timeout = setTimeout(() => {
|
| 40 |
c.destroy()
|
| 41 |
-
reject(new Error(`
|
| 42 |
-
},
|
| 43 |
|
| 44 |
c.once('clientReady', () => {
|
| 45 |
-
clearTimeout(
|
| 46 |
resolve(c)
|
| 47 |
})
|
| 48 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 49 |
c.login(token).catch((err) => {
|
| 50 |
-
clearTimeout(
|
| 51 |
c.destroy()
|
| 52 |
reject(err)
|
| 53 |
})
|
|
@@ -60,22 +88,19 @@ function raceConnections(token, round) {
|
|
| 60 |
let settled = false
|
| 61 |
let failures = 0
|
| 62 |
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
p.then((winner) => {
|
| 69 |
-
if (settled) {
|
| 70 |
-
winner.destroy()
|
| 71 |
-
return
|
| 72 |
-
}
|
| 73 |
settled = true
|
| 74 |
-
console.log(`[bot]
|
| 75 |
resolve(winner)
|
| 76 |
}).catch((err) => {
|
| 77 |
failures++
|
| 78 |
-
console.warn(`[bot]
|
| 79 |
if (!settled && failures === RACE_CONCURRENCY) {
|
| 80 |
reject(new Error(`All ${RACE_CONCURRENCY} attempts failed in round ${round}`))
|
| 81 |
}
|
|
@@ -84,6 +109,23 @@ function raceConnections(token, round) {
|
|
| 84 |
})
|
| 85 |
}
|
| 86 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 87 |
// Exported client reference β populated once connected
|
| 88 |
export let client = null
|
| 89 |
|
|
@@ -91,41 +133,36 @@ 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
|
| 95 |
const eventsDir = resolve(__dirname, 'events')
|
| 96 |
const eventFiles = readdirSync(eventsDir).filter((f) => f.endsWith('.js'))
|
| 97 |
const events = await Promise.all(
|
| 98 |
eventFiles.map((file) => import(pathToFileURL(resolve(eventsDir, file)).href))
|
| 99 |
)
|
| 100 |
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
try {
|
| 108 |
-
const winner = await raceConnections(token, round)
|
| 109 |
-
|
| 110 |
-
for (const event of events) {
|
| 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}`)
|
| 122 |
-
|
| 123 |
-
if (MAX_RETRIES !== -1 && round >= MAX_RETRIES) {
|
| 124 |
-
throw new Error(`[bot] Giving up after ${MAX_RETRIES} rounds`)
|
| 125 |
}
|
| 126 |
-
|
| 127 |
-
console.log(`[bot] Retrying in ${RETRY_DELAY_MS / 1000}s...`)
|
| 128 |
-
await new Promise((r) => setTimeout(r, RETRY_DELAY_MS))
|
| 129 |
}
|
| 130 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 131 |
}
|
|
|
|
| 1 |
+
import { Client, GatewayIntentBits, Partials, WebSocketShardEvents } from 'discord.js'
|
| 2 |
import { Agent } from 'undici'
|
| 3 |
import { readdirSync } from 'node:fs'
|
| 4 |
import { resolve, dirname } from 'node:path'
|
|
|
|
| 6 |
|
| 7 |
const __dirname = dirname(fileURLToPath(import.meta.url))
|
| 8 |
|
| 9 |
+
const RACE_CONCURRENCY = 5 // parallel attempts per round
|
| 10 |
+
const MAX_RETRIES = -1 // -1 = retry forever
|
| 11 |
+
const BASE_RETRY_DELAY = 2_000 // starting backoff (ms)
|
| 12 |
+
const MAX_RETRY_DELAY = 30_000 // cap backoff at 30s
|
| 13 |
+
const ATTEMPT_TIMEOUT = 90_000 // per-slot timeout (ms) β long enough for slow HF network
|
| 14 |
+
|
| 15 |
+
function sleep(ms) {
|
| 16 |
+
return new Promise((r) => setTimeout(r, ms))
|
| 17 |
+
}
|
| 18 |
+
|
| 19 |
+
// Exponential backoff with jitter so all slots don't slam at once
|
| 20 |
+
function backoff(round) {
|
| 21 |
+
const exp = Math.min(BASE_RETRY_DELAY * 2 ** (round - 1), MAX_RETRY_DELAY)
|
| 22 |
+
const jitter = Math.random() * 1000
|
| 23 |
+
return exp + jitter
|
| 24 |
+
}
|
| 25 |
|
|
|
|
|
|
|
|
|
|
| 26 |
function createClient() {
|
| 27 |
return new Client({
|
| 28 |
intents: [
|
|
|
|
| 32 |
GatewayIntentBits.MessageContent,
|
| 33 |
],
|
| 34 |
partials: [Partials.GuildMember],
|
| 35 |
+
|
| 36 |
+
// Override the REST HTTP agent β helps with the initial token auth request
|
| 37 |
rest: {
|
| 38 |
+
agent: new Agent({
|
| 39 |
+
connect: {
|
| 40 |
+
timeout: ATTEMPT_TIMEOUT,
|
| 41 |
+
rejectUnauthorized: false,
|
| 42 |
+
minVersion: 'TLSv1.2',
|
| 43 |
+
keepAlive: true,
|
| 44 |
+
},
|
| 45 |
+
}),
|
| 46 |
+
},
|
| 47 |
+
|
| 48 |
+
// WebSocket options β this is where the gateway connection lives
|
| 49 |
+
ws: {
|
| 50 |
+
large_threshold: 50,
|
| 51 |
},
|
| 52 |
})
|
| 53 |
}
|
| 54 |
|
| 55 |
// Single connection attempt β resolves with the ready client or rejects on failure
|
| 56 |
+
function attemptLogin(token, label) {
|
| 57 |
return new Promise((resolve, reject) => {
|
| 58 |
const c = createClient()
|
| 59 |
|
| 60 |
+
const timer = setTimeout(() => {
|
|
|
|
|
|
|
| 61 |
c.destroy()
|
| 62 |
+
reject(new Error(`${label} timed out after ${ATTEMPT_TIMEOUT / 1000}s`))
|
| 63 |
+
}, ATTEMPT_TIMEOUT)
|
| 64 |
|
| 65 |
c.once('clientReady', () => {
|
| 66 |
+
clearTimeout(timer)
|
| 67 |
resolve(c)
|
| 68 |
})
|
| 69 |
|
| 70 |
+
// Catch gateway-level errors before clientReady fires
|
| 71 |
+
c.ws.once('error', (err) => {
|
| 72 |
+
clearTimeout(timer)
|
| 73 |
+
c.destroy()
|
| 74 |
+
reject(err)
|
| 75 |
+
})
|
| 76 |
+
|
| 77 |
c.login(token).catch((err) => {
|
| 78 |
+
clearTimeout(timer)
|
| 79 |
c.destroy()
|
| 80 |
reject(err)
|
| 81 |
})
|
|
|
|
| 88 |
let settled = false
|
| 89 |
let failures = 0
|
| 90 |
|
| 91 |
+
Array.from({ length: RACE_CONCURRENCY }, (_, i) => {
|
| 92 |
+
const label = `round=${round} slot=${i + 1}`
|
| 93 |
+
// Stagger launches slightly so they don't all hit the same DNS resolution
|
| 94 |
+
return sleep(i * 300).then(() => attemptLogin(token, label))
|
| 95 |
+
}).forEach((p, i) => {
|
| 96 |
p.then((winner) => {
|
| 97 |
+
if (settled) { winner.destroy(); return }
|
|
|
|
|
|
|
|
|
|
| 98 |
settled = true
|
| 99 |
+
console.log(`[bot] Connected! (round=${round} slot=${i + 1})`)
|
| 100 |
resolve(winner)
|
| 101 |
}).catch((err) => {
|
| 102 |
failures++
|
| 103 |
+
console.warn(`[bot] Slot ${i + 1} failed: ${err.message}`)
|
| 104 |
if (!settled && failures === RACE_CONCURRENCY) {
|
| 105 |
reject(new Error(`All ${RACE_CONCURRENCY} attempts failed in round ${round}`))
|
| 106 |
}
|
|
|
|
| 109 |
})
|
| 110 |
}
|
| 111 |
|
| 112 |
+
async function connectWithRetry(token) {
|
| 113 |
+
let round = 0
|
| 114 |
+
while (true) {
|
| 115 |
+
round++
|
| 116 |
+
const label = MAX_RETRIES === -1 ? 'β' : MAX_RETRIES
|
| 117 |
+
console.log(`[bot] Connecting... (round ${round}/${label})`)
|
| 118 |
+
|
| 119 |
+
try {
|
| 120 |
+
return await raceConnections(token, round)
|
| 121 |
+
} catch (err) {
|
| 122 |
+
const delay = backoff(round)
|
| 123 |
+
console.error(`[bot] Round ${round} failed β retrying in ${(delay / 1000).toFixed(1)}s`)
|
| 124 |
+
await sleep(delay)
|
| 125 |
+
}
|
| 126 |
+
}
|
| 127 |
+
}
|
| 128 |
+
|
| 129 |
// Exported client reference β populated once connected
|
| 130 |
export let client = null
|
| 131 |
|
|
|
|
| 133 |
const token = process.env.DISCORD_TOKEN
|
| 134 |
if (!token) throw new Error('Missing required environment variable: DISCORD_TOKEN')
|
| 135 |
|
| 136 |
+
// Load all event modules once upfront
|
| 137 |
const eventsDir = resolve(__dirname, 'events')
|
| 138 |
const eventFiles = readdirSync(eventsDir).filter((f) => f.endsWith('.js'))
|
| 139 |
const events = await Promise.all(
|
| 140 |
eventFiles.map((file) => import(pathToFileURL(resolve(eventsDir, file)).href))
|
| 141 |
)
|
| 142 |
|
| 143 |
+
function registerEvents(c) {
|
| 144 |
+
for (const event of events) {
|
| 145 |
+
if (event.once) {
|
| 146 |
+
c.once(event.name, (...args) => event.execute(...args))
|
| 147 |
+
} else {
|
| 148 |
+
c.on(event.name, (...args) => event.execute(...args))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 149 |
}
|
|
|
|
|
|
|
|
|
|
| 150 |
}
|
| 151 |
}
|
| 152 |
+
|
| 153 |
+
const winner = await connectWithRetry(token)
|
| 154 |
+
registerEvents(winner)
|
| 155 |
+
client = winner
|
| 156 |
+
|
| 157 |
+
// Auto-reconnect if the bot disconnects mid-session (HF network flakiness)
|
| 158 |
+
client.on('shardDisconnect', async (event, shardId) => {
|
| 159 |
+
console.warn(`[bot] Shard ${shardId} disconnected (code=${event.code}) β reconnecting...`)
|
| 160 |
+
// discord.js handles most reconnects internally; this catches fatal closes
|
| 161 |
+
if (event.code === 1000 || event.code === 4000) {
|
| 162 |
+
client.destroy()
|
| 163 |
+
const newClient = await connectWithRetry(token)
|
| 164 |
+
registerEvents(newClient)
|
| 165 |
+
client = newClient
|
| 166 |
+
}
|
| 167 |
+
})
|
| 168 |
}
|