iceyy4400

Create me a modern discord gambling bot with it's own virtual currency, daily rewards, blackjack minigame using images, coinflip using images, dice (rolling 1-6) using images, mines using containers, all bets doable by using slash commands, include a leaderboard auto updating in a set channel via a cmd with a 1m cooldown, balance command, pay command, feel free to propose more things to add

Kodari AI
KodariApr 30 at 10:17 am 88,450 (v2)
GamblingBot
A feature-rich Discord gambling bot with a virtual coin economy. Includes Blackjack with card images, Coinflip with visuals, Dice rolls (1–6) with visuals, Mines on a button grid, and a Slot Machine — all bet via slash commands. Features daily rewards, work income, pay transfers, rob mechanic, profile stats, and an auto-updating leaderboard channel refreshed every minute. Powered by discord.js v14, canvas image generation, and a persistent SQLite database.

Here’s the full plan before writing:

  • Core: index.js (client, command loader, button dispatcher, leaderboard loop), deploy-commands.js, src/database.js (SQLite via better-sqlite3)

  • Utils: src/utils/canvas.js (draws all game images), src/utils/helpers.js (mines multiplier math, formatters)

  • Commands (12): balance, daily, pay, blackjack, coinflip, dice, mines, slots, work, rob, leaderboard, setleaderboard, profile

  • Blackjack + Mines export a handleButton() dispatched from index.js; all game states live in in-memory Maps

Now let me verify no file references something that doesn’t exist by tracing the key dependency chains before finishing.

Everything looks solid. Here’s a full breakdown of what was built:


📁 Project Structure

Plain Text
GamblingBot/
├── index.js                  ← Bot entry, command loader, button dispatcher, leaderboard loop
├── deploy-commands.js        ← Register slash commands with Discord
├── package.json
├── .env                      ← DISCORD_TOKEN + CLIENT_ID
├── data/                     ← Auto-created, holds gambling.db
└── src/
    ├── database.js           ← SQLite (better-sqlite3), all DB helpers
    ├── utils/
    │   ├── canvas.js         ← All image generation (blackjack, coin, dice, slots)
    │   └── helpers.js        ← Mines multiplier math, formatNumber, formatTime
    └── commands/
        ├── balance.js        ← /balance [user]
        ├── daily.js          ← /daily — 500 coins, 24h cooldown
        ├── pay.js            ← /pay <user> <amount>
        ├── blackjack.js      ← /blackjack <bet> — card image + Hit/Stand/Double buttons
        ├── coinflip.js       ← /coinflip <bet> <heads|tails> — coin image
        ├── dice.js           ← /dice <bet> <1–6|high|low> — die image, 5× or 2× payout
        ├── mines.js          ← /mines <bet> <mines> — 4×5 button grid, cash out any time
        ├── slots.js          ← /slots <bet> — weighted 3-reel, jackpot or pair wins
        ├── work.js           ← /work — earn 10–300 coins, 30m cooldown, 10 random jobs
        ├── rob.js            ← /rob <user> — 40% steal 10–30%, 60% pay fine
        ├── leaderboard.js    ← /leaderboard — top 10 on demand
        ├── setleaderboard.js ← /setleaderboard <channel> — requires Manage Guild
        └── profile.js        ← /profile [user] — balance, rank, win rate, profit

🚀 Setup

Shell
npm install
# Fill in .env with your token and client ID
npm run deploy    # Register slash commands once
npm start         # Run the bot

🎮 Feature highlights

