Files
bot.js
package.json
Code
2 201
bot.js
const { Client, GatewayIntentBits, EmbedBuilder, ActivityType, REST, Routes } = require('discord.js');
const { status } = require('minecraft-server-util');
require('dotenv').config();
const client = new Client({
intents: [
GatewayIntentBits.Guilds
]
});
const SERVER_HOST = 'eu-19.axyron.cloud';
const SERVER_PORT = 6637;
const MAX_PLAYERS = 150;
const STATUS_UPDATE_INTERVAL = 60000;
let statusMessageId = null;
const commands = [
{
name: 'ip',
description: 'Shows the Minecraft server IP address'
}
];
async function registerCommands() {
const rest = new REST({ version: '10' }).setToken(process.env.DISCORD_TOKEN);
try {
await rest.put(
Routes.applicationCommands(client.user.id),
{ body: commands }
);
console.log('Slash commands registered.');
} catch (err) {
console.error('Failed to register slash commands:', err);
}
}
async function fetchServerStatus() {
try {
const result = await status(SERVER_HOST, SERVER_PORT, { timeout: 5000 });
return {
online: true,
players: result.players.online,
motd: result.motd?.clean ?? 'Minecraft Server'
};
} catch {
return {
online: false,
players: 0,
motd: null
};
}
}
function buildStatusEmbed(serverData) {
const embed = new EmbedBuilder();
if (serverData.online) {
embed
.setTitle('๐ข Server Online')
.setColor(0x57F287)
.addFields(
{
name: '๐ก IP Address',
value: `\`${SERVER_HOST}:${SERVER_PORT}\``,
inline: false
},
{
name: '๐ฅ Players Online',
value: `\`${serverData.players}/${MAX_PLAYERS}\``,
inline: true
},
{
name: '๐ Server Load',
value: buildPlayerBar(serverData.players, MAX_PLAYERS),
inline: true
}
)
.setFooter({ text: 'Last updated' })
.setTimestamp();
} else {
embed
.setTitle('๐ด Server Offline')
.setColor(0xED4245)
.addFields(
{
name: '๐ก IP Address',
value: `\`${SERVER_HOST}:${SERVER_PORT}\``,
inline: false
},
{
name: '๐ญ Status',
value: 'The server is currently **offline** or unreachable.',
inline: false
}
)
.setFooter({ text: 'Last updated' })
.setTimestamp();
}
return embed;
}
function buildPlayerBar(current, max) {
const totalBars = 10;
const filled = Math.round((current / max) * totalBars);
const empty = totalBars - filled;
return `${'โ'.repeat(filled)}${'โ'.repeat(empty)} ${Math.round((current / max) * 100)}%`;
}
async function updateStatusMessage() {
let channel = client.channels.cache.get(process.env.CHANNEL_ID);
if (!channel) {
try {
channel = await client.channels.fetch(process.env.CHANNEL_ID);
} catch (err) {
console.error(`Status channel not found. CHANNEL_ID used: "${process.env.CHANNEL_ID}"`);
console.error(`Fetch error: ${err.message} (code: ${err.code})`);
console.error('Listing all channels the bot can see:');
client.channels.cache.forEach(c => {
console.error(` - [${c.type}] #${c.name ?? 'unknown'} | ID: ${c.id} | Guild: ${c.guild?.name ?? 'DM'}`);
});
return;
}
}
const serverData = await fetchServerStatus();
const embed = buildStatusEmbed(serverData);
client.user.setPresence({
activities: [
{
name: serverData.online
? `${serverData.players}/${MAX_PLAYERS} players online`
: 'Server is offline',
type: ActivityType.Watching
}
],
status: serverData.online ? 'online' : 'dnd'
});
try {
if (statusMessageId) {
const existing = await channel.messages.fetch(statusMessageId).catch(() => null);
if (existing) {
await existing.edit({ embeds: [embed] });
console.log(`[${new Date().toLocaleTimeString()}] Status message updated.`);
return;
}
}
const sent = await channel.send({ embeds: [embed] });
statusMessageId = sent.id;
console.log(`[${new Date().toLocaleTimeString()}] Status message sent. ID: ${statusMessageId}`);
} catch (err) {
console.error('Failed to send/edit status message:', err);
}
}
client.once('clientReady', async () => {
console.log(`Bot is ready! Logged in as ${client.user.tag}`);
await registerCommands();
await updateStatusMessage();
setInterval(updateStatusMessage, STATUS_UPDATE_INTERVAL);
});
client.on('interactionCreate', async (interaction) => {
if (!interaction.isChatInputCommand()) return;
if (interaction.commandName === 'ip') {
await interaction.reply({
embeds: [
new EmbedBuilder()
.setTitle('๐ก Server IP')
.setColor(0x5865F2)
.setDescription(`Connect using the address below:\n\n\`\`\`${SERVER_HOST}:${SERVER_PORT}\`\`\``)
.setFooter({ text: `Requested by ${interaction.user.username}` })
.setTimestamp()
]
});
}
});
client.on('error', (err) => {
console.error('Discord client error:', err);
});
client.login(process.env.DISCORD_TOKEN);