### Cross-Platform Manual Setup for MusicBot Source: https://github.com/umutxyp/musicbot/blob/main/README.md This guide outlines the manual steps required to set up the musicbot on any operating system. It involves cloning the repository, installing Node.js dependencies, configuring environment variables, and starting the bot. It also mentions the automatic registration of slash commands. ```powershell # 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 ``` -------------------------------- ### Windows Quick Start Commands for MusicBot Source: https://github.com/umutxyp/musicbot/blob/main/README.md These batch commands automate the setup and startup process for the musicbot on Windows. `setup.bat` handles dependency installation and environment setup, while `start.bat` launches the bot. Ensure Node.js and npm are installed. ```batch # Run from the repo root .\setup.bat # Edit the generated .env with your credentials .\start.bat ``` -------------------------------- ### Install and Use PM2 for Process Management (bash) Source: https://github.com/umutxyp/musicbot/blob/main/SHARDING.md Installs PM2 globally, starts the bot's sharding script, and provides commands to monitor, view logs, and restart the bot process. ```bash # Install PM2 npm install -g pm2 # Start with PM2 pm2 start shard.js --name "musicbot-shards" # Monitor pm2 monit # View logs pm2 logs musicbot-shards # Restart pm2 restart musicbot-shards ``` -------------------------------- ### Start Discord Bot (Linux/Mac) Source: https://github.com/umutxyp/musicbot/blob/main/SHARDING.md Commands to start the Discord bot on Linux or Mac. 'npm start' is for bots with less than 1000 servers, while 'npm run shard' is for sharding mode (1000+ servers). ```bash # Normal mode (< 1000 servers) npm start # Sharding mode (1000+ servers) npm run shard ``` -------------------------------- ### Install Dependencies (powershell) Source: https://github.com/umutxyp/musicbot/blob/main/SHARDING.md Installs all necessary project dependencies using npm. This is a common troubleshooting step for issues like a shard respawn loop. ```powershell npm install ``` -------------------------------- ### Start Sharding Script (bash) Source: https://github.com/umutxyp/musicbot/blob/main/SHARDING.md Executes the sharding script using npm. This command is used after configuring the bot for sharding. ```bash npm run shard ``` -------------------------------- ### Sharding Mode Configuration (Process) Source: https://github.com/umutxyp/musicbot/blob/main/SHARDING.md Configuration example for using 'process' mode for sharding, which is recommended for production due to better stability and error isolation. ```dotenv SHARD_MODE=process ``` -------------------------------- ### Start MusicBot with Sharding (Direct) Source: https://github.com/umutxyp/musicbot/blob/main/README.md Directly launch the musicbot using sharding enabled. This is an alternative to the interactive launcher for bots that require sharding due to a large server count. ```bash .\start-shard.bat ``` ```bash node shard.js ``` -------------------------------- ### Start Discord Bot with Sharding (Windows) Source: https://github.com/umutxyp/musicbot/blob/main/SHARDING.md Commands to start the Discord bot using sharding on Windows. Option 2 starts the bot in interactive mode with sharding enabled, while direct sharding can be initiated with 'start-shard.bat' or 'npm run shard'. ```powershell # Interactive mode .\start.bat # Choose option 2 for sharding # Direct sharding start .\start-shard.bat # or npm run shard ``` -------------------------------- ### Start MusicBot with Sharding (Interactive) Source: https://github.com/umutxyp/musicbot/blob/main/README.md Execute a batch script to launch the musicbot. This script provides an interactive menu where you can choose the sharding mode. ```powershell .\start.bat ``` -------------------------------- ### Start MusicBot in Normal Mode Source: https://github.com/umutxyp/musicbot/blob/main/README.md Command to start the musicbot in its default mode, suitable for bots with fewer than 1000 servers. This is the standard way to launch the bot for everyday use. ```bash node index.js ``` -------------------------------- ### Running Specific Shards Across Multiple Servers Source: https://github.com/umutxyp/musicbot/blob/main/SHARDING.md Configuration examples for distributing shards across multiple VPS servers. Each server's .env file specifies the total shards and the specific list of shards it should run. ```dotenv # Server 1 (.env): TOTAL_SHARDS=4 SHARD_LIST=[0,1] # Run shards 0 and 1 # Server 2 (.env): TOTAL_SHARDS=4 SHARD_LIST=[2,3] # Run shards 2 and 3 ``` -------------------------------- ### Manual Shard Count Configuration Source: https://github.com/umutxyp/musicbot/blob/main/SHARDING.md Configuration example for forcing a specific number of shards, regardless of the server count. This is useful for pre-scaling or meeting specific requirements. ```dotenv TOTAL_SHARDS=8 # Always use 8 shards ``` -------------------------------- ### Backup Database File (powershell) Source: https://github.com/umutxyp/musicbot/blob/main/SHARDING.md Creates a backup of the languages.json database file. This is part of the migration guide to ensure data safety before switching to sharding. ```powershell Copy-Item database/languages.json database/languages.json.backup ``` -------------------------------- ### MusicBot Environment Configuration (.env) Example Source: https://github.com/umutxyp/musicbot/blob/main/README.md This is a sample `.env` file for configuring the musicbot. It lists essential variables such as Discord token, client ID, Spotify credentials, and optional settings for Genius API, status messages, and cookie handling. ```dotenv DISCORD_TOKEN=your_bot_token CLIENT_ID=your_application_id GUILD_ID=optional_guild_for_fast_testing SPOTIFY_CLIENT_ID=spotify_client_id SPOTIFY_CLIENT_SECRET=spotify_client_secret GENIUS_CLIENT_ID=optional_genius_client_id GENIUS_CLIENT_SECRET=optional_genius_client_secret STATUS=🎵 Beatra | /play EMBED_COLOR=#FF6B6B SUPPORT_SERVER=https://discord.gg/ACJQzJuckW WEBSITE=https://beatra.app COOKIES_FROM_BROWSER=chrome COOKIES_FILE=./cookies.txt ``` -------------------------------- ### Sharding Mode Configuration (Worker) Source: https://github.com/umutxyp/musicbot/blob/main/SHARDING.md Configuration example for using 'worker' mode for sharding, which is experimental and offers lower memory footprint but is harder to debug. ```dotenv SHARD_MODE=worker ``` -------------------------------- ### Play Music Command Example Source: https://github.com/umutxyp/musicbot/blob/main/YOUTUBE_FIX.md An example command to test music playback after resolving bot detection issues. This command is used within Discord to verify that the bot can now access YouTube content. ```bash /play Despacito ``` -------------------------------- ### Rollback to Single-Process Mode (bash) Source: https://github.com/umutxyp/musicbot/blob/main/SHARDING.md Command to stop the current sharded process and start the bot in its original single-process mode, useful for reverting if sharding causes issues. ```bash # Stop sharding # Start normal mode npm start ``` -------------------------------- ### Start Musicbot Application Source: https://github.com/umutxyp/musicbot/blob/main/YOUTUBE_FIX.md This command initiates the musicbot application after configuration changes. It is used to restart the bot and apply the updated .env settings, including cookie configurations. ```bash npm start ``` -------------------------------- ### Enable Auto-Respawn (dotenv) Source: https://github.com/umutxyp/musicbot/blob/main/SHARDING.md Enables the automatic respawning of shards if they crash or disconnect unexpectedly, ensuring higher bot uptime. ```dotenv SHARD_RESPAWN=true ``` -------------------------------- ### Configure for Sharding (dotenv) Source: https://github.com/umutxyp/musicbot/blob/main/SHARDING.md Updates the .env file to enable automatic sharding and set the sharding mode to process, preparing the bot for a sharded environment. ```dotenv TOTAL_SHARDS=auto SHARD_MODE=process ``` -------------------------------- ### Discord Bot Sharding Configuration (.env) Source: https://github.com/umutxyp/musicbot/blob/main/SHARDING.md Environment variables for configuring Discord bot sharding. Includes settings for token, client ID, total shards, shard list, sharding mode, auto-respawn, spawn delay, and spawn timeout. ```dotenv # === Required for Sharding === DISCORD_TOKEN=your_bot_token_here CLIENT_ID=your_client_id_here # === Sharding Configuration === # Total number of shards to spawn # 'auto' = Discord.js calculates optimal count (RECOMMENDED) # Or set a specific number: 2, 4, 8, etc. TOTAL_SHARDS=auto # Which shards to spawn # 'auto' = spawn all shards (RECOMMENDED) # Or specify array: [0,1,2] to spawn specific shards SHARD_LIST=auto # Sharding mode # 'process' = each shard in separate Node.js process (RECOMMENDED for production) # 'worker' = each shard in worker thread (experimental, less memory) SHARD_MODE=process # Auto-restart crashed shards # true = automatically respawn dead shards (RECOMMENDED) # false = manual restart required SHARD_RESPAWN=true # Delay between spawning shards (milliseconds) # Discord recommends 5000-5500ms to avoid rate limits SHARD_SPAWN_DELAY=5500 # Timeout for shard ready event (milliseconds) # Increase if shards time out during startup SHARD_SPAWN_TIMEOUT=30000 ``` -------------------------------- ### Use Guild-Specific Command Testing (dotenv) Source: https://github.com/umutxyp/musicbot/blob/main/SHARDING.md Specifies a particular guild ID for testing global commands. This allows you to see command updates in a specific server without waiting for global propagation. ```dotenv GUILD_ID=your_test_server_id ``` -------------------------------- ### Reduce Concurrent Spawns with Delay (dotenv) Source: https://github.com/umutxyp/musicbot/blob/main/SHARDING.md Increase the delay between spawning shards to reduce peak memory usage and avoid hitting Discord's rate limits for connections. ```dotenv SHARD_SPAWN_DELAY=7000 ``` -------------------------------- ### Adjust Shard Spawn Delays and Timeouts (dotenv) Source: https://github.com/umutxyp/musicbot/blob/main/SHARDING.md Configure the delay between shard spawns and the timeout for shards to become ready. These settings are crucial for preventing shard timeouts during startup and managing concurrent spawns. ```dotenv SHARD_SPAWN_DELAY=7000 SHARD_SPAWN_TIMEOUT=60000 ``` -------------------------------- ### Set Shard Spawn Delay (dotenv) Source: https://github.com/umutxyp/musicbot/blob/main/SHARDING.md Configures a specific delay in milliseconds between spawning individual shards. This helps respect Discord's connection rate limits. ```dotenv SHARD_SPAWN_DELAY=5500 ``` -------------------------------- ### Enable Automatic Shard Count (dotenv) Source: https://github.com/umutxyp/musicbot/blob/main/SHARDING.md Recommended for production, this setting allows Discord.js to automatically determine the optimal number of shards based on the bot's server count. ```dotenv TOTAL_SHARDS=auto SHARD_LIST=auto ``` -------------------------------- ### Direct Audio Link Support Source: https://context7.com/umutxyp/musicbot/llms.txt Supports playback of direct audio file URLs including MP3, WAV, OGG, FLAC, and others. Includes functions to validate URLs, check accessibility, retrieve file information, and get audio streams. Uses the DirectLink module. ```javascript const DirectLink = require('./src/DirectLink'); // Validate URL const isValid = DirectLink.isDirectAudioLink('https://example.com/song.mp3'); const accessible = await DirectLink.validateUrl('https://example.com/song.mp3'); // Get file info const info = await DirectLink.getInfo('https://example.com/audio.mp3', guildId); // Returns: { title, artist, url, duration, thumbnail, platform: 'direct' } // Get stream const stream = await DirectLink.getStream( 'https://example.com/audio.mp3', guildId, 30 // Start at 30 seconds ); // Supported formats: .mp3, .wav, .ogg, .flac, .m4a, .aac, .wma, .opus, .webm ``` -------------------------------- ### SoundCloud Integration via yt-dlp Source: https://context7.com/umutxyp/musicbot/llms.txt Integrates SoundCloud support for tracks and playlists using yt-dlp. It allows searching, retrieving track information, fetching playlists, and getting audio streams. Requires the SoundCloud module. ```javascript const SoundCloud = require('./src/SoundCloud'); // Search SoundCloud const results = await SoundCloud.search('deadmau5', 5, guildId); // Returns: Array of track objects // Get track info const trackInfo = await SoundCloud.getInfo( 'https://soundcloud.com/artist/track', guildId ); // Get playlist const playlist = await SoundCloud.getPlaylist( 'https://soundcloud.com/artist/sets/playlist-name', guildId ); // Get stream const stream = await SoundCloud.getStream(trackUrl, guildId, 0); ``` -------------------------------- ### Configure Shard List using Environment Variable Source: https://github.com/umutxyp/musicbot/blob/main/README.md This configuration snippet shows how to manually specify which shards to spawn by setting the `SHARD_LIST` environment variable. This is useful for testing or running only a subset of shards. ```dotenv SHARD_LIST=[0,1,2] # Only spawn shards 0, 1, and 2 ``` -------------------------------- ### Configure Sharding Settings Source: https://github.com/umutxyp/musicbot/blob/main/README.md Environment variables to configure the sharding behavior of the musicbot. These settings allow for automatic shard calculation, specific shard lists, respawning, and delays between shard spawns. ```dotenv # Sharding Settings TOTAL_SHARDS=auto # 'auto' = Discord calculates optimal count SHARD_LIST=auto # 'auto' = spawn all shards, or [0,1,2] for specific SHARD_MODE=process # 'process' (recommended) or 'worker' SHARD_RESPAWN=true # Auto-restart crashed shards SHARD_SPAWN_DELAY=5500 # Delay between spawning shards (ms) SHARD_SPAWN_TIMEOUT=30000 # Timeout for shard ready event (ms) ``` -------------------------------- ### Increase Shard Spawn Timeout (dotenv) Source: https://github.com/umutxyp/musicbot/blob/main/SHARDING.md This setting increases the time Discord.js waits for a shard to become ready before considering it timed out. Useful for slow startup environments. ```dotenv SHARD_SPAWN_TIMEOUT=60000 ``` -------------------------------- ### Configure Environment Variables for Bot Features Source: https://context7.com/umutxyp/musicbot/llms.txt Defines the necessary environment variables for configuring various features of the music bot, including Discord integration, Spotify, Genius lyrics, and optional YouTube cookie support. It also includes settings for bot customization and sharding for scalability. ```bash # .env file configuration # Discord Bot (Required) DISCORD_TOKEN=your_discord_bot_token CLIENT_ID=your_application_client_id # Spotify Integration (Required for Spotify support) SPOTIFY_CLIENT_ID=your_spotify_client_id SPOTIFY_CLIENT_SECRET=your_spotify_client_secret # Genius Lyrics (Optional - improves lyrics accuracy) GENIUS_CLIENT_ID=your_genius_client_id GENIUS_CLIENT_SECRET=your_genius_client_secret # YouTube Cookie Support (Optional - bypasses bot detection) COOKIES_FROM_BROWSER=chrome # Or use cookie file: # COOKIES_FILE=./cookies.txt # Bot Customization STATUS=🎵 Beatra | /play EMBED_COLOR=#FF6B6B SUPPORT_SERVER=https://discord.gg/your-server WEBSITE=https://your-website.com # Sharding (For 1000+ servers) TOTAL_SHARDS=auto SHARD_LIST=auto SHARD_MODE=process SHARD_RESPAWN=true SHARD_SPAWN_DELAY=5500 SHARD_SPAWN_TIMEOUT=30000 # Guild ID (Optional - for testing commands in specific server) GUILD_ID=your_test_guild_id ``` -------------------------------- ### Set YouTube Cookies from Browser Source: https://github.com/umutxyp/musicbot/blob/main/README.md Configure environment variables to automatically extract cookies from your browser for yt-dlp. This helps bypass YouTube's bot detection. Ensure you are logged into YouTube in the specified browser. ```env # For Chrome users COOKIES_FROM_BROWSER=chrome # For Firefox users COOKIES_FROM_BROWSER=firefox # For Edge users COOKIES_FROM_BROWSER=edge # For Safari users COOKIES_FROM_BROWSER=safari ``` -------------------------------- ### Configure Manual Shard Count using Environment Variable Source: https://github.com/umutxyp/musicbot/blob/main/README.md This configuration snippet demonstrates how to force a specific number of shards to be used, overriding the automatic calculation, by setting the `TOTAL_SHARDS` environment variable. ```dotenv TOTAL_SHARDS=4 # Force 4 shards regardless of server count ``` -------------------------------- ### Monitor Shard Status Output Source: https://github.com/umutxyp/musicbot/blob/main/README.md This output demonstrates how the musicbot displays real-time status updates for each shard, including launch messages, readiness confirmations, server counts, and the total number of servers across all shards. ```logs [SHARD MANAGER] Launching shard 0... [SHARD 0] ✅ Shard 0 is ready! [SHARD 0] 🎵 Music bot serving 847 servers on this shard! [SHARD 0] 🌐 Total servers across all shards: 1523 [SHARD MANAGER] Launching shard 1... [SHARD 1] ✅ Shard 1 is ready! [SHARD 1] 🎵 Music bot serving 676 servers on this shard! ``` -------------------------------- ### Shard Count Calculator Formula Source: https://github.com/umutxyp/musicbot/blob/main/SHARDING.md Formula to calculate the recommended number of shards based on the total number of servers the bot will serve. Discord.js can automatically calculate this when TOTAL_SHARDS is set to 'auto'. ```javascript // Formula: Math.ceil(total_servers / 1000) = required_shards ``` -------------------------------- ### Configure Sharding for Large Bot Deployments Source: https://context7.com/umutxyp/musicbot/llms.txt Sets up a sharding manager to distribute a Discord bot across multiple processes, suitable for bots managing over 1000 servers. It utilizes `discord.js`'s ShardingManager to control shard creation, respawning, and communication. Configuration can be done via code or environment variables. ```javascript // In shard.js const { ShardingManager } = require('discord.js'); const config = require('./config'); const manager = new ShardingManager('./index.js', { token: config.discord.token, totalShards: config.sharding.totalShards, // 'auto' or specific number shardList: config.sharding.shardList, // 'auto' or [0, 1, 2, ...] mode: config.sharding.mode, // 'process' or 'worker' respawn: config.sharding.respawn, // Auto-restart crashed shards shardArgs: [], execArgv: [], token: config.discord.token }); manager.on('shardCreate', shard => { console.log(`Launched shard ${shard.id}`); shard.on('ready', () => { console.log(`Shard ${shard.id} ready`); }); shard.on('disconnect', () => { console.warn(`Shard ${shard.id} disconnected`); }); shard.on('reconnecting', () => { console.log(`Shard ${shard.id} reconnecting`); }); }); manager.spawn({ amount: manager.totalShards, delay: 5500, // Discord rate limit compliance timeout: 30000 }); // Environment variables for sharding: // TOTAL_SHARDS=auto // SHARD_LIST=auto // SHARD_MODE=process // SHARD_RESPAWN=true // SHARD_SPAWN_DELAY=5500 // SHARD_SPAWN_TIMEOUT=30000 ``` -------------------------------- ### Configure Genius API Credentials Source: https://github.com/umutxyp/musicbot/blob/main/README.md This snippet shows how to add your Genius API Client ID and Client Secret to the .env file for authentication. These credentials are obtained from the Genius API Clients Page. Without them, the bot will fall back to web scraping for lyrics. ```dotenv GENIUS_CLIENT_ID=your_genius_client_id GENIUS_CLIENT_SECRET=your_genius_client_secret ``` -------------------------------- ### Spotify Integration for Music Search Source: https://context7.com/umutxyp/musicbot/llms.txt Integrates with Spotify to search for tracks, albums, and playlists, then finds corresponding YouTube audio streams for playback. Requires Spotify API credentials to be set as environment variables. Supports initializing the API, searching by various criteria, and retrieving content by URL or ID. ```javascript const Spotify = require('./src/Spotify'); await Spotify.initializeApi(); const results = await Spotify.search('daft punk', 10, 'track', guildId); const track = await Spotify.getFromURL( 'https://open.spotify.com/track/0DiWol3AO6WpXZgp0goxAV', guildId ); const album = await Spotify.getAlbum('albumId', guildId); const playlist = await Spotify.getPlaylist('playlistId', guildId); const topTracks = await Spotify.getArtistTopTracks('artistId', guildId); // Required environment variables: // SPOTIFY_CLIENT_ID=your_client_id // SPOTIFY_CLIENT_SECRET=your_client_secret ``` -------------------------------- ### YouTube Integration for Music Streaming Source: https://context7.com/umutxyp/musicbot/llms.txt Handles YouTube searches, playlist extraction, and direct streaming. It supports bypassing bot detection using cookies configured via environment variables. Provides functions to get search results, video information, playlist contents, and stream URLs with seeking capabilities. ```javascript const YouTube = require('./src/YouTube'); const results = await YouTube.search('lofi hip hop', 5, guildId); const videoInfo = await YouTube.getInfo( 'https://www.youtube.com/watch?v=jfKfPfyJRdk', guildId ); const playlist = await YouTube.getPlaylist( 'https://www.youtube.com/playlist?list=PLRBp0Fe2GpgmsW46rJyudVFlY6IYjFBIK', guildId ); const streamInfo = await YouTube.getStream(videoUrl, guildId, 30); // Start at 30 seconds // Configure cookie support in .env for bot detection bypass // COOKIES_FROM_BROWSER=chrome // Or: COOKIES_FILE=./cookies.txt ``` -------------------------------- ### Save and Restore Player State with PlayerStateManager Source: https://context7.com/umutxyp/musicbot/llms.txt Manages saving and restoring active playback sessions across bot restarts. It allows saving the current player state, retrieving it, getting all saved states, removing a state, and accessing protected cache files to prevent deletion during cleanup. Dependencies include the PlayerStateManager module. ```javascript const PlayerStateManager = require('./src/PlayerStateManager'); // Save player state await PlayerStateManager.saveState(guildId, { voiceChannelId: '123456789', textChannelId: '987654321', queue: player.queue, currentTrack: player.currentTrack, volume: 75, loop: 'queue', shuffle: true, autoplay: 'lofi', paused: false, pausedTime: 0, currentTrackStartOffsetMs: 45000, // 45 seconds into track currentDownloadedFile: '/path/to/track.opus', downloadedFiles: ['/path/to/track1.opus', '/path/to/track2.opus'] }); // Restore state const savedState = PlayerStateManager.getState(guildId); if (savedState) { await player.restoreFromState(savedState); } // Get all saved sessions const allStates = PlayerStateManager.getAllStates(); // Remove state after player disconnects await PlayerStateManager.removeState(guildId); // Get protected cache files (prevents deletion during cleanup) const protectedFiles = PlayerStateManager.getProtectedCacheFiles(); ```