Skip to main content

Common Issues

Missing Dependencies

Problem

Bot fails to start with ModuleNotFoundError:
ModuleNotFoundError: No module named 'discord'
ModuleNotFoundError: No module named 'yt_dlp'

Solution

Install all required dependencies:
pip install -r requirements.txt
Or install individually:
pip install discord.py yt-dlp python-dotenv requests
Verify installation:
python3 -c "import discord; import yt_dlp; print('All dependencies installed')"

API Key Errors

Missing DISCORD_BOT_TOKEN

Error message (bot.py:103-105):
CRITICAL: DISCORD_BOT_TOKEN not found in environment variables.
Exiting: DISCORD_BOT_TOKEN not set. Please check your .env file
Solution:
  1. Create a .env file in the bot directory:
touch .env
  1. Add your Discord bot token:
DISCORD_BOT_TOKEN=your_token_here
YOUTUBE_API_KEY=your_youtube_key_here
  1. Get your Discord bot token from:

Missing YOUTUBE_API_KEY

Error message (bot.py:99-101):
CRITICAL: YOUTUBE_API_KEY not found in environment variables.
Exiting: YOUTUBE_API_KEY not set.
Solution:
  1. Get a YouTube Data API v3 key:
    • Visit Google Cloud Console
    • Create a project
    • Enable YouTube Data API v3
    • Create credentials (API key)
  2. Add to .env file:
YOUTUBE_API_KEY=AIzaSyXXXXXXXXXXXXXXXXXXXXXXXXXX
Note: The bot will still work for direct YouTube URLs without an API key, but search functionality (!play song name) requires it.

Invalid Discord Token

Error message (bot.py:755-756):
Login Failure: Invalid Discord token. Please check your DISCORD_BOT_TOKEN.
Solution:
  • Regenerate your token in the Discord Developer Portal
  • Ensure no extra spaces or quotes in .env file
  • Token should be a long string without spaces

Permission Errors

Cannot Join Voice Channel

Error message (bot.py:253-257):
Error connecting to voice channel: Missing Permissions
Could not join your voice channel. Error: Missing Permissions
Solution:
  1. Check bot permissions in Discord:
    • Connect - Required to join voice channels
    • Speak - Required to play audio
    • Use Voice Activity - Recommended
  2. Verify channel-specific permissions:
    • Right-click voice channel → Edit Channel → Permissions
    • Ensure bot role has voice permissions
  3. Re-invite bot with correct permissions:
https://discord.com/api/oauth2/authorize?client_id=YOUR_CLIENT_ID&permissions=36703232&scope=bot
Permissions integer 36703232 includes:
  • Connect
  • Speak
  • Send Messages
  • Read Message History

File Permission Errors

Error message:
OSError: [Errno 13] Permission denied: 'music/123456789'
Error deleting cache directory: Permission denied
Solution:
  1. Check directory permissions:
ls -la music/
  1. Fix permissions:
chmod -R 755 music/
  1. Ensure bot process has write access to working directory

FFmpeg Not Found

Problem

Error when playing audio:
FileNotFoundError: [Errno 2] No such file or directory: 'ffmpeg'
Error trying to play: FFmpeg was not found
FFmpeg is required for audio processing (bot.py:70, 628).

Solution

Ubuntu/Debian:
sudo apt update
sudo apt install ffmpeg
macOS:
brew install ffmpeg
Windows:
  1. Download from ffmpeg.org
  2. Extract to C:\ffmpeg
  3. Add C:\ffmpeg\bin to system PATH
Verify installation:
ffmpeg -version
Should output version information.

YouTube Download Errors

yt_dlp.utils.DownloadError

Error message (bot.py:403-406):
yt-dlp download error: Video unavailable
Error downloading the song. It might be region-locked, private, deleted, or invalid.
Common causes:
  1. Region-locked video
    • Video not available in bot’s region
    • No direct solution (use VPN for bot)
  2. Private/deleted video
    • Video removed or set to private
    • Try different video
  3. Age-restricted content
    • yt-dlp cannot access without authentication
    • Avoid age-restricted videos
  4. Live streams
    • Bot configured with noplaylist: True (bot.py:75)
    • May not support live content
Solutions:
  1. Check if video is accessible in browser
  2. Try different search terms
  3. Use direct URL instead of search
  4. Check yt-dlp logs:
ydl_opts['quiet'] = False  # Enable verbose output

HTTP Error 429 (Too Many Requests)

Error message:
HTTP Error 429: Too Many Requests
Solution:
  1. YouTube rate limiting detected
  2. Wait 10-30 minutes before retrying
  3. Use cache to reduce downloads (automatic)
  4. Consider rotating IP addresses for heavy usage

Network Timeout

Error message (bot.py:154-156):
Request error occurred during YouTube search: Connection timeout
Solution:
  1. Check internet connection
  2. Increase timeout (bot.py:139):
response = requests.get(youtube_api_url, params=params, timeout=10)  # Increase from 5
  1. Check if YouTube is accessible:
curl https://www.youtube.com

Voice Connection Issues

Bot Joins But No Audio

Symptoms:
  • Bot shows as connected
  • “Now playing” message sent
  • No audio output
Solutions:
  1. Check voice client status:
logger.info(f"Voice client playing: {voice_client.is_playing()}")
logger.info(f"Voice client connected: {voice_client.is_connected()}")
  1. Verify FFmpeg installation (see FFmpeg section)
  2. Check file exists (bot.py:611-624):
if not os.path.exists(file_path):
    logger.error(f"File not found for playback: {file_path}")
  1. Reconnect bot:
