Case Study

Gambling BOT – Discord Casino & Admin Dashboard Ecosystem

Gambling BOT is a full-stack gambling and virtual-economy system built for Discord communities.

It combines a feature-rich casino engine, persistent user balances, VIP rooms, predictions, daily bonuses, and a powerful admin dashboard.

All gameplay, configuration, logging, and economy interactions share a unified database and a shared NPM package, ensuring consistency across the entire ecosystem.

Project Overview

The system now consists of three tightly connected parts: a Discord bot for gameplay, an admin dashboard for configuration and insights, and a shared NPM package that provides all shared models, types, and utilities.

Contents

  1. 1. Motivation & Goals
  2. 2. System Architecture
  3. 3. Shared Package Architecture
  4. 4. Economy & Transaction Model
  5. 5. Casino Game Engine
  6. 6. RTP System & Fairness Logic
  7. 7. Daily Bonus System
  8. 8. VIP Rooms & Access Control
  9. 9. Predictions (Betting Market)
  10. 10. Admin Web Dashboard
  11. 11. Future Work & Technical Challenges

1. Motivation & Goals

Gambling BOT started as a way to introduce a structured, persistent casino experience into a Discord community—something deeper than simple “fun” commands. The goal was to design a unified system where all layers share the same logic, models, and economic rules.

Over time, the project matured into a scalable multi-application ecosystem with:

  • A persistent virtual currency with complete transaction logging.
  • Casino-style games with fully configurable RTP and fairness controls.
  • VIP rooms that feel personal, private, automated, and temporary.
  • A modern admin dashboard for analytics, management, and server customization.
  • A shared NPM package providing schemas, validation, helpers, and strong typing across all apps.

2. High-Level Architecture

The system is composed of three interconnected applications that share the same data structures and logic through a dedicated NPM package. Each runs independently but stays perfectly aligned thanks to shared schemas, helpers, constants, and TypeScript types.

Discord Bot

  • Built with discord.js and CommandKit.
  • Implements all casino games, VIP management, predictions, and ATM logic.
  • Handles gameplay, validation, messaging, cooldowns, and transactional state.
  • Reads all models and types directly from gambling-bot-shared.

Shared NPM Package

  • Exports all TypeScript types, interfaces, enums, and constants.
  • Contains all Mongoose schemas and models.
  • Includes helper functions, validators, and probability utilities.
  • Ensures 100% consistency across the bot and dashboard.

Admin Dashboard

  • Built using Next.js, React, Radix UI, Framer Motion, and Tailwind.
  • Authentication via Discord OAuth with role-based access control.
  • Provides transparency: transaction history, RTP controls, VIP management.
  • Reads and updates the same MongoDB collections as the bot.
  • Uses shared models and utilities from gambling-bot-shared.

3. Shared Package Architecture

To prevent desynchronization between the bot and the admin dashboard, all logic that defines the casino ecosystem lives inside a dedicated NPM package: gambling-bot-shared.

  • Mongoose schemas & models for User, Transaction, Games, Predictions, VIP Rooms, GuildConfiguration.
  • Strongly typed constants and enums used by both applications.
  • Shared helper functions including RTP calculations and probability utilities.
  • Reusable validation logic for commands, forms, and internal systems.
  • Utilities for formatting, randomization, state transitions, and gameplay rules.
Benefits of a Shared Core

By centralizing all shared logic, the ecosystem becomes easier to maintain, safer to extend, and impossible to desync. Both applications always run on the same logic by design.

4. Economy & Transaction Model

All economy-related schemas now come from the shared NPM package, guaranteeing identical behavior in both the Discord bot and the admin dashboard.

  • User — stored per guild, containing balance, lockedBalance, and daily-streak metadata.
  • Transaction — immutable economic log entry with fields such as type (deposit, withdraw, bet, win, bonus, vip, refund), source (command, web, system, casino), and optional betId.

The bot never “just updates balance numbers” — every mutation is an atomic database operation paired with a transaction document. This enables full historical reconstruction for any player, guild, or administrative action, supported by compound indexes on guild, user, type, source, and betId for fast querying.

Gated Deposits & Withdrawals

Deposits and withdrawals are not automatic. Players create requests, and admins must approve them. This design makes the system safe for RP servers (e.g., GTA RP), preventing the bot from moving real or sensitive in-game currency on its own.

5. Game Engine Design

