-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathindex.js
More file actions
390 lines (345 loc) Β· 13.3 KB
/
index.js
File metadata and controls
390 lines (345 loc) Β· 13.3 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
/**
* Minecraft Server Status Bot
* Created by Team BLK
*
* YouTube: https://www.youtube.com/@team_blk_official
* Discord: adithyadev.blk
* GitHub: https://github.com/BLKOFFICIAL
*/
const { Client, GatewayIntentBits, EmbedBuilder, ActivityType, AttachmentBuilder } = require('discord.js');
const util = require('minecraft-server-util');
const config = require('./config.json');
const chalk = require('chalk');
const { createCanvas } = require('canvas');
const { Chart } = require('chart.js/auto');
// Initialize Discord client with intents
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages,
]
});
// Store server status messages and intervals
const statusMessages = new Map();
const updateIntervals = new Map();
const playerHistory = new Map(); // Store player count history
// Fancy console logging
const log = {
info: (msg) => console.log(chalk.blue('βΉοΈ [INFO]'), msg),
success: (msg) => console.log(chalk.green('β
[SUCCESS]'), msg),
error: (msg) => console.log(chalk.red('β [ERROR]'), msg),
warn: (msg) => console.log(chalk.yellow('β οΈ [WARN]'), msg)
};
// Initialize player history for a server
function initializePlayerHistory(serverId) {
if (!playerHistory.has(serverId)) {
playerHistory.set(serverId, []);
}
}
// Add player count to history
function updatePlayerHistory(serverId, playerCount, maxHistory = 24) {
const history = playerHistory.get(serverId) || [];
const currentTime = Date.now();
// If history is empty or it's been an hour since last record
if (history.length === 0 ||
(currentTime - history[history.length - 1].timestamp) >= 3600000) { // 1 hour in milliseconds
history.push({
timestamp: currentTime,
count: playerCount
});
// Keep only last 24 records
if (history.length > maxHistory) {
history.shift(); // Remove oldest record
}
playerHistory.set(serverId, history);
} else {
// Update the latest record if within the same hour
history[history.length - 1].count = playerCount;
playerHistory.set(serverId, history);
}
}
// Generate player count chart
async function generatePlayerChart(serverId, color = '#3498db') {
const history = playerHistory.get(serverId) || [];
if (history.length < 2) return null;
const width = 800;
const height = 400;
const canvas = createCanvas(width, height);
const ctx = canvas.getContext('2d');
// Set background
ctx.fillStyle = '#2F3136';
ctx.fillRect(0, 0, width, height);
const labels = history.map(entry => {
const date = new Date(entry.timestamp);
return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
});
const data = history.map(entry => entry.count);
new Chart(ctx, {
type: 'line',
data: {
labels,
datasets: [{
label: 'Player Count',
data,
borderColor: color,
backgroundColor: color + '33', // Add transparency
borderWidth: 2,
tension: 0.4,
fill: true,
pointRadius: 4,
pointHoverRadius: 6
}]
},
options: {
responsive: false,
animation: false, // Disable animations for static image
plugins: {
legend: {
labels: {
color: '#FFFFFF',
font: {
size: 14
}
}
},
title: {
display: true,
text: 'Player Count History',
color: '#FFFFFF',
font: {
size: 16,
weight: 'bold'
}
}
},
scales: {
y: {
beginAtZero: true,
grid: {
color: '#666666',
drawBorder: false
},
ticks: {
color: '#FFFFFF',
font: {
size: 12
},
padding: 10
}
},
x: {
grid: {
color: '#666666',
drawBorder: false
},
ticks: {
color: '#FFFFFF',
font: {
size: 12
},
maxRotation: 45,
minRotation: 45
}
}
},
layout: {
padding: 20
}
}
});
return canvas.toBuffer('image/png');
}
// Bot ready event
client.once('ready', () => {
log.success(`Logged in as ${client.user.tag}`);
// Set custom presence from config
const presence = config.bot.presence;
client.user.setPresence({
status: presence.status,
activities: presence.activities.map(activity => ({
name: activity.name,
type: ActivityType[activity.type]
}))
});
// Initialize status updates for all configured servers
initializeStatusUpdates();
});
async function checkServerStatus(ip, port = 25565) {
try {
const result = await util.status(ip, port);
return {
online: true,
players: result.players.online,
maxPlayers: result.players.max,
version: result.version.name,
description: result.motd.clean,
ping: result.roundTripLatency
};
} catch (error) {
log.error(`Failed to check status for ${ip}:${port} - ${error.message}`);
return {
online: false,
error: error.message
};
}
}
async function updateServerStatus(serverConfig) {
const channel = await client.channels.fetch(serverConfig.channelId).catch(() => null);
if (!channel) {
log.error(`Channel ${serverConfig.channelId} not found for server ${serverConfig.name}`);
return;
}
const status = await checkServerStatus(serverConfig.ip, serverConfig.port);
// Update player history if server is online
if (status.online) {
initializePlayerHistory(serverConfig.channelId);
updatePlayerHistory(serverConfig.channelId, status.players, serverConfig.display.chart.historyHours);
}
const embed = new EmbedBuilder()
.setTitle(config.embed.title)
.setColor(status.online ? config.embed.colors.online : config.embed.colors.offline)
.setTimestamp();
// Add banner if enabled
if (serverConfig.display.type === 'banner' && serverConfig.display.banner.enabled) {
embed.setImage(serverConfig.display.banner.url);
}
// Add server info fields
embed.addFields(
{ name: 'π‘ Server', value: `${serverConfig.name} (${serverConfig.ip}:${serverConfig.port})`, inline: true },
{ name: 'π Status', value: status.online ? 'β
Online' : 'β Offline', inline: true }
);
if (status.online) {
embed.addFields(
{ name: 'π₯ Players', value: `${status.players}/${status.maxPlayers}`, inline: true },
{ name: 'π·οΈ Version', value: status.version, inline: true },
{ name: 'π Ping', value: `${status.ping}ms`, inline: true },
{ name: 'π MOTD', value: status.description || 'No description available' }
);
// Add next update timestamp if enabled
if (serverConfig.display.showNextUpdate) {
const nextUpdate = Math.floor((Date.now() + serverConfig.updateInterval) / 1000);
embed.addFields({
name: 'β±οΈ Next Update',
value: `<t:${nextUpdate}:R>`,
inline: true
});
}
} else {
embed.addFields(
{ name: 'β Error', value: status.error || 'Could not connect to server' }
);
}
embed.setFooter(config.embed.footer);
const files = [];
// Generate and add player chart if enabled
if (serverConfig.display.type === 'chart' && serverConfig.display.chart.enabled && status.online) {
try {
const chartBuffer = await generatePlayerChart(
serverConfig.channelId,
serverConfig.display.chart.color
);
if (chartBuffer) {
const attachment = new AttachmentBuilder(chartBuffer, { name: 'player-chart.png' });
files.push(attachment);
embed.setImage('attachment://player-chart.png');
}
} catch (error) {
log.error(`Failed to generate player chart: ${error.message}`);
}
}
const existingMessage = statusMessages.get(serverConfig.channelId);
try {
if (existingMessage) {
await existingMessage.edit({ embeds: [embed], files });
} else {
const message = await channel.send({ embeds: [embed], files });
statusMessages.set(serverConfig.channelId, message);
}
log.info(`Updated status for ${serverConfig.name}`);
} catch (error) {
log.error(`Failed to update status message for ${serverConfig.name} - ${error.message}`);
}
}
function initializeStatusUpdates() {
// Clear any existing intervals
for (const interval of updateIntervals.values()) {
clearInterval(interval);
}
updateIntervals.clear();
// Set up new intervals for each server
for (const server of config.minecraft.servers) {
// Initial update
updateServerStatus(server);
// Set up periodic updates
const interval = setInterval(() => updateServerStatus(server), server.updateInterval);
updateIntervals.set(server.channelId, interval);
log.info(`Initialized status updates for ${server.name} (${server.ip}:${server.port})`);
}
}
// Status command handler
client.on('interactionCreate', async interaction => {
if (!interaction.isCommand()) return;
if (interaction.commandName === 'status') {
const serverName = interaction.options.getString('server');
const server = config.minecraft.servers.find(s => s.name.toLowerCase() === serverName.toLowerCase());
if (!server) {
await interaction.reply({
content: `Server "${serverName}" not found in configuration!`,
ephemeral: true
});
return;
}
const status = await checkServerStatus(server.ip, server.port);
const embed = new EmbedBuilder()
.setTitle(`${server.name} Status`)
.setColor(status.online ? config.embed.colors.online : config.embed.colors.offline)
.setTimestamp()
.setFooter(config.embed.footer);
if (status.online) {
embed.addFields(
{ name: 'π Status', value: 'β
Online', inline: true },
{ name: 'π₯ Players', value: `${status.players}/${status.maxPlayers}`, inline: true },
{ name: 'π Ping', value: `${status.ping}ms`, inline: true },
{ name: 'π·οΈ Version', value: status.version }
);
if (server.display.showNextUpdate) {
const nextUpdate = Math.floor((Date.now() + server.updateInterval) / 1000);
embed.addFields({
name: 'β±οΈ Next Update',
value: `<t:${nextUpdate}:R>`,
inline: true
});
}
} else {
embed.addFields(
{ name: 'π Status', value: 'β Offline', inline: true },
{ name: 'β Error', value: status.error || 'Could not connect to server' }
);
}
const files = [];
if (server.display.type === 'chart' && server.display.chart.enabled && status.online) {
try {
const chartBuffer = await generatePlayerChart(
server.channelId,
server.display.chart.color
);
if (chartBuffer) {
const attachment = new AttachmentBuilder(chartBuffer, { name: 'player-chart.png' });
files.push(attachment);
embed.setImage('attachment://player-chart.png');
}
} catch (error) {
log.error(`Failed to generate player chart: ${error.message}`);
}
} else if (server.display.type === 'banner' && server.display.banner.enabled) {
embed.setImage(server.display.banner.url);
}
await interaction.reply({
embeds: [embed],
files,
ephemeral: true
});
}
});
// Start the bot
client.login(config.bot.token);