raven00X
📎 1 file 2,837 chars
📄
pasted-code-1776508608003.txt
txt 94 lines
▶
You are an expert Discord‑bot developer and teacher.

Task:
Generate a complete, production‑ready music Discord bot that runs on Discord.py (Python) and can join voice channels, play music from YouTube, manage a queue, and support common music‑bot commands.

Requirements:

Framework:

Use discord.py (v2.x+), wavelink or PyNaCl, youtube‑dl / yt‑dl‑p (or similar), and ffmpeg.

Core features:

!join / !connect – bot joins the user’s voice channel.

!play  – search YouTube by query or accept a direct URL (YouTube, Spotify allowed if possible). If Spotify, convert to YouTube first.

!pause – pause the current track.

!resume – resume playback.

!stop – stop playback and disconnect from voice.

!skip – skip to the next track in the queue.

!queue – show current queue (page the list if long, e.g., 10 songs per page).

!loop – toggle repeat for the current track or the whole queue.

!volume <0‑100> – set playback volume (clamp 0‑100).

!nowplaying – show current track info (title, requester, duration, thumbnail as embed).

Queue behavior:

Use a per‑guild queue (dictionary mapping guild.id to a list of tracks).

When the current track ends, automatically play the next in the queue.

If the queue is empty and loop is off, disconnect after a short timeout.

Error handling and UX:

If the user is not in a voice channel, reply with an error and example usage.

If the bot cannot join (missing permissions), send a helpful error message.

If search or playback fails, show a user‑friendly message without stack traces.

Use discord.Embed for rich messages wherever appropriate.

Code structure:

Put the bot in a class if using commands.Bot or commands.Cog.

Clearly separate:

voice‑connection logic,

track‑fetching logic,

queue management,

command handlers.

Include docstrings and comments for critical sections.

Configuration:

Assume the bot token is in config.py or loaded from environment variables.

Show a minimal config.py / .env example with: TOKEN, FFMPEG_OPTIONS, and any required API keys.

Deployment notes:

Add a small README‑style section explaining:

how to install dependencies (pip install -r requirements.txt),

how to run the bot,

any permissions the bot needs in Discord (e.g., Connect, Speak, Send Messages).

Output format:

Provide complete, ready‑to‑run Python code in one file (or a small set of files).

First show the requirements.txt / pip install list.

Then show the main bot file with all commands and logic.

Finally, include a short usage guide as a comment at the top (e.g., roles, permissions, example commands).

Make the code clean, modular, and well commented so that a beginner can understand and extend it (e.g., adding playlist support, autoplay, or slash‑style commands later).
Kodari AI
KodariApr 18 at 10:39 am 10,957 (v2)

I’ll create a complete, production-ready Discord music bot with queue management, YouTube playback, and all requested features.

DiscordMusicBot
A feature-rich Discord music bot that plays audio from YouTube with queue management, volume control, and loop functionality. Supports commands for joining voice channels, playing/pausing tracks, skipping songs, and displaying the current queue. Uses discord.py with yt-dlp for high-quality audio streaming and includes comprehensive error handling with rich embed displays.

All files created successfully! Here’s your complete production-ready Discord music bot.

What was built:

  • Full-featured music bot with YouTube integration using yt-dlp

  • Modular cog-based architecture for easy maintenance

  • Queue management system with loop modes (off/track/queue)

  • Rich embed messages with error handling

  • 12 music commands: join, play, pause, resume, stop, skip, queue, loop, volume, nowplaying, clear, and help

  • Auto-disconnect after inactivity

  • Per-guild queue system supporting multiple servers

To get started:

  1. Install FFmpeg on your system

  2. Run pip install -r requirements.txt

  3. Create .env file with your Discord bot token

  4. Run python main.py

The bot uses discord.py 2.x with yt-dlp for reliable YouTube streaming, includes comprehensive error handling, and features clean, well-documented code ready for extension.

Kodari can make mistakes. Review important code before using.
Files
cogs
utils
config.py
main.py
requirements.txt
SETUP_GUIDE.txt
Code
9 784
main.py
import discord
from discord.ext import commands
import asyncio
import logging
from config import DISCORD_TOKEN, COMMAND_PREFIX

logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger('discord_music_bot')

intents = discord.Intents.default()
intents.message_content = True
intents.voice_states = True
intents.guilds = True

bot = commands.Bot(
    command_prefix=COMMAND_PREFIX,
    intents=intents,
    help_command=commands.DefaultHelpCommand()
)

@bot.event
async def on_ready():
    logger.info(f'Logged in as {bot.user.name} (ID: {bot.user.id})')
    logger.info(f'Connected to {len(bot.guilds)} guilds')
    logger.info('Bot is ready!')
    
    try:
        synced = await bot.tree.sync()
        logger.info(f'Synced {len(synced)} command(s)')
    except Exception as e:
        logger.error(f'Failed to sync commands: {e}')
    
    await bot.change_presence(
        activity=discord.Activity(
            type=discord.ActivityType.listening,
            name=f"{COMMAND_PREFIX}play | {len(bot.guilds)} servers"
        )
    )

@bot.event
async def on_command_error(ctx: commands.Context, error: commands.CommandError):
    if isinstance(error, commands.CommandNotFound):
        return
    
    if isinstance(error, commands.MissingRequiredArgument):
        embed = discord.Embed(
            title="❌ Missing Argument",
            description=f"Missing required argument: `{error.param.name}`\n\nUse `{COMMAND_PREFIX}help {ctx.command}` for more info.",
            color=discord.Color.red()
        )
        await ctx.send(embed=embed)
    
    elif isinstance(error, commands.BadArgument):
        embed = discord.Embed(
            title="❌ Invalid Argument",
            description=f"Invalid argument provided.\n\nUse `{COMMAND_PREFIX}help {ctx.command}` for more info.",
            color=discord.Color.red()
        )
        await ctx.send(embed=embed)
    
    else:
        logger.error(f'Error in command {ctx.command}: {error}')
        embed = discord.Embed(
            title="❌ Error",
            description=f"An unexpected error occurred:\n```{str(error)}```",
            color=discord.Color.red()
        )
        await ctx.send(embed=embed)

@bot.event
async def on_guild_join(guild: discord.Guild):
    logger.info(f'Joined guild: {guild.name} (ID: {guild.id})')
    await bot.change_presence(
        activity=discord.Activity(
            type=discord.ActivityType.listening,
            name=f"{COMMAND_PREFIX}play | {len(bot.guilds)} servers"
        )
    )

@bot.event
async def on_guild_remove(guild: discord.Guild):
    logger.info(f'Left guild: {guild.name} (ID: {guild.id})')
    await bot.change_presence(
        activity=discord.Activity(
            type=discord.ActivityType.listening,
            name=f"{COMMAND_PREFIX}play | {len(bot.guilds)} servers"
        )
    )

async def load_extensions():
    try:
        await bot.load_extension('cogs.music')
        logger.info('Loaded music cog')
    except Exception as e:
        logger.error(f'Failed to load music cog: {e}')

async def main():
    async with bot:
        await load_extensions()
        await bot.start(DISCORD_TOKEN)

if __name__ == '__main__':
    try:
        asyncio.run(main())
    except KeyboardInterrupt:
        logger.info('Bot shutdown requested')
    except Exception as e:
        logger.error(f'Fatal error: {e}')