!leave
!play <song>

Bot Disconnects Unexpectedly

Possible causes:
  1. Inactivity timeout (bot.py:25, 701-741)
    • Default: 300 seconds (5 minutes)
    • Expected behavior when queue is empty
    • Check logs:
    Disconnecting due to inactivity from guild {guild_id}
    
  2. Voice connection lost
    • Network issues
    • Discord server issues
    • Bot will log: voice_client is not valid or not connected
  3. Manual kick from voice channel
    • User action
    • No error, bot clears queue
Solutions:
  1. Adjust inactivity timeout:
inactive_time = 600  # 10 minutes
  1. Add songs to queue to keep bot active
  2. Check Discord API status: status.discord.com

Already Connected to Different Channel

Error message (bot.py:238-240):
I am already in a different voice channel: 'Music Room'
Solution:
  1. Bot can only be in one voice channel per guild
  2. Options:
    • Have requester join bot’s current channel
    • Use !leave then !play from new channel
    • Bot will not auto-move between channels

File Path and Caching Issues

Downloaded File Not Found

Error message (bot.py:363-365):
Critical: Downloaded file for {video_id} not found after download.
Error: Could not locate the downloaded file after download.
Causes:
  1. FFmpeg conversion failed
    • MP3 conversion incomplete
    • Check FFmpeg logs
  2. Disk space full
    • Check available space:
    df -h
    
  3. File path mismatch
    • yt-dlp output format doesn’t match expected
    • Check logs for actual filename
Solutions:
  1. Verify yt-dlp output template (bot.py:326):
download_opts['outtmpl'] = os.path.join(guild_music_dir, '%(id)s.%(ext)s')
  1. Check music/<guild_id>/ directory contents:
ls -la music/*/
  1. Enable verbose yt-dlp logging:
ydl_opts['quiet'] = False

Cache Directory Issues

Problem: Cache not being used or cleared unexpectedly Solutions:
  1. Verify cache structure (bot.py:281-282):
tree music/
# Expected:
# music/
# └── 123456789/
#     ├── dQw4w9WgXcQ.mp3
#     └── jNQXAC9IVRw.mp3
  1. Check cache hit logs (bot.py:315-316):
Cache hit: Using existing file music/123456789/dQw4w9WgXcQ.mp3
  1. Cache is cleared on:
    • !leave command (bot.py:462-476)
    • !clearcache command (bot.py:514-545)
  2. Prevent accidental cache deletion:
    • Don’t manually delete music/ directory while bot is running
    • Use !clearcache for controlled cleanup

Logging System

Configuration

The bot uses Python’s standard logging module (bot.py:82-90):
logger = logging.getLogger('discord')
logger.setLevel(logging.INFO)
handler = logging.StreamHandler(sys.stdout)
formatter = logging.Formatter('%(asctime)s:%(levelname)s:%(name)s: %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)

Log Levels

CRITICAL - Fatal errors, bot cannot continue:
CRITICAL: DISCORD_BOT_TOKEN not found
Login Failure: Invalid Discord token
ERROR - Operation failed but bot continues:
ERROR: HTTP error during YouTube search
ERROR: File not found for playback
WARNING - Unexpected but handled:
WARNING: MP3 not found, using original extension
WARNING: Could not update presence
INFO - Normal operations:
INFO: Bot joined voice channel
INFO: Download complete for 'Song Name'
DEBUG - Detailed information (disabled by default):
DEBUG: Presence updated

Enabling Debug Logging

Modify logging level (bot.py:85):
logger.setLevel(logging.DEBUG)

Logging to File

Change handler (bot.py:86-87):
handler = logging.FileHandler("bot.log")  # Instead of StreamHandler
Or add both:
file_handler = logging.FileHandler("bot.log")
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)
logger.addHandler(handler)  # Keep console output

Reading Logs

Real-time monitoring:
tail -f bot.log
Search for errors:
grep ERROR bot.log
grep CRITICAL bot.log
Filter by guild:
grep "guild 123456789" bot.log

Advanced Debugging

Voice Client State

Add debug logging in commands:
logger.info(f"Voice client: {guild_state.voice_client}")
logger.info(f"Connected: {guild_state.voice_client.is_connected() if guild_state.voice_client else False}")
logger.info(f"Playing: {guild_state.voice_client.is_playing() if guild_state.voice_client else False}")
logger.info(f"Queue length: {len(guild_state.queue)}")
logger.info(f"Current song: {guild_state.current_song_title}")

Check Guild State

The __repr__ method (bot.py:42-45) provides useful debug output:
logger.info(guild_state)
# Output: <GuildPlayerState guild_id=123456789 queue_len=3 vc_connected=Yes>

Network Diagnostics

Test YouTube API connectivity:
import requests
response = requests.get(
    'https://www.googleapis.com/youtube/v3/search',
    params={'q': 'test', 'part': 'snippet', 'type': 'video', 'key': YOUTUBE_API_KEY}
)
print(response.status_code, response.json())

yt-dlp Version Issues

yt-dlp frequently updates to handle YouTube changes:
pip install --upgrade yt-dlp
Check version:
python3 -c "import yt_dlp; print(yt_dlp.version.__version__)"

Getting Help

If issues persist:
  1. Check logs for detailed error messages
  2. Enable DEBUG logging for more information
  3. Verify all dependencies are installed and up-to-date
  4. Test with direct YouTube URLs before search queries
  5. Review recent code changes if bot was recently modified
For architecture details, see Architecture Overview.

Build docs developers (and LLMs) love