File size: 9,135 Bytes
eb5d055
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
const express = require('express');
const http = require('http');
const { Server } = require('socket.io');
const mineflayer = require('mineflayer');
const path = require('path');

const app = express();
const server = http.createServer(app);
const io = new Server(server, {
    cors: {
        origin: "*",
        methods: ["GET", "POST"]
    }
});

const PORT = process.env.PORT || 7860;

// Store active bots
const activeBots = new Map();

// Middleware
app.use(express.json());
app.use(express.static('public'));

// Health check endpoint
app.get('/health', (req, res) => {
    res.json({ status: true, uptime: process.uptime(), bots: activeBots.size });
});

// API Routes
app.get('/api/bots', (req, res) => {
    const bots = Array.from(activeBots.entries()).map(([id, data]) => ({
        id,
        username: data.bot.username,
        host: data.host,
        port: data.port,
        connected: data.connected,
        players: data.players || []
    }));
    res.json(bots);
});

// Socket.IO Connection
io.on('connection', (socket) => {
    console.log('Client connected:', socket.id);

    let currentBot = null;
    let botId = null;

    // Connect bot to Minecraft server
    socket.on('connect-bot', (config) => {
        const { username, host, port = 25565, version } = config;

        if (!username || !host) {
            socket.emit('error', { message: 'Username and host are required' });
            return;
        }

        // Disconnect existing bot for this socket
        if (currentBot) {
            currentBot.quit();
            activeBots.delete(botId);
        }

        botId = `${socket.id}_${Date.now()}`;

        try {
            const bot = mineflayer.createBot({
                host: host,
                port: parseInt(port),
                username: username,
                version: version || false,
                auth: 'offline',
                hideErrors: true
            });

            currentBot = bot;

            const botData = {
                bot: bot,
                socket: socket,
                host: host,
                port: port,
                connected: false,
                players: [],
                chatHistory: []
            };

            activeBots.set(botId, botData);

            // Bot Events
            bot.on('login', () => {
                botData.connected = true;
                socket.emit('bot-status', {
                    status: 'online',
                    username: bot.username,
                    host: host,
                    port: port
                });
                console.log(`Bot ${username} connected to ${host}:${port}`);
            });

            bot.on('spawn', () => {
                socket.emit('bot-spawned', {
                    position: bot.entity?.position,
                    health: bot.health,
                    food: bot.food
                });
                updatePlayersList(bot, socket);
            });

            bot.on('chat', (username, message) => {
                if (username === bot.username) return;

                const chatData = {
                    username: username,
                    message: message,
                    timestamp: new Date().toISOString(),
                    type: 'chat'
                };

                botData.chatHistory.push(chatData);
                socket.emit('chat-message', chatData);
            });

            bot.on('message', (jsonMsg) => {
                const text = jsonMsg.toString();
                if (text && !text.includes(bot.username)) {
                    socket.emit('system-message', {
                        message: text,
                        timestamp: new Date().toISOString()
                    });
                }
            });

            bot.on('playerJoined', (player) => {
                socket.emit('player-joined', {
                    username: player.username,
                    timestamp: new Date().toISOString()
                });
                updatePlayersList(bot, socket);
            });

            bot.on('playerLeft', (player) => {
                socket.emit('player-left', {
                    username: player.username,
                    timestamp: new Date().toISOString()
                });
                updatePlayersList(bot, socket);
            });

            bot.on('health', () => {
                socket.emit('bot-health', {
                    health: bot.health,
                    food: bot.food
                });
            });

            bot.on('death', () => {
                socket.emit('bot-death', {
                    message: 'Bot died!',
                    timestamp: new Date().toISOString()
                });
            });

            bot.on('kicked', (reason) => {
                socket.emit('bot-kicked', {
                    reason: reason.toString(),
                    timestamp: new Date().toISOString()
                });
                cleanupBot(botId);
            });

            bot.on('error', (err) => {
                console.error('Bot error:', err.message);
                socket.emit('bot-error', {
                    message: err.message,
                    timestamp: new Date().toISOString()
                });
            });

            bot.on('end', (reason) => {
                socket.emit('bot-disconnected', {
                    reason: reason || 'Connection closed',
                    timestamp: new Date().toISOString()
                });
                cleanupBot(botId);
            });

        } catch (error) {
            socket.emit('error', { message: error.message });
        }
    });

    // Send chat message
    socket.on('send-chat', (message) => {
        if (currentBot && currentBot.chat) {
            currentBot.chat(message);
            socket.emit('chat-sent', {
                username: currentBot.username,
                message: message,
                timestamp: new Date().toISOString()
            });
        }
    });

    // Send command
    socket.on('send-command', (command) => {
        if (currentBot && currentBot.chat) {
            currentBot.chat(command);
        }
    });

    // Bot actions
    socket.on('bot-action', (action) => {
        if (!currentBot) return;

        switch(action.type) {
            case 'jump':
                currentBot.setControlState('jump', true);
                setTimeout(() => currentBot.setControlState('jump', false), 500);
                break;
            case 'sneak':
                currentBot.setControlState('sneak', true);
                setTimeout(() => currentBot.setControlState('sneak', false), 1000);
                break;
            case 'look':
                if (action.x !== undefined && action.y !== undefined && action.z !== undefined) {
                    const Vec3 = require('vec3');
                    currentBot.lookAt(new Vec3(action.x, action.y, action.z));
                }
                break;
            case 'move':
                if (action.direction) {
                    currentBot.setControlState(action.direction, true);
                    setTimeout(() => currentBot.setControlState(action.direction, false), 500);
                }
                break;
        }
    });

    // Disconnect bot
    socket.on('disconnect-bot', () => {
        if (currentBot) {
            currentBot.quit();
            cleanupBot(botId);
            currentBot = null;
            botId = null;
        }
    });

    // Get players list
    socket.on('get-players', () => {
        if (currentBot) {
            updatePlayersList(currentBot, socket);
        }
    });

    // Disconnect handler
    socket.on('disconnect', () => {
        console.log('Client disconnected:', socket.id);
        if (currentBot) {
            currentBot.quit();
            cleanupBot(botId);
        }
    });
});

function updatePlayersList(bot, socket) {
    if (!bot.players) return;

    const players = Object.values(bot.players).map(p => ({
        username: p.username,
        ping: p.ping,
        uuid: p.uuid
    }));

    socket.emit('players-list', players);
}

function cleanupBot(id) {
    if (activeBots.has(id)) {
        const data = activeBots.get(id);
        if (data.bot) {
            try {
                data.bot.quit();
                data.bot.removeAllListeners();
            } catch (e) {}
        }
        activeBots.delete(id);
    }
}

// Start server
server.listen(PORT, () => {
    console.log(`🎮 Minecraft Bot Controller running on port ${PORT}`);
    console.log(`🌐 Access the web interface at http://localhost:${PORT}`);
});

// Graceful shutdown
process.on('SIGTERM', () => {
    console.log('SIGTERM received, shutting down gracefully');
    activeBots.forEach((data, id) => {
        cleanupBot(id);
    });
    server.close(() => {
        process.exit(0);
    });
});

process.on('SIGINT', () => {
    console.log('SIGINT received, shutting down gracefully');
    activeBots.forEach((data, id) => {
        cleanupBot(id);
    });
    server.close(() => {
        process.exit(0);
    });
});