Cookies Shelby20

Create a Discord.js bot project called Carnage Tierlist. It should have slash commands for Minecraft PvP tier rankings, using this order: LT5, HT5, LT4, HT4, LT3, HT3, LT2, HT2, LT1, HT1, Unranked. Include ranking, unranking, tier list, player profile, and leaderboard commands. Save rankings persistently and register the slash commands on startup.

Kodari AI
KodariOct 27 at 12:03 am 1
CarnageTierlist
Discord.js bot providing Minecraft PvP tier rankings with slash commands for ranking, unranking, viewing tier lists, player profiles, and leaderboards. Uses tier order LT5 through HT1 and Unranked. Persists rankings to JSON and registers all slash commands on startup.
  • Add a discord.js bot with /rank, /unrank, /tierlist, /profile, and /leaderboard.

  • Persist rankings as JSON and register slash commands when the bot starts.

Created the Carnage Tierlist bot with /rank, /unrank, /tierlist, /profile, and /leaderboard. Rankings persist in data/rankings.json, and slash commands register at startup. /rank and /unrank require Manage Server permission.

Copy .env.example to .env, add your DISCORD_TOKEN, then run npm install and npm start.

Cookies Shelby20

Add token and Discord developer portal application link

Kodari AI
KodariOct 27 at 12:14 am 1
  1. Add a DISCORD_TOKEN placeholder with the Discord Developer Portal link in the project’s environment setup.

  2. Keep the actual token private; you’ll paste it into .env.

Added the DISCORD_TOKEN placeholder and Discord Developer Portal link to .env.example. Create or copy your bot token from https://discord.com/developers/applications, then put it in .env; don’t share the real token here.

Cookies Shelby20

Where is env ?

Kodari AI
KodariOct 27 at 12:17 am 1

.env.example is in the project’s root folder. There isn’t an actual .env file yet—copy .env.example to .env, then add your bot token there. Keep .env private.

Cookies Shelby20

Link

Cookies Shelby20

Then what next

Kodari AI
KodariOct 27 at 12:18 am 1
  1. In the project’s root folder, create a file named .env (same folder as package.json) and add:

    Env
    DISCORD_TOKEN=paste_your_bot_token_here
    

    Copy the token from your app’s Bot page in the Discord Developer Portal. Keep it secret.

  2. In the project terminal, run:

    Shell
    npm install
    npm start
    
  3. Invite the bot to your server from OAuth2 → URL Generator in the Developer Portal. Select the bot and applications.commands scopes, then open the generated URL.

The bot registers its slash commands when it starts. Give it a moment for the commands to appear in your server. /rank and /unrank require Manage Server permission.

Cookies Shelby20
Kodari AI
KodariOct 27 at 12:22 am 1

Your app is created. Open the right-hand “Carnage Tierlist” with the gaming collage, then go to Bot in its settings and choose Add Bot (if prompted). Under Token, click Reset Token and copy it.

Paste the token into a .env file in your Kodari project’s root folder—the same folder as package.json:

Env
DISCORD_TOKEN=paste_your_token_here

Keep the token private; don’t post or send it here.

Cookies Shelby20

Can we do it with github.com

Kodari AI
KodariOct 27 at 12:24 am 1

Yes—GitHub can store the bot’s code, but don’t upload your Discord token to GitHub. Keep DISCORD_TOKEN in a private .env file in your Kodari project, and deploy/run the bot on Kodari. The token itself still comes from the Discord Developer Portal.

Cookies Shelby20

Like bro on discord developer portal after it opens it shows , my app Carnage Tierlist and I open it and it's on this page nothing shows about add bot and tokens but it shows application token and public tole and other url things linked role url

Kodari AI
KodariOct 27 at 12:26 am 1

Yeah—you’re on General Information. Application ID, Public Key, and Role Connection URL aren’t the bot token.

On your phone, tap the ☰ menu at the top-left of the Developer Portal, then choose Bot. There you can add the bot if prompted, then use Reset Token to generate and copy its token. Put that token in .env in your Kodari project—not on GitHub, and don’t share it here.

Cookies Shelby20

This is menu

Kodari AI
KodariOct 27 at 12:32 am 1

That menu is the Developer Portal’s main menu, not your app settings. Tap × to close it, then open the Carnage Tierlist app.

Once it’s open, go to the app’s Bot settings. On mobile, you may need to open the app-specific menu or switch Chrome to Desktop site. You can also try this direct link after replacing YOUR_APPLICATION_ID with the Application ID shown on General Information:

https://discord.com/developers/applications/YOUR_APPLICATION_ID/bot

On the Bot page, choose Add Bot if shown, then Reset Token to get the token. Don’t share it with anyone.

Cookies Shelby20

YOUR APPLICATION ID I write it there?

Kodari AI
KodariOct 27 at 12:34 am 1

Yes. Replace YOUR_APPLICATION_ID in the link with the actual Application ID shown on your app’s General Information page—don’t type the words YOUR_APPLICATION_ID.

For example, if the ID were 123456789012345678, open:

https://discord.com/developers/applications/123456789012345678/bot

Your real ID will be different.

Cookies Shelby20
Kodari AI
KodariOct 27 at 12:35 am 1

You’re on the right Bot page, and Discord has generated a new token. If you didn’t copy it from the popup, it won’t be shown again—tap Reset Token (you may need to scroll down), confirm, then copy the token from the popup immediately.

Paste it into your Kodari project’s .env file:

Env
DISCORD_TOKEN=your_copied_token

Keep the token secret. If you already copied it, don’t reset it again.

Cookies Shelby20

Where us the file

Kodari AI
KodariOct 27 at 12:39 am 1

The .env file is not in the Discord Developer Portal—create it in your Carnage Tierlist project on Kodari:

  1. Return to the Kodari project and open its Files view.

  2. In the project root—the same folder as package.json—create a new file named .env.

  3. Add DISCORD_TOKEN=your_copied_token to it.

.env.example is only a sample; it isn’t the actual token file. Keep .env private and don’t upload it to GitHub.

Cookies Shelby20

Should I write the new generated code 🤔 for examp. DISCORD_TOKEN=hyudryut6in

Kodari AI
KodariOct 27 at 12:42 am 1

Yes—put the full bot token after DISCORD_TOKEN= in your project’s .env file, without quotes:

Env
DISCORD_TOKEN=paste_the_full_token_here

But if the text you just posted was your real token, reset it in the Developer Portal first. Treat it as exposed, and only put the new token in .env—never share it in chat or upload it to GitHub.

Cookies Shelby20

Done I added it

Kodari AI
KodariOct 27 at 12:44 am 1

Great! Now start or restart the bot project. When it’s online, you should see KODARI_READY in the logs; then invite it to your server with the bot and applications.commands scopes. The slash commands should appear after registration.

Cookies Shelby20

Like i type run test

Kodari AI
KodariOct 27 at 12:45 am 1

To start the bot, use the project’s Run button. If you’re using a terminal, enter:

Shell
npm start

You don’t need to type “run test.” Check the logs for KODARI_READY to confirm it connected.

Kodari can make mistakes. Review important code before using.
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