Okay, here's a basic Discord music bot written in Python using discord.py and yt-dlp (a more actively maintained fork of youtube_dl) for fetching audio streams.
Important Prerequisites:
Python 3.8+: Make sure you have a recent version of Python installed.
ffmpeg: This is a crucial external dependency that discord.py uses to process audio streams. You need to download and install ffmpeg and make sure the executable is accessible in your system's PATH environment variable, or you'll need to provide the full path to it in the code.
Windows: Extract the zip, find the bin folder containing ffmpeg.exe. Add the path to this bin folder to your system's PATH. (Search online for "add to system path windows").
macOS (using Homebrew):brew install ffmpeg
Linux (using package manager):sudo apt update && sudo apt install ffmpeg (Debian/Ubuntu), sudo dnf install ffmpeg (Fedora), etc.
Discord Bot Token: You need to create a bot application on the Discord Developer Portal (https://discord.com/developers/applications), get its token, and invite it to your server with the necessary permissions (Read Message History, Send Messages, Connect, Speak, Use Voice Activity).
Installation:
You'll need to install the required Python libraries:
bash
pip install discord.py yt-dlp
The Code:
python
import discord
from discord.ext import commands
import yt_dlp as youtube_dl
import asyncio
import os
# --- Bot Setup ---
# Define intents (needed for discord.py 2.0+)
intents = discord.Intents.default()
intents.message_content = True # Required to read command content
intents.voice_states = True # Required to interact with voice channels
# Set up the bot prefix
bot = commands.Bot(command_prefix='!', intents=intents)
# --- Configuration ---
# FFmpeg needs to be installed and in your system's PATH
# If ffmpeg is not in PATH, provide the full path like:
# FFMPEG_PATH = "C:/path/to/ffmpeg/bin/ffmpeg.exe" # Windows example
# FFMPEG_PATH = "/usr/local/bin/ffmpeg" # Linux/macOS example
FFMPEG_PATH = 'ffmpeg' # Assumes ffmpeg is in PATH
# FFmpeg options for discord.py
FFMPEG_OPTIONS = {
'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5',
'options': '-vn' # No video
}
# yt-dlp options for extracting audio
YDL_OPTIONS = {
'format': 'bestaudio/best',
'restrictfilenames': True,
'noplaylist': True,
'nocheckcertificate': True,
'ignoreerrors': False,
'logtostderr': False,
'quiet': True,
'no_warnings': True,
'default_search': 'auto', # Allow search queries instead of just URLs
'source_address': '0.0.0.0' # Bind to ipv4 since ipv6 addresses cause issues sometimes
}
# Dictionary to hold queues for each guild (server)
queues = {}
# Dictionary to hold voice clients for each guild
voice_clients = {}
# --- Helper Function: Play Next Song ---
def after_song(ctx):
"""Callback function to play the next song after one finishes."""
guild_id = ctx.guild.id
# Check if there's a queue for this guild and if it's not empty
if guild_id in queues and queues[guild_id]:
# Get the next song (title, URL) from the queue
next_song = queues[guild_id].pop(0)
title, url = next_song
# Get the voice client for this guild
vc = voice_clients.get(guild_id)
if vc and vc.is_connected():
try:
# Create the FFmpeg audio source
source = discord.FFmpegPCMAudio(url, **FFMPEG_OPTIONS, executable=FFMPEG_PATH)
# Play the next song, calling after_song again when finished
vc.play(source, after=lambda e: after_song(ctx) if e is None else print(f'Player error: {e}'))
# Send a message to the context channel about playing the next song
# This needs to be run in an async context, so use bot.loop.create_task
bot.loop.create_task(ctx.send(f'Now playing: **{title}**'))
except Exception as e:
print(f"Error playing next song: {e}")
bot.loop.create_task(ctx.send(f"Could not play the next song: {title}"))
# If there's an error, try playing the song after this one
after_song(ctx) # recursion to skip the problematic song
else:
print(f"Voice client not found or not connected for guild {guild_id}")
# Clear queue if voice client is gone
if guild_id in queues:
del queues[guild_id]
async def play_song(ctx, song_info):
"""Starts playing a song or adds it to the queue."""
guild_id = ctx.guild.id
vc = ctx.voice_client
if not vc:
# If bot is not in a voice channel, try joining
if ctx.author.voice:
vc = await ctx.author.voice.channel.connect()
voice_clients[guild_id] = vc
else:
await ctx.send("You need to be in a voice channel for me to join.")
return
title = song_info['title']
url = song_info['url'] # This is the stream URL
# Get the queue for this guild, create if it doesn't exist
if guild_id not in queues:
queues[guild_id] = []
# Check if something is currently playing
if vc.is_playing():
# Add the song to the queue
queues[guild_id].append((title, url))
await ctx.send(f'Added **{title}** to the queue.')
else:
# Play the song immediately
try:
source = discord.FFmpegPCMAudio(url, **FFMPEG_OPTIONS, executable=FFMPEG_PATH)
vc.play(source, after=lambda e: after_song(ctx) if e is None else print(f'Player error: {e}'))
await ctx.send(f'Now playing: **{title}**')
except Exception as e:
await ctx.send(f"Could not play: **{title}**\nError: {e}")
# --- Bot Events ---
@bot.event
async def on_ready():
print(f'Logged in as {bot.user.name}')
print('------')
# --- Bot Commands ---
@bot.command(name='join', help='Tells the bot to join the voice channel')
async def join(ctx):
if not ctx.author.voice:
await ctx.send(f"{ctx.author.name} is not connected to a voice channel")
return
channel = ctx.author.voice.channel
guild_id = ctx.guild.id
if guild_id in voice_clients and voice_clients[guild_id].is_connected():
# Bot is already in a channel in this guild
if voice_clients[guild_id].channel == channel:
await ctx.send("I'm already in this channel.")
else:
await voice_clients[guild_id].move_to(channel)
await ctx.send(f"Moved to {channel}")
else:
# Bot is not in a channel in this guild
try:
vc = await channel.connect()
voice_clients[guild_id] = vc
await ctx.send(f"Joined {channel}")
except discord.errors.ClientException:
await ctx.send("Could not join the voice channel. Am I missing permissions?")
except Exception as e:
await ctx.send(f"An error occurred while joining: {e}")
@bot.command(name='leave', help='To make the bot leave the voice channel')
async def leave(ctx):
guild_id = ctx.guild.id
vc = voice_clients.get(guild_id)
if not vc or not vc.is_connected():
await ctx.send("I'm not in a voice channel.")
return
# Stop playback and clear the queue before leaving
vc.stop()
if guild_id in queues:
del queues[guild_id]
if guild_id in voice_clients:
del voice_clients[guild_id]
await vc.disconnect()
await ctx.send("Disconnected from the voice channel.")
@bot.command(name='play', help='Plays a song from YouTube (or other sources)')
async def play(ctx, *args):
if not args:
await ctx.send("Please provide a song title or URL.")
return
search_query = " ".join(args)
guild_id = ctx.guild.id
vc = voice_clients.get(guild_id)
# If bot is not in a voice channel, try joining the user's channel first
if not vc or not vc.is_connected():
if ctx.author.voice:
try:
channel = ctx.author.voice.channel
vc = await channel.connect()
voice_clients[guild_id] = vc
await ctx.send(f"Joined {channel} to play the song.")
except discord.errors.ClientException:
await ctx.send("Could not join your voice channel. Please use `!join` first.")
return
except Exception as e:
await ctx.send(f"An error occurred while joining: {e}")
return
else:
await ctx.send("You need to be in a voice channel for me to play music, or use `!join` first.")
return
# Use yt-dlp to get song info. This is a blocking operation, so run it in a separate thread.
await ctx.send(f"Searching for `{search_query}`...")
try:
loop = asyncio.get_event_loop()
# Run blocking yt-dlp operation in a thread
info = await loop.run_in_executor(None, lambda: youtube_dl.YoutubeDL(YDL_OPTIONS).extract_info(search_query, download=False))
# If yt-dlp found a playlist or multiple results, take the first one
if 'entries' in info:
# Take the first entry from a playlist or search results
info = info['entries'][0]
# Now play or queue the song
await play_song(ctx, info)
except youtube_dl.utils.DownloadError as e:
await ctx.send(f"Error: Could not download/extract information for that song. Details: {e}")
except Exception as e:
await ctx.send(f"An unexpected error occurred while processing your request: {e}")
print(f"Error in !play: {e}")
@bot.command(name='stop', help='Stops the current song and clears the queue')
async def stop(ctx):
guild_id = ctx.guild.id
vc = voice_clients.get(guild_id)
if not vc or not vc.is_connected():
await ctx.send("I'm not playing anything.")
return
if vc.is_playing() or vc.is_paused():
vc.stop() # This will trigger the 'after' callback if it's playing
# Clear the queue immediately
if guild_id in queues:
del queues[guild_id]
await ctx.send("Stopped playback and cleared the queue.")
else:
await ctx.send("I'm not currently playing anything.")
@bot.command(name='pause', help='Pauses the current song')
async def pause(ctx):
guild_id = ctx.guild.id
vc = voice_clients.get(guild_id)
if not vc or not vc.is_connected():
await ctx.send("I'm not in a voice channel.")
return
if vc.is_playing():
vc.pause()
await ctx.send("Paused playback.")
else:
await ctx.send("I'm not currently playing anything to pause.")
@bot.command(name='resume', help='Resumes the paused song')
async def resume(ctx):
guild_id = ctx.guild.id
vc = voice_clients.get(guild_id)
if not vc or not vc.is_connected():
await ctx.send("I'm not in a voice channel.")
return
if vc.is_paused():
vc.resume()
await ctx.send("Resumed playback.")
else:
await ctx.send("I'm not currently paused.")
@bot.command(name='queue', help='Shows the current song queue')
async def show_queue(ctx):
guild_id = ctx.guild.id
if guild_id not in queues or not queues[guild_id]:
await ctx.send("The queue is empty.")
return
# Format the queue nicely
queue_list = "\n".join([f"{i+1}. {title}" for i, (title, url) in enumerate(queues[guild_id])])
await ctx.send(f"**Current Queue:**\n{queue_list}")
# --- Run the Bot ---
# It's best practice to load the token from an environment variable
# Set an environment variable named DISCORD_TOKEN with your bot's token
try:
# Replace 'YOUR_BOT_TOKEN' with your actual bot token if not using env var
# TOKEN = 'YOUR_BOT_TOKEN'
TOKEN = os.environ['DISCORD_TOKEN']
bot.run(TOKEN)
except KeyError:
print("Error: DISCORD_TOKEN environment variable not set.")
print("Please set the DISCORD_TOKEN environment variable to your bot's token,")
print("or replace `os.environ['DISCORD_TOKEN']` with your token string in the script.")
except discord.errors.LoginFailure:
print("Error: Bot token is invalid.")
except Exception as e:
print(f"An error occurred during bot startup: {e}")
How to Run:
Save: Save the code as a Python file (e.g., music_bot.py).
Environment Variable (Recommended): Set an environment variable named DISCORD_TOKEN to your bot's token. How you do this depends on your operating system (search online for "set environment variable [your OS]"). This is safer than putting the token directly in the code.
Alternatively, replace os.environ['DISCORD_TOKEN'] with 'YOUR_BOT_TOKEN' and put your token string there (but be careful not to share the code with the token).
Run: Open a terminal or command prompt, navigate to the directory where you saved the file, and run:
bash
python music_bot.py
Invite Bot: If you haven't already, invite the bot to your server using the OAuth2 URL generated from the Discord Developer Portal (under the "OAuth2" -> "URL Generator" section, select bot and applications.commands scopes and the necessary permissions: Connect, Speak, Use Voice Activity, Send Messages, Read Message History).
Test: Go to your Discord server and use the commands:
!join
!play [song title or youtube URL] (e.g., !play never gonna give you up or !play https://www.youtube.com/watch?v=dQw4w9WgXcQ)
!queue
!pause
!resume
!stop
!leave
Explanation:
Imports: Imports discord, commands from discord.ext, yt_dlp, asyncio for asynchronous operations, and os to potentially read the token from environment variables.
Bot Setup: Initializes the bot with a command prefix (!) and specifies the required intents. Intents are mandatory for newer discord.py versions.
Configuration:
FFMPEG_PATH: Specifies the path to your ffmpeg executable. If ffmpeg is in your system's PATH, 'ffmpeg' is usually sufficient.
FFMPEG_OPTIONS: Configures how ffmpeg should process the audio stream.
YDL_OPTIONS: Configures yt-dlp to extract the best audio format without downloading the full file, allowing search queries, etc.
queues and voice_clients: Dictionaries to keep track of song queues and connected voice clients for each guild (server) the bot is in. This is important for managing multiple servers simultaneously.
after_song(ctx): This is a callback function that discord.py runs after vc.play() finishes playing a song. It checks the queue for the specific guild and starts the next song if available using play_next. It uses bot.loop.create_task to send the "Now playing" message asynchronously from within the synchronous callback.
play_song(ctx, song_info): A helper function that either starts playing a song immediately (if the bot is idle) or adds it to the guild's queue. It also handles joining the voice channel if the bot isn't already in one.
on_ready(): An event that fires when the bot successfully connects to Discord. It prints a confirmation message.
Commands (@bot.command()):
!join: Connects the bot to the voice channel the user is in. Handles moving if already connected elsewhere.
!leave: Disconnects the bot, stops playback, and clears the queue for that server.
!play [query]: Takes the user's input, uses yt-dlp to find the song information (including the stream URL), and calls play_song to handle playback or queuing. The part is crucial because is a blocking call and must be run off the main asyncio loop to prevent the bot from freezing.
This code provides a solid foundation. You can extend it further by adding features like volume control, skipping, looping, more sophisticated queue management, displaying current song info, etc.
await loop.run_in_executor(...)
yt-dlp.extract_info
!stop: Stops the current song and clears the entire queue.
!pause: Pauses the current song.
!resume: Resumes a paused song.
!queue: Displays the list of songs currently in the queue.
bot.run(TOKEN): Starts the bot using the provided token. Includes error handling for missing/invalid tokens.