The casino part of the bot offers several games, each implemented as a slash command with its own betting rules, fairness model, and UX flow. Despite their differences, all games follow the same high-level pattern:

  1. Validate registration and guild configuration (allowed channels, limits).
  2. Validate bet size using per-guild min/max limits and the user balance.
  3. Lock funds by decrementing balance and creating a bet transaction.
  4. Execute the game logic (single or multi-round flow, animations, embeds).
  5. Compute winnings, update balance, and create win transaction(s).
  6. Render a final summary embed with optional balance information.

Blackjack

Blackjack uses a strongly typed Card model, generating a shuffled deck and storing it in MongoDB along with player and dealer hands.

  • Session stored in a dedicated BlackjackGame document.
  • Only one active game per user per guild (unique index).
  • Dealer hits until 17, with soft-17 support built into hand evaluation.
  • Blackjack detection on the initial deal for both sides.
  • Player actions implemented via interaction buttons (hit, stand, double).
  • Dealer reveals cards with short delays, updating the embed each step.
  • Final outcomes include win, loss, push, and blackjack-specific cases.

Mini Roulette

Roulette is implemented as a custom 19-field wheel (0–18). Colors are defined using the strongly typed MINI_NUMBERS map. Players can submit multiple bets in a single command.

  • Bet types: number, color, parity, range, dozen (D1–D3), and column (C1–C3).
  • Bets parsed from comma-separated input like "10 red, 5 D2".
  • Game logic resolves each bet using typed helpers.
  • Supports multi-spin commands with persistent live results.

Lottery

Users select a set of numbers. The bot draws unique numbers from a fixed pool, and payouts scale with the number of matches. Probabilities are handled combinatorially in the RTP logic.

Coinflip

A simple, configurable game where users pick heads or tails and run multiple flips. Rewards use a configurable win multiplier that directly determines the RTP.

Slots

Slots use weighted symbols for each spin. Three random symbols appear, and only 3-of-a-kind combinations pay out via configured multipliers in the guild settings.

Rock, Paper, Scissors (PvP)

A peer-to-peer duel: one user challenges another, both place the same bet, and the winner takes the pot minus a casino cut. All transactions reference the same betId for clean traceability.

Golden Jackpot

A high-variance game with a one-in-N win chance and a large multiplier. Users buy multiple “tickets”, and the bot draws attempts with optional animations, logging each jackpot hit.

6. RTP Calculation & Fairness Controls

Instead of treating RTP (Return to Player) as a vague concept, the system exposes it explicitly through a dedicated calculateRTP function. This function reads the guild’s casino settings and computes the real, effective RTP for every game using probability and configuration data — not hardcoded values.

How RTP Is Computed

Game Rules

Each game defines its probability model (dice odds, slot weights, lottery combinations, roulette layout…).

Guild Settings

Win multipliers, symbol weights, odds, and casino cuts are stored in GuildConfiguration.

RTP Function

The system computes expected value for every game, producing a transparent, configurable RTP %.

  • Dice – a fixed 1/6 probability with a configurable win multiplier.
  • Coinflip – 50/50 outcome scaled by a guild multiplier.
  • Slots – RTP derived from weighted symbols + multiplier tables using probability across all 3-of-a-kind outcomes.
  • Lottery – uses combinatorics to compute exact match probabilities.
  • Mini Roulette – RTP per bet type (number, color, parity, range, dozen, column) based on custom 0–18 wheel.
  • RPS – simply 1 - casinoCut.
  • Golden Jackpot winMultiplier / oneInChance.
  • Blackjack – currently fixed at ~99.4% to match real-world expected return.

Example: RTP Calculation Snippet

case 'coinflip': {
  const { winMultiplier } = settings;
  return 0.5 * Number(winMultiplier) * 100;
}

case 'slots': {
  const { symbolWeights, winMultipliers } = settings;
  const totalWeight = Object.values(symbolWeights).reduce((a, b) => a + b, 0);
  let rtp = 0;

  for (const [symbol, weight] of Object.entries(symbolWeights)) {
    const p = (weight / totalWeight) ** 3; // probability of 3-of-a-kind
    const multi = winMultipliers[symbol + symbol + symbol] ?? 0;
    rtp += p * multi;
  }

  return rtp * 100;
}
Why RTP Matters

RTP gives admins predictable control over how generous or challenging the casino feels. Because the system computes RTP from real probabilities instead of static presets, servers can tune risk level in a transparent and mathematically correct way.

