Create a YouTube music discord bot using yt-dlp that has playlist support and lyrics…
- User
Create a YouTube music discord bot using yt-dlp that has playlist support and lyrics searching
- Assistant
Create a YouTube music discord bot using yt-dlp that has playlist support and lyrics searching
Creating a Discord music bot that streams audio from YouTube using yt-dlp, supports playlists, and includes lyrics searching is an engaging project that combines several technologies. Below is a step-by-step guide to help you build this bot using Python.
Disclaimer: Before proceeding, please be aware that streaming or downloading content from YouTube may violate YouTube's Terms of Service. Ensure that you have the necessary rights and permissions to access and stream the content. This guide is for educational purposes, and you should comply with all applicable laws and platform policies.
Python 3.7 or higher: Ensure you have Python installed. You can download it from the official website.
Discord Account and Server: Create a Discord account if you haven't already and set up a server where you can test your bot.
Discord Bot Token: You need to create a bot account to obtain a token.
FFmpeg: The bot uses FFmpeg to handle audio encoding.
brew install ffmpeg.sudo apt-get install ffmpeg.Install Required Python Libraries:
Open your terminal and run:
pip install discord.py yt-dlp lyricsgenius
discord.py: Discord API wrapper for Python.yt-dlp: Fork of youtube-dlc, which is a fork of youtube-dl, used to download audio streams.lyricsgenius: Python client for the Genius API to search for lyrics.Genius API Token: For lyrics searching, you'll need a Genius API token.
Create a new directory for your bot and navigate into it:
mkdir discord-music-bot
cd discord-music-bot
Create a Python script, e.g., bot.py:
touch bot.py
Below is the complete code for your bot. Explanations are provided in comments.
Bot Initialization: The bot is initialized with a command prefix !. Adjust it as needed.
Intents: Discord now requires explicit intents to access certain information. The message_content intent allows the bot to read the content of messages, which is necessary for commands.
Music Queue: Implemented as a simple list to hold songs. The bot uses an is_playing flag to determine if it should start playing or just queue songs.
Search and Play Functions: search_yt() handles searching and retrieving video information from YouTube. The play_next() function manages playing songs from the queue.
Commands:
!join: Bot joins the user's voice channel.!leave: Bot disconnects from the voice channel.!play [song name or URL]: Searches for the song and adds it to the queue.!queue: Displays the current music queue.!skip: Skips the currently playing song.!lyrics [song name]: Searches for the lyrics of the specified song. If no song is specified and music is playing, it attempts to find lyrics for the current song.Replace Placeholder Tokens: In the script, replace 'YOUR_DISCORD_BOT_TOKEN' and 'YOUR_GENIUS_API_TOKEN' with your actual tokens.
Run the Script:
python bot.py
Invite the Bot to Your Server:
bot.Send Messages, Connect, Speak).Test the Bot:
!join to have the bot join your voice channel.!play [song name or YouTube URL] to play music.!lyrics [song name] to get the lyrics.Error Handling: Implement try-except blocks and checks to handle exceptions and edge cases gracefully.
Playlist Support: The search_yt() function already handles playlists by checking if 'entries' is in the info dictionary. YTDL automatically parses playlists if a playlist URL is provided.
Improved Queue Management: Consider implementing queue management commands like !pause, !resume, !remove [index], and !clear.
Looping and Shuffling: Add functionality to loop the current song or shuffle the queue.
Persistent Queue: Save the queue state to a file or database to preserve it between restarts.
Custom Prefix and Configurations: Allow users to set a custom command prefix or adjust settings via commands.
Resource Cleanup: Make sure to handle resources properly. If the bot disconnects unexpectedly, it might leave dangling voice connections.
Latency and Performance: For production use, consider optimizing for lower latency and better performance, possibly by running the bot on a server with good uptime.
Legal Compliance: Always ensure that your use of APIs and content complies with all relevant laws and terms of service.
By following this guide, you should have a functional Discord music bot capable of playing music from YouTube, supporting playlists, and fetching song lyrics. Feel free to customize and expand upon this foundation to suit your needs.
Disclaimer: This bot is for personal and educational use. Redistribution or public hosting of the bot may require you to obtain permissions for the content accessed and comply with Discord's Terms of Service and other relevant policies.
Not yet included in a published release.
import os
import asyncio
import discord
from discord.ext import commands
import yt_dlp as youtube_dl
import lyricsgenius
# Replace these with your tokens
DISCORD_TOKEN = 'YOUR_DISCORD_BOT_TOKEN' # Replace with your bot's token
GENIUS_TOKEN = 'YOUR_GENIUS_API_TOKEN' # Replace with your Genius API token
# Intents are required for the bot to function properly in newer versions of discord.py
intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix='!', intents=intents)
# Initialize Genius API client
genius = lyricsgenius.Genius(GENIUS_TOKEN)
# Suppress noise about console usage from errors
youtube_dl.utils.bug_reports_message = lambda: ''
# YTDL and FFMPEG configuration
ytdl_format_options = {
'format': 'bestaudio/best',
'outtmpl': 'downloads/%(extractor)s-%(id)s-%(title)s.%(ext)s',
'restrictfilenames': True,
'nocheckcertificate': True,
'ignoreerrors': False,
'logtostderr': False,
'quiet': True,
'no_warnings': True,
'default_search': 'auto',
# For playlist support
'playlistend': 5 # Limits the number of playlist items to download
}
ffmpeg_options = {
'options': '-vn'
}
ytdl = youtube_dl.YoutubeDL(ytdl_format_options)
# Music queue and related variables
music_queue = []
is_playing = False
# Function to search and download the audio from the YouTube URL
def search_yt(item):
with ytdl:
try:
info = ytdl.extract_info(item, download=False)
except Exception:
return False
# 'entries' is a key when it's a playlist
if 'entries' in info:
# Can be a playlist or a list of videos
video = info['entries']
else:
video = [info]
return video
# Play next song in the queue
async def play_next(ctx):
global is_playing
if len(music_queue) > 0:
is_playing = True
# Get the first URL
m_url = music_queue.pop(0)
# Try to connect to voice channel if not already connected
if ctx.voice_client is None:
await ctx.invoke(join)
# Create the player and play the music
ctx.voice_client.play(discord.FFmpegPCMAudio(m_url['url'], **ffmpeg_options), after=lambda e: asyncio.run_coroutine_threadsafe(play_next(ctx), bot.loop))
await ctx.send(f"Now playing: {m_url['title']}")
else:
is_playing = False
# Command to join voice channel
@bot.command(name='join')
async def join(ctx):
if ctx.author.voice:
channel = ctx.author.voice.channel
await channel.connect()
else:
await ctx.send("You're not connected to a voice channel!")
# Command to leave voice channel
@bot.command(name='leave')
async def leave(ctx):
if ctx.voice_client:
await ctx.voice_client.disconnect()
else:
await ctx.send("I'm not connected to a voice channel!")
# Command to play a song
@bot.command(name='play')
async def play(ctx, *, search: str):
global is_playing
# Search for song
songs = search_yt(search)
if songs is False:
await ctx.send("Could not download the song. Incorrect format.")
return
# Add song(s) to the queue
for song in songs:
music_queue.append({'source': song['url'], 'title': song['title'], 'url': song['webpage_url']})
await ctx.send(f"Added to queue: {songs[0]['title']}")
if not is_playing:
await play_next(ctx)
# Command to display the queue
@bot.command(name='queue')
async def queue_(ctx):
if len(music_queue) == 0:
await ctx.send("The queue is empty.")
else:
queue_list = ''
for i, song in enumerate(music_queue):
queue_list += f"{i+1}. {song['title']}\n"
await ctx.send(f"Current Queue:\n{queue_list}")
# Command to skip the current song
@bot.command(name='skip')
async def skip(ctx):
if ctx.voice_client:
ctx.voice_client.stop()
await play_next(ctx)
else:
await ctx.send("I'm not playing any song!")
# Command to search for lyrics
@bot.command(name='lyrics')
async def lyrics(ctx, *, song_name: str = None):
if song_name is None and ctx.voice_client and ctx.voice_client.is_playing():
# Use the currently playing song's title
song_name = ctx.voice_client.source.title
if song_name is None:
await ctx.send("Please specify a song name.")
return
song = genius.search_song(song_name)
if song:
# Discord has a character limit for messages (2000), so we may need to truncate or split the lyrics
lyrics = song.lyrics
if len(lyrics) > 2000:
# Split the lyrics into multiple messages
for i in range(0, len(lyrics), 2000):
await ctx.send(lyrics[i:i+2000])
else:
await ctx.send(lyrics)
else:
await ctx.send("Lyrics not found.")
# Run the bot
bot.run(DISCORD_TOKEN)