const express = require('express') const http = require('http') const { Server } = require('socket.io') const { v4: uuidv4 } = require('uuid') const { createBotInstance } = require('./index') const app = express() const server = http.createServer(app) const io = new Server(server) app.use(express.json()) const bots = {} // ================= BOT START ================= function startBot(id, cfg) { bots[id] = bots[id] || { logs: [], instance: null, stopped: false, config: cfg } const b = bots[id] const log = (msg) => { const line = `[${new Date().toLocaleTimeString()}] ${msg}` b.logs.push(line) if (b.logs.length > 200) b.logs.shift() io.emit('log', { id, msg: line }) } log(`[SYSTEM] start ${cfg.name}`) if (b.instance) { try { b.instance.quit() } catch {} } b.instance = createBotInstance(cfg, log, () => { if (!b.stopped) { log(`[SYSTEM] reconnecting...`) setTimeout(() => startBot(id, cfg), 10000) } }) } // ================= API ================= app.post('/api/create', (req, res) => { const id = uuidv4().slice(0, 6) const cfg = { name: req.body.name || `AFK_${id}`, host: req.body.ip, port: parseInt(req.body.port || 25565), version: req.body.version || false, password: req.body.password || "11111111" } startBot(id, cfg) res.json({ id }) }) app.get('/api/list', (req, res) => { const out = {} for (const id in bots) { out[id] = { name: bots[id].config.name, running: !!bots[id].instance } } res.json(out) }) app.post('/api/stop/:id', (req, res) => { const b = bots[req.params.id] if (!b) return res.json({ ok: false }) b.stopped = true try { b.instance?.quit() } catch {} b.instance = null res.json({ ok: true }) }) app.post('/api/restart/:id', (req, res) => { const b = bots[req.params.id] if (!b) return res.json({ ok: false }) b.stopped = false startBot(req.params.id, b.config) res.json({ ok: true }) }) app.get('/api/logs/:id', (req, res) => { res.json(bots[req.params.id]?.logs || []) }) // ================= UI ================= app.get('/', (req, res) => { res.send(`