Files
bot.js
package.json
Code
2 243
bot.js
const fs = require('node:fs/promises');
const path = require('node:path');
const {
Client,
EmbedBuilder,
Events,
GatewayIntentBits,
PermissionFlagsBits,
SlashCommandBuilder
} = require('discord.js');
require('dotenv').config();
const TIERS = ['LT5', 'HT5', 'LT4', 'HT4', 'LT3', 'HT3', 'LT2', 'HT2', 'LT1', 'HT1', 'Unranked'];
const DATA_DIRECTORY = path.join(__dirname, 'data');
const DATA_FILE = path.join(DATA_DIRECTORY, 'rankings.json');
const TEMP_FILE = path.join(DATA_DIRECTORY, 'rankings.json.tmp');
const client = new Client({ intents: [GatewayIntentBits.Guilds] });
let rankings = {};
let saveQueue = Promise.resolve();
const tierChoices = TIERS.map(tier => ({ name: tier, value: tier }));
const commands = [
new SlashCommandBuilder()
.setName('rank')
.setDescription('Set a player’s Minecraft PvP tier')
.setDefaultMemberPermissions(PermissionFlagsBits.ManageGuild)
.addUserOption(option => option.setName('player').setDescription('Player to rank').setRequired(true))
.addStringOption(option => option.setName('tier').setDescription('PvP tier').setRequired(true).addChoices(...tierChoices))
.addStringOption(option => option.setName('ign').setDescription('Minecraft username').setMaxLength(32)),
new SlashCommandBuilder()
.setName('unrank')
.setDescription('Remove a player’s Minecraft PvP ranking')
.setDefaultMemberPermissions(PermissionFlagsBits.ManageGuild)
.addUserOption(option => option.setName('player').setDescription('Player to unrank').setRequired(true)),
new SlashCommandBuilder()
.setName('tierlist')
.setDescription('Show the server tier list')
.addStringOption(option => option.setName('tier').setDescription('Show only this tier').addChoices(...tierChoices)),
new SlashCommandBuilder()
.setName('profile')
.setDescription('View a player’s PvP tier profile')
.addUserOption(option => option.setName('player').setDescription('Player to view')),
new SlashCommandBuilder()
.setName('leaderboard')
.setDescription('Show the server’s highest-ranked players')
].map(command => command.toJSON());
async function loadRankings() {
await fs.mkdir(DATA_DIRECTORY, { recursive: true });
try {
const saved = JSON.parse(await fs.readFile(DATA_FILE, 'utf8'));
if (!saved || typeof saved !== 'object' || Array.isArray(saved)) {
throw new Error('Rankings data must be a JSON object.');
}
rankings = Object.fromEntries(Object.entries(saved).filter(([, entry]) =>
entry && typeof entry === 'object' && TIERS.includes(entry.tier)
));
} catch (error) {
if (error.code === 'ENOENT') {
rankings = {};
return;
}
throw error;
}
}
function persistRankings() {
const snapshot = JSON.stringify(rankings, null, 2);
const write = saveQueue.catch(() => {}).then(async () => {
await fs.mkdir(DATA_DIRECTORY, { recursive: true });
await fs.writeFile(TEMP_FILE, snapshot, 'utf8');
await fs.rename(TEMP_FILE, DATA_FILE);
});
saveQueue = write;
return write;
}
function sortedRankings(entries = Object.entries(rankings)) {
return entries.sort(([, left], [, right]) => {
const tierDifference = TIERS.indexOf(right.tier) - TIERS.indexOf(left.tier);
return tierDifference || String(left.updatedAt || '').localeCompare(String(right.updatedAt || ''));
});
}
function playerLabel(entry, userId) {
return `<@${userId}>${entry.minecraftName ? ` — ${entry.minecraftName}` : ''}`;
}
function tierListValue(entries) {
if (!entries.length) return 'No players ranked in this tier.';
const lines = [];
let length = 0;
for (const [userId, entry] of entries) {
const line = `• ${playerLabel(entry, userId)}`;
if (length + line.length + 1 > 350) break;
lines.push(line);
length += line.length + 1;
}
if (lines.length < entries.length) lines.push(`…and ${entries.length - lines.length} more`);
return lines.join('\n');
}
function requireGuildManager(interaction) {
if (!interaction.inGuild() || !interaction.memberPermissions?.has(PermissionFlagsBits.ManageGuild)) {
throw new Error('You need the Manage Server permission to change rankings.');
}
}
async function handleCommand(interaction) {
const command = interaction.commandName;
if (command === 'rank') {
requireGuildManager(interaction);
const player = interaction.options.getUser('player');
const tier = interaction.options.getString('tier');
const minecraftName = interaction.options.getString('ign')?.trim() || null;
rankings[player.id] = { userId: player.id, tier, minecraftName, updatedAt: new Date().toISOString() };
await persistRankings();
await interaction.reply({ content: `Set ${player} to **${tier}**${minecraftName ? ` (IGN: **${minecraftName}**)` : ''}.`, ephemeral: true });
return;
}
if (command === 'unrank') {
requireGuildManager(interaction);
const player = interaction.options.getUser('player');
if (!rankings[player.id]) {
await interaction.reply({ content: `${player} does not have a ranking to remove.`, ephemeral: true });
return;
}
delete rankings[player.id];
await persistRankings();
await interaction.reply({ content: `Removed ${player} from the tier list.`, ephemeral: true });
return;
}
if (command === 'tierlist') {
const selectedTier = interaction.options.getString('tier');
const shownTiers = selectedTier ? [selectedTier] : TIERS;
const embed = new EmbedBuilder()
.setColor(0xC0392B)
.setTitle(selectedTier ? `${selectedTier} Tier` : 'Minecraft PvP Tier List')
.setDescription('Rank order: LT5 → HT5 → LT4 → HT4 → LT3 → HT3 → LT2 → HT2 → LT1 → HT1 → Unranked');
for (const tier of shownTiers) {
const entries = sortedRankings(Object.entries(rankings).filter(([, entry]) => entry.tier === tier));
embed.addFields({ name: tier, value: tierListValue(entries), inline: true });
}
await interaction.reply({ embeds: [embed] });
return;
}
if (command === 'profile') {
const player = interaction.options.getUser('player') || interaction.user;
const entry = rankings[player.id];
const embed = new EmbedBuilder()
.setColor(0xC0392B)
.setTitle(`${player.username}’s PvP Profile`)
.setThumbnail(player.displayAvatarURL())
.addFields(
{ name: 'Tier', value: entry?.tier || 'Unranked', inline: true },
{ name: 'Minecraft Username', value: entry?.minecraftName || 'Not set', inline: true }
);
if (entry?.updatedAt && !Number.isNaN(Date.parse(entry.updatedAt))) {
embed.addFields({ name: 'Last Ranked', value: `<t:${Math.floor(Date.parse(entry.updatedAt) / 1000)}:R>`, inline: true });
}
await interaction.reply({ embeds: [embed] });
return;
}
if (command === 'leaderboard') {
const entries = sortedRankings().slice(0, 25);
const description = entries.length
? entries.map(([userId, entry], index) => `**${index + 1}.** ${playerLabel(entry, userId)} — **${entry.tier}**`).join('\n')
: 'No players have been ranked yet.';
const embed = new EmbedBuilder().setColor(0xC0392B).setTitle('Minecraft PvP Leaderboard').setDescription(description);
await interaction.reply({ embeds: [embed] });
}
}
client.once(Events.ClientReady, async () => {
try {
await client.application.commands.set(commands);
console.log('Slash commands registered.');
} catch (error) {
console.error('Failed to register slash commands:', error);
}
console.log(`Bot is ready! Logged in as ${client.user.tag}`);
console.log('KODARI_READY');
});
client.on(Events.InteractionCreate, async interaction => {
if (!interaction.isChatInputCommand()) return;
try {
await handleCommand(interaction);
} catch (error) {
console.error(`Command /${interaction.commandName} failed:`, error);
const message = error.message === 'You need the Manage Server permission to change rankings.'
? error.message