Fully Configurable Per Guild

All RTP-sensitive values (win multipliers, symbol weights, odds, casino cut) are stored directly inside GuildConfiguration. Server admins can adjust them from the dashboard without restarting the bot.

7. Daily Bonus & Streak System

To keep players engaged without forcing them to gamble constantly, the system includes a flexible daily bonus mechanic. The bonus logic is fully configurable per guild through bonusSettings, allowing each community to tune progression and pacing.

  • Linear or exponential reward mode.
  • Base reward, streak increment or multiplier.
  • Maximum reward with optional cycle reset behavior.
  • Weekly and monthly milestone bonuses.

The /bonus command exposes two subcommands: check and claim. The check subcommand renders a 28-day calendar using emoji icons to represent past, current, and upcoming rewards. The claim subcommand enforces the 24-hour cooldown, updates streak progression, writes a bonus transaction, and updates both balance and lockedBalance on the user document.

Locked Balance for Bonus Rewards

Daily bonuses are applied to both balance and lockedBalance. Locked funds cannot be withdrawn immediately and are intended for in-system usage, preventing pure farming behavior while keeping bonuses meaningful.

8. VIP Rooms

VIP rooms are private text channels that players can purchase for a configurable duration. The system ties together the GuildConfiguration, User, and VipRoom models to manage pricing, ownership, permissions, and expiration.

Purchasing Flow

  • Purchase is initiated through /vip buy.
  • Duration can be specified in days or weeks (e.g., 3d, 1w).
  • Total price is based on duration plus an optional creation fee.
  • Balance is validated to ensure the user can afford the purchase.

Channel & Role Handling

  • A private channel is created in the configured VIP category.
  • Permissions restrict access so only the buyer can view and write.
  • A VIP role is assigned for visibility and easier moderation.
  • A corresponding VipRoom entry stores the channel ID and expiration date.

When a VIP room expires, the channel remains visible but becomes locked — the user loses write permissions. This preserves message history for light auditing while maintaining the temporary nature of the perk.

Extending VIP Duration

Players can extend their VIP room using /vip extend. The system recalculates the total price based on the added time, updates the expiry timestamp, and logs the extension as a VIP transaction.

9. Predictions

Predictions function as an on-chain betting system inside the Discord server: moderators can create events with up to three choices, each with custom odds. Players place bets on one of the options, and payouts are calculated once the event resolves.

Admin creates prediction
Users place bets
Autolock triggers (optional)
Admin resolves outcome
Winners are paid / refunds issued
  • Prediction documents store title, guild, channel, creator, status, autolock time, and all choices with their odds and attached bets.
  • Autolock automatically closes the prediction after a configured timeout.
  • When resolved, winning bets are paid out as amount × odds.
  • Cancelled predictions refund all users and create refund transactions.
Admin-Driven, Player-Visible

Predictions are created and resolved by moderators, but every step is visible to players through Discord embeds. All payouts and refunds are still logged internally for admins.

10. Admin Web Dashboard (TBD)

The web dashboard is built using Next.js, React, Radix UI and Tailwind CSS. Authentication is handled through Discord OAuth, with access restricted to users who hold the manager role or the Administrator permission. The dashboard operates on the same Mongoose models as the bot, making it the central place for configuring every aspect of the casino.

TBD – Dashboard Management Views

Planned dashboard features include transaction analytics, casino settings management (including RTP controls), user inspectors, VIP room administration, and prediction control panels. This section will be expanded as the admin interface is fully implemented.

11. Future Work & Technical Challenges (TBD)

Developing a unified Discord–web ecosystem brings a number of deeper engineering problems: ensuring consistency between rapid Discord interactions and database state, preventing race conditions in multiplayer flows, and designing indexes that remain efficient under transaction-heavy workloads.

TBD – Challenges & Solutions

A detailed breakdown of the largest technical obstacles—concurrency, scaling, dashboard ergonomics, anti-abuse mechanisms—will be added as the project matures and real-world usage patterns emerge.

For now, the core effort focuses on strong typing, clean data modeling, and a unified user experience across Discord and the dashboard. As new features are introduced, this section will grow into a log of problems encountered and the architectural decisions that solved them.

This page is a living case study of the Gambling BOT ecosystem. As the dashboard, Discord bot, and shared package evolve, this write-up will be updated to reflect new architectural decisions and best practices.