Feature
Details
Blackjack
Canvas card table image, Hit/Stand/Double buttons, natural 21 = 2.5×
Mines
4×5 button grid, 1–15 mines, hypergeometric multiplier formula, cash out any time
Slots
7 weighted symbols, jackpot (3-match) or pair payouts, canvas reel image
Dice
Exact number = 5×, high/low = 2×, drawn die-face canvas
Coinflip
Animated-feel gold/silver coin canvas
Leaderboard
/setleaderboard
pins a message that edits itself every 60 seconds
Economy
All games, daily, work, rob, and pay share the same persistent SQLite balance
Kodari can make mistakes. Review important code before using.
Files
src
deploy-commands.js
index.js
package.json
Code
19 1,761
index.js
const { Client, GatewayIntentBits, Collection, Events, EmbedBuilder } = require('discord.js');
require('dotenv').config();
const path = require('path');
const fs = require('fs');
const db = require('./src/database');

const client = new Client({ intents: [GatewayIntentBits.Guilds] });
client.commands = new Collection();

const commandsPath = path.join(__dirname, 'src', 'commands');
for (const file of fs.readdirSync(commandsPath).filter(f => f.endsWith('.js'))) {
    const command = require(path.join(commandsPath, file));
    if (command.data && command.execute) {
        client.commands.set(command.data.name, command);
    }
}

client.once(Events.ClientReady, () => {
    console.log(`✅ Ready! Logged in as ${client.user.tag}`);
    startLeaderboardUpdater(client);
});

client.on(Events.InteractionCreate, async interaction => {
    if (interaction.isChatInputCommand()) {
        const command = client.commands.get(interaction.commandName);
        if (!command) return;
        try {
            await command.execute(interaction);
        } catch (err) {
            console.error(`Error in /${interaction.commandName}:`, err);
            const payload = { content: '❌ An error occurred while running this command.', ephemeral: true };
            if (interaction.replied || interaction.deferred) {
                await interaction.followUp(payload).catch(() => {});
            } else {
                await interaction.reply(payload).catch(() => {});
            }
        }
        return;
    }

    if (interaction.isButton()) {
        const prefix = interaction.customId.split('_')[0];
        try {
            if (prefix === 'bj') {
                const { handleButton } = require('./src/commands/blackjack');
                await handleButton(interaction);
            } else if (prefix === 'mines') {
                const { handleButton } = require('./src/commands/mines');
                await handleButton(interaction);
            }
        } catch (err) {
            console.error('Button handler error:', err);
            await interaction.reply({ content: '❌ Something went wrong.', ephemeral: true }).catch(() => {});
        }
    }
});

function buildLeaderboardEmbed(guildId) {
    const top = db.getTopUsers(guildId, 10);
    const desc = top.length === 0
        ? '*No users have played yet.*'
        : top.map((u, i) => {
            const medal = i === 0 ? '🥇' : i === 1 ? '🥈' : i === 2 ? '🥉' : `**${i + 1}.**`;
            return `${medal} <@${u.user_id}> — 🪙 **${u.balance.toLocaleString()}**`;
        }).join('\n');

    return new EmbedBuilder()
        .setTitle('🏆 Server Leaderboard')
        .setDescription(desc)
        .setColor(0xFFD700)
        .setFooter({ text: 'Auto-updates every minute' })
        .setTimestamp();
}

async function startLeaderboardUpdater(client) {
    const update = async () => {
        const entries = db.getLeaderboardChannels();
        for (const entry of entries) {
            try {
                const guild = await client.guilds.fetch(entry.guild_id).catch(() => null);
                if (!guild) continue;
                const channel = await guild.channels.fetch(entry.channel_id).catch(() => null);
                if (!channel || !channel.isTextBased()) continue;

                const embed = buildLeaderboardEmbed(entry.guild_id);

                if (entry.message_id) {
                    const msg = await channel.messages.fetch(entry.message_id).catch(() => null);
                    if (msg) {
                        await msg.edit({ embeds: [embed] });
                        continue;
                    }
                }
                const newMsg = await channel.send({ embeds: [embed] });
                db.updateLeaderboardMessage(entry.guild_id, newMsg.id);
            } catch (err) {
                console.error('Leaderboard update error:', err.message);
            }
        }
    };

    await update();
    setInterval(update, 60_000);
}

client.login(process.env.DISCORD_TOKEN);