Repository navigation
Expand file tree
/
Copy pathserver.js
More file actions
502 lines (433 loc) · 18.1 KB
/
Copy pathserver.js
File metadata and controls
502 lines (433 loc) · 18.1 KB
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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
'use strict';
const http = require('http');
const fs = require('fs');
const path = require('path');
// ── Patch Transfer Packet ─────────────────────────────────────────────────────
// DEVE vir antes do require(mineflayer) para garantir que o cache do Node.js
// já tem o tipo definido quando o mineflayer/minecraft-protocol inicializa.
// O Velocity envia o Transfer Packet (MC 1.20.5+) para mover players entre
// servidores backend. O minecraft-data mapeia o ID do pacote mas não define o
// tipo "packet_common_transfer", causando erro de decode e disconnect com
// "An internal error occurred in your connection."
try {
const mcData = require(path.join(__dirname, 'node_modules', 'minecraft-data'));
for (const ver of ['1.21', '1.21.1', '1.21.4']) {
try {
const d = mcData(ver);
// O Transfer Packet do Velocity está no estado 'configuration' (0x0b em 1.21.1)
// não no 'play' como assumido antes. Patch nos dois por segurança.
for (const state of ['play', 'configuration']) {
const types = d?.protocol?.[state]?.toClient?.types;
if (types && !types.packet_common_transfer) {
types.packet_common_transfer = [
'container',
[
{ name: 'host', type: 'string' },
{ name: 'port', type: 'varint' },
],
];
}
}
} catch (_) {}
}
} catch (_) {}
// ─────────────────────────────────────────────────────────────────────────────
// Resolve dependências a partir deste arquivo, independente do cwd
const mineflayer = require(path.join(__dirname, 'node_modules', 'mineflayer'));
const mc = require(path.join(__dirname, 'node_modules', 'minecraft-protocol'));
const PORT = process.env.PORT || 3000;
const DATA_FILE = path.join(__dirname, 'data', 'bots.json');
const PUBLIC_DIR = __dirname;
const DEFAULT_NICK = 'RochaBot';
// ── Persistência ─────────────────────────────────────────────────────────────
function loadBots() {
try {
return JSON.parse(fs.readFileSync(DATA_FILE, 'utf8'));
} catch {
return [];
}
}
function saveBots(bots) {
const safe = bots.map(({ id, label, nick, host, port, version, autoConnect }) => ({
id, label, nick, host, port, version: version || '', autoConnect: Boolean(autoConnect),
}));
// Escrita atômica: salva num temp e renomeia para evitar corrompimento
const tmp = DATA_FILE + '.tmp';
fs.writeFileSync(tmp, JSON.stringify(safe, null, 2));
fs.renameSync(tmp, DATA_FILE);
}
// ── Estado em memória ─────────────────────────────────────────────────────────
let botConfigs = loadBots();
const runtime = {};
function getRuntime(id) {
if (!runtime[id]) runtime[id] = { client: null, status: 'offline', log: [], chatLog: [] };
return runtime[id];
}
function pushLog(id, msg) {
const rt = getRuntime(id);
rt.log.push({ t: Date.now(), msg: String(msg) });
if (rt.log.length > 100) rt.log.shift();
}
function pushChat(id, direction, text) {
const rt = getRuntime(id);
rt.chatLog.push({ t: Date.now(), direction, text: String(text) });
if (rt.chatLog.length > 150) rt.chatLog.shift();
}
// ── Auto-detect versão via ping ───────────────────────────────────────────────
function detectVersion(host, port) {
return new Promise((resolve) => {
const timer = setTimeout(() => resolve(null), 5000);
try {
mc.ping({ host, port: Number(port), closeTimeout: 4000 }, (err, result) => {
clearTimeout(timer);
if (err || !result) return resolve(null);
// result.version.name ex: "1.21.4" ou "BungeeCord 1.21.x"
const raw = String(result?.version?.name || result?.version || '');
// Extrair somente "X.Y.Z" ou "X.Y"
const match = raw.match(/\d+\.\d+(?:\.\d+)?/);
resolve(match ? match[0] : null);
});
} catch {
clearTimeout(timer);
resolve(null);
}
});
}
// ── Conexão Minecraft ─────────────────────────────────────────────────────────
async function connectBot(id) {
const cfg = botConfigs.find((b) => b.id === id);
if (!cfg) return;
const rt = getRuntime(id);
if (rt.client && rt.status === 'online') return;
// Desconectar instância anterior
if (rt.client) {
try { rt.client.quit(); } catch (_) {}
rt.client = null;
}
rt.status = 'connecting';
pushLog(id, `Conectando em ${cfg.host}:${cfg.port} como ${cfg.nick}...`);
// Avisa se outro bot online já usa o mesmo nick no mesmo servidor
const conflict = botConfigs.find((b) =>
b.id !== id && b.host === cfg.host && b.port === cfg.port &&
b.nick === cfg.nick && getRuntime(b.id).status === 'online'
);
if (conflict) {
pushLog(id, `AVISO: bot "${conflict.label || conflict.id}" já está online com o nick "${cfg.nick}" no mesmo servidor. O servidor pode kickar um dos dois.`);
}
// Versão: usa a configurada, ou auto-detecta via ping
let version = cfg.version || '';
if (!version) {
pushLog(id, 'Detectando versão do servidor...');
const detected = await detectVersion(cfg.host, cfg.port);
if (detected) {
version = detected;
pushLog(id, `Versão detectada: ${version}`);
} else {
pushLog(id, 'Não foi possível detectar versão, usando 1.21.4 como fallback.');
version = '1.21.4';
}
}
let bot;
try {
bot = mineflayer.createBot({
host: cfg.host,
port: Number(cfg.port),
username: cfg.nick,
version,
auth: 'offline',
keepAlive: true,
checkTimeoutInterval: 30000,
});
} catch (err) {
rt.status = 'error';
pushLog(id, `Erro ao criar bot: ${err.message}`);
return;
}
rt.client = bot;
// Flag para saber se a desconexão foi intencional (pelo painel)
let intentionalDisconnect = false;
// Guarda referência para poder checar depois
rt._setIntentional = () => { intentionalDisconnect = true; };
// ── Velocity server switch (start_configuration) ─────────────────────────
// O Velocity troca o bot de servidor via start_configuration → ciclo de
// configuration → play. O minecraft-protocol já trata isso internamente
// em play.js (client.on('start_configuration', () => enterConfigState())).
// Não precisamos fazer nada aqui — apenas logamos para debug.
const rawClient = bot._client;
if (rawClient) {
rawClient.on('start_configuration', () => {
if (intentionalDisconnect) return;
pushLog(id, 'Velocity: trocando de servidor, aguardando reconexão...');
rt.status = 'connecting';
});
rawClient.on('login', () => {
if (intentionalDisconnect) return;
if (rt.status === 'connecting') {
rt.status = 'online';
pushLog(id, 'Reconectado no novo servidor via Velocity.');
}
});
}
// ─────────────────────────────────────────────────────────────────────────
bot.on('login', () => {
rt.status = 'online';
pushLog(id, `Online no servidor. (v${version})`);
});
// spawn é emitido pelo mineflayer toda vez que entra num mundo — inclui após troca de servidor via Velocity
bot.on('spawn', () => {
if (rt.status === 'connecting') {
rt.status = 'online';
pushLog(id, 'Reconectado no novo servidor via Velocity.');
}
});
bot.on('chat', (username, message) => {
if (username === bot.username) return;
pushChat(id, 'in', `<${username}> ${message}`);
});
bot.on('message', (jsonMsg) => {
const text = jsonMsg.toString().trim();
if (text) pushChat(id, 'system', text);
});
bot.on('kicked', (reason) => {
if (intentionalDisconnect) return;
// reason pode ser string JSON, string plana, objeto JSON ou NBT compound
let msg = '';
let rawReason = reason;
try {
if (typeof reason === 'string') {
const parsed = JSON.parse(reason);
rawReason = parsed;
msg = parsed?.text || parsed?.translate || parsed?.extra?.[0]?.text || reason;
} else if (typeof reason === 'object' && reason !== null) {
rawReason = reason;
// NBT compound: { type: 'compound', value: { text: { type: 'string', value: '...' } } }
if (reason.type === 'compound' && reason.value) {
msg = reason.value?.text?.value || reason.value?.translate?.value || JSON.stringify(reason);
} else {
msg = reason.text || reason.translate || reason.extra?.[0]?.text || JSON.stringify(reason);
}
}
} catch (_) {
msg = String(reason);
}
pushLog(id, `[kicked raw] ${JSON.stringify(rawReason)}`);
const lower = msg.toLowerCase();
const rawStr = JSON.stringify(rawReason).toLowerCase();
const isTransfer =
lower.includes('transfer') || lower.includes('moving') ||
lower.includes('connecting') || lower.includes('please wait') ||
rawStr.includes('transfer') || rawStr.includes('switchserver') ||
rawStr.includes('connect_to');
if (isTransfer) {
pushLog(id, `Transfer de servidor detectado, reconectando...`);
rt.client = null;
rt.status = 'connecting';
setTimeout(() => {
if (!intentionalDisconnect && runtime[id]?.status === 'connecting') connectBot(id);
}, 1500);
return;
}
rt.status = 'offline';
rt.client = null;
pushLog(id, `Kickado: ${msg}`);
});
bot.on('error', (err) => {
if (intentionalDisconnect || rt.status === 'offline' || rt.status === 'connecting') return;
const msg = String(err && err.message || '').toLowerCase();
// Erros de decode de pacote são tratados pelo handler do rawClient — ignorar aqui
if (msg.includes('packet') || msg.includes('decode') || msg.includes('invalid data')) return;
rt.status = 'error';
rt.client = null;
pushLog(id, `Erro: ${err.message}`);
});
bot.on('end', (reason) => {
if (intentionalDisconnect) return;
const lower = String(reason || '').toLowerCase();
// Velocity transfer: reconecta automaticamente após breve delay
const isTransfer = lower.includes('transfer') || lower.includes('switchproxycommand') ||
lower === '' || lower === 'socketclosed' || lower === 'end';
if (isTransfer && rt.status !== 'offline') {
pushLog(id, `Troca de servidor (${reason || 'transfer'}), reconectando em 1.5s...`);
rt.client = null;
rt.status = 'connecting';
setTimeout(() => {
// Só reconecta se ainda não foi desconectado manualmente
if (!intentionalDisconnect && runtime[id]?.status === 'connecting') {
connectBot(id);
}
}, 1500);
return;
}
if (rt.status !== 'offline') {
rt.status = 'offline';
rt.client = null;
pushLog(id, `Desconectado: ${reason || 'conexão encerrada'}`);
}
});
}
function disconnectBot(id) {
const rt = getRuntime(id);
// Sinaliza desconexão intencional antes do quit para ignorar eventos end/error
if (rt._setIntentional) rt._setIntentional();
if (rt.client) {
try { rt.client.quit('Desconectado pelo painel'); } catch (_) {}
rt.client = null;
}
rt.status = 'offline';
rt._setIntentional = null;
pushLog(id, 'Desconectado pelo painel.');
}
function sendChat(id, message) {
const rt = getRuntime(id);
if (!rt.client || rt.status !== 'online') return false;
try {
rt.client.chat(message);
const nick = botConfigs.find((b) => b.id === id)?.nick || '?';
pushChat(id, 'out', `<${nick}> ${message}`);
return true;
} catch (err) {
pushLog(id, `Erro ao enviar: ${err.message}`);
return false;
}
}
// Auto-connect na inicialização
botConfigs.forEach((cfg) => { if (cfg.autoConnect) connectBot(cfg.id); });
// ── HTTP helpers ──────────────────────────────────────────────────────────────
function send(res, status, headers, body) {
res.writeHead(status, headers);
res.end(body);
}
function json(res, status, data) {
send(res, status, { 'Content-Type': 'application/json; charset=utf-8' }, JSON.stringify(data));
}
function readBody(req) {
return new Promise((resolve, reject) => {
let body = '';
req.on('data', (c) => { body += c; if (body.length > 32768) reject(new Error('body too large')); });
req.on('end', () => { try { resolve(JSON.parse(body || '{}')); } catch { resolve({}); } });
req.on('error', reject);
});
}
function newId() {
return `bot_${Date.now()}_${Math.floor(Math.random() * 9000) + 1000}`;
}
// ── API ───────────────────────────────────────────────────────────────────────
async function handleApi(req, res, pathname) {
// GET /api/bots
if (req.method === 'GET' && pathname === '/api/bots') {
return json(res, 200, {
ok: true,
bots: botConfigs.map((cfg) => {
const rt = getRuntime(cfg.id);
return { ...cfg, status: rt.status, log: rt.log.slice(-30), chatLog: rt.chatLog.slice(-50) };
}),
});
}
// POST /api/bots — criar
if (req.method === 'POST' && pathname === '/api/bots') {
const body = await readBody(req);
const host = String(body.host || '').trim();
if (!host) return json(res, 400, { ok: false, error: 'host obrigatorio' });
const nick = String(body.nick || DEFAULT_NICK).trim().slice(0, 16) || DEFAULT_NICK;
// Avisa se já existe bot online com mesmo nick no mesmo servidor
const conflict = botConfigs.find((b) =>
b.host === host && b.port === (Number(body.port) || 25565) &&
b.nick === nick && getRuntime(b.id).status === 'online'
);
if (conflict) {
return json(res, 409, {
ok: false,
error: 'nick_conflict',
message: `Já existe um bot online com o nick "${nick}" em ${host}. Use um nick diferente.`,
});
}
const id = newId();
const cfg = {
id,
label: String(body.label || host).trim(),
nick,
host,
port: Number(body.port) || 25565,
version: String(body.version || '').trim(),
autoConnect: Boolean(body.autoConnect),
};
botConfigs.push(cfg);
saveBots(botConfigs);
pushLog(id, 'Bot criado.');
if (cfg.autoConnect) connectBot(id);
return json(res, 200, { ok: true, id });
}
// Rotas /:id
const m = pathname.match(/^\/api\/bots\/([^/]+)(\/.*)?$/);
if (!m) return json(res, 404, { ok: false, error: 'rota nao encontrada' });
const id = m[1];
const sub = m[2] || '';
const cfg = botConfigs.find((b) => b.id === id);
if (!cfg) return json(res, 404, { ok: false, error: 'bot nao encontrado' });
// PATCH — editar config
if (req.method === 'PATCH' && sub === '') {
const body = await readBody(req);
if (body.label !== undefined) cfg.label = String(body.label).trim() || cfg.label;
if (body.nick !== undefined) cfg.nick = String(body.nick).trim().slice(0, 16) || cfg.nick;
if (body.host !== undefined) cfg.host = String(body.host).trim() || cfg.host;
if (body.port !== undefined) cfg.port = Number(body.port) || cfg.port;
if (body.version !== undefined) cfg.version = String(body.version).trim();
if (body.autoConnect !== undefined) cfg.autoConnect = Boolean(body.autoConnect);
saveBots(botConfigs);
pushLog(id, 'Configuração atualizada.');
return json(res, 200, { ok: true });
}
// DELETE — remover
if (req.method === 'DELETE' && sub === '') {
disconnectBot(id);
botConfigs = botConfigs.filter((b) => b.id !== id);
delete runtime[id];
saveBots(botConfigs);
return json(res, 200, { ok: true });
}
// POST /connect
if (req.method === 'POST' && sub === '/connect') {
connectBot(id); // async, não aguarda
return json(res, 200, { ok: true });
}
// POST /disconnect
if (req.method === 'POST' && sub === '/disconnect') {
disconnectBot(id);
return json(res, 200, { ok: true });
}
// POST /chat
if (req.method === 'POST' && sub === '/chat') {
const body = await readBody(req);
const message = String(body.message || '').trim();
if (!message) return json(res, 400, { ok: false, error: 'mensagem vazia' });
const ok = sendChat(id, message);
return json(res, ok ? 200 : 409, { ok, error: ok ? undefined : 'bot offline' });
}
return json(res, 404, { ok: false, error: 'rota nao encontrada' });
}
// ── Servidor ──────────────────────────────────────────────────────────────────
const server = http.createServer(async (req, res) => {
const url = new URL(req.url, 'http://localhost');
const pathname = url.pathname;
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PATCH, DELETE, OPTIONS');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
if (req.method === 'OPTIONS') return send(res, 204, {}, '');
if (pathname.startsWith('/api/')) {
try {
await handleApi(req, res, pathname);
} catch (err) {
json(res, 500, { ok: false, error: err.message });
}
return;
}
try {
const data = fs.readFileSync(path.join(PUBLIC_DIR, 'index.html'));
send(res, 200, { 'Content-Type': 'text/html; charset=utf-8' }, data);
} catch {
send(res, 404, { 'Content-Type': 'text/plain' }, 'not found');
}
});
server.listen(PORT, () => {
console.log(`Rocha Bot Manager rodando na porta ${PORT}`);
});