Beatra Discord Music Bot

repository·main·Indexed 23 days ago

https://github.com/umutxyp/musicbot

A high-performance Discord music bot built with discord.js v14.22. It features lossless playback via local audio caching, cinematic embeds, and support for YouTube, Spotify, SoundCloud, and direct links. Includes advanced features such as genre-based autoplay, Genius API lyrics integration, automated sharding for large-scale deployments (1,000+ servers), and multi-language support.

Tokens
14.5K
Snippets
11
Records
89
Agent score
78%

What's inside Beatra

  1. How the Local Audio Cache System works

    main

    Beatra uses a local caching system to prevent playback interruptions like buffering, stuttering, or voice crackling. Instead of streaming directly from external URLs (YouTube, Spotify, SoundCloud), the bot pre-downloads tracks to a local directory before playback.

    Workflow:

    1. Queue Detection: Triggered by /play or autoplay.
    2. Background Download: Tracks are downloaded silently while the current song plays.
    3. Smart Preloading: The entire queue is preloaded in parallel for instant transitions.
    4. Local Streaming: FFmpeg streams the cached .opus file to Discord.
    5. Automatic Cleanup: Files are deleted after playback to save space.

    Technical Specifications:

    • Cache Directory: audio_cache/ (automatically created).
    • Format: Opus audio (.opus) for optimal Discord quality.
    • Naming Convention: track_[MD5 hash].opus.
    • Disk Space Requirements: While usage is minimal (~30-80 MB for a 10-track queue), it is recommended to have at least 500 MB free space on VPS deployments to handle large queues comfortably.
  2. Security Warning for cookies.txt

    main

    The cookies.txt file contains your sensitive YouTube session data.

    Critical Security Actions:

    • Never share this file with anyone.
    • Always add cookies.txt to your .gitignore file.
    • Never upload this file to GitHub or any public repository.
  3. How sharding works and when to use it

    main

    Sharding is Discord's method for scaling bots. When a bot reaches 1,000 servers, Discord requires sharding to distribute the workload across multiple processes.

    Key Concepts

    • Mandate: 1,000+ servers MUST use sharding.
    • Mechanism: Discord routes events to the correct shard based on the server (guild) ID. A single bot instance is split into multiple 'shards', each handling a subset of the total servers.
    • Benefits: Distributes load, improves stability (one shard crash doesn't kill the whole bot), and allows for massive scalability (10,000+ servers).

    Shard Count Calculation

    The required number of shards can be calculated using the formula: Math.ceil(total_servers / 1000). Setting TOTAL_SHARDS=auto in your configuration automates this calculation.

  4. How the Autoplay system works

    main

    The Autoplay engine automatically queues music when the current queue ends.

    Workflow

    1. Enable: Click the 🎲 Autoplay button on the nowplaying embed.
    2. Select Genre: Choose from 20 genres (e.g., Pop, Rock, Anime, Lo-Fi, Random).
    3. Automatic Queueing: The bot searches for tracks matching the genre, applies filters, and queues them.

    Content Filtering

    To ensure high-quality music, the system filters content based on:

    • Duration: Tracks must be between 30 seconds and 10 minutes.
    • Keywords: Automatically skips content containing tutorial, podcast, interview, review, unboxing, ASMR, audiobook, documentary, etc.
    • Quality: Prioritizes official music videos and avoids clickbait/spam titles.

    Technical Details

    • Fallback: If a search yields no results, the bot retries with different keywords from the genre pool.
    • Caching: Autoplay tracks are pre-downloaded to local storage for zero-buffering playback.
    • Priority: Manually added tracks always take precedence over autoplay suggestions.
  5. Install and run Beatra on Windows

    main

    For Windows users, the project provides a fast-track setup using batch files.

    1. Run setup.bat from the repository root to verify Node.js/npm, install dependencies, and scaffold a .env template.
    2. Edit the generated .env file with your Discord and service credentials.
    3. Run start.bat to launch the bot.

    setup.bat ensures your environment is ready, while start.bat executes npm run start.

    # Run from the repo root
    .\setup.bat
    # Edit the generated .env with your credentials
    .\start.bat
  6. Deployment tips for Beatra

    main

    When deploying the bot, consider the following best practices:

    • Development Testing: Set the GUILD_ID environment variable during development to avoid global propagation delays for slash commands. Remove it for production to allow the bot to work in all servers.
    • Process Management: Use tools like pm2, systemd, or Docker to ensure the bot restarts automatically on crashes. If using Docker, ensure you persist the database/languages.json file to save user language preferences.
    • Logging: The bot uses Chalk-colored console output. For long-term monitoring, redirect stdout and stderr to log files.
    • Scaling: The current architecture maintains one voice connection per guild. Horizontal scaling is not natively supported and would require a shared state/queue (e.g., Redis).
  7. Install and run Beatra on Cross-platform (Manual)

    main

    To install Beatra on Linux, macOS, or via manual steps on Windows, follow these commands:

    1. Clone the repository and enter the directory.
    2. Install dependencies using npm install.
    3. Configure your secrets by creating a .env file (it is recommended to back up the template first).
    4. Start the bot using npm run start or node index.js.

    Note: Slash commands register automatically. If GUILD_ID is provided in .env, commands deploy to that specific guild instantly. Otherwise, global registration may take up to an hour.

    # 1. Clone & enter
    git clone https://github.com/umutxyp/musicbot.git discord-musicbot
    cd discord-musicbot
    
    # 2. Install dependencies
    npm install
    
    # 3. Configure secrets (see below)
    Copy-Item .env .env.backup -ErrorAction SilentlyContinue
    # Edit .env with your token, client ID, Spotify credentials, etc.
    
    # 4. Boot the bot
    npm run start
    # or
    node index.js
  8. Configure Sharding for large bots (1,000+ servers)

    main

    Discord requires sharding once your bot reaches 1,000+ servers. Beatra uses an automated system via ShardingManager.

    Launching in Sharding Mode

    • Windows (Interactive): Run .\start.bat and select option [2] Sharding Mode.
    • Windows (Direct): Run .\start-shard.bat.
    • Linux/Cross-platform: Run node shard.js.

    Sharding Configuration

    Configure these keys in .env or config.js:

    KeyType/ValueDescription
    TOTAL_SHARDSauto or numberauto lets Discord calculate the count. Use a number to force a specific count.
    SHARD_LISTauto or arrayauto spawns all. Use an array like [0,1,2] for specific shards.
    SHARD_MODEprocess or workerprocess is recommended for production (stable/isolated). worker is for development.
    SHARD_RESPAWNbooleanIf true, crashed shards restart automatically.
    SHARD_SPAWN_DELAYnumber (ms)Delay between spawning shards (recommended: 5500).
    SHARD_SPAWN_TIMEOUTnumber (ms)Timeout for shard ready event.

    Best Practices

    • Use TOTAL_SHARDS=auto for production.
    • Use SHARD_MODE=process for stability.
    • Ensure SHARD_SPAWN_DELAY is around 5500ms to avoid Discord rate limits.
    TOTAL_SHARDS=auto
    SHARD_LIST=auto
    SHARD_MODE=process
    SHARD_RESPAWN=true
    SHARD_SPAWN_DELAY=5500
    SHARD_SPAWN_TIMEOUT=30000
  9. Migrate from single-process to sharding

    main

    If your bot is growing and you need to move from a single process to sharding, follow these steps:

    1. Backup your database: Copy-Item database/languages.json database/languages.json.backup (Windows)
    2. Update .env: Set TOTAL_SHARDS=auto and SHARD_MODE=process.
    3. Start in sharding mode: Run npm run shard.
    4. Verify: Check console logs for [SHARD X] ✅ Shard X is ready! messages.
    5. Test: Run commands like /play in several servers to ensure functionality.

    To Rollback: Simply stop the sharding process and run npm start to return to normal mode. No code changes are required.

  10. Use PM2 for production sharding management

    main

    For production environments, it is recommended to use PM2 to manage your shards. This allows for easy monitoring and automatic restarts.

    1. Install PM2: npm install -g pm2
    2. Start the bot: pm2 start shard.js --name "musicbot-shards"
    3. Monitor health: pm2 monit
    4. View logs: pm2 logs musicbot-shards
    5. Restart: pm2 restart musicbot-shards
    npm install -g pm2
    pm2 start shard.js --name "musicbot-shards"
    pm2 monit
    pm2 logs musicbot-shards
    pm2 restart musicbot-shards
  11. Fix YouTube Bot Detection Error using Browser Cookies

    main

    If you encounter the error ERROR: [youtube] Sign in to confirm you're not a bot., you can resolve it by allowing the bot to extract cookies directly from your web browser. This is the recommended method for running the bot on a personal computer because it supports automatic updates.

    Steps to Configure:

    1. Open your .env file.
    2. Add the COOKIES_FROM_BROWSER key with the name of the browser you use to access YouTube.
    3. Ensure you are actively logged into YouTube in that specific browser.
    4. Restart the bot.

    Supported browser values: chrome, firefox, edge, safari.

  12. Start the bot in Sharding or Normal mode

    main

    Depending on your server count and operating system, use the following commands to start the bot. Use Normal mode if you have fewer than 1,000 servers, and Sharding mode if you have 1,000 or more servers.

    Windows

    • Interactive mode: Run .\start.bat and choose option 2 for sharding.
    • Direct sharding start: Run .\start-shard.bat or npm run shard.

    Linux/Mac

    • Normal mode (< 1000 servers): Run npm start.
    • Sharding mode (1000+ servers): Run npm run shard.