Add music bot with YouTube integration and basic commands Implemented a Discord bot with commands for playing, pausing, skipping, and managing a music queue utilizing yt_dlp and FFmpeg. Includes opus library loading fallback logic and gitignore entry for environment files.
245 lines
8.4 KiB
Python
245 lines
8.4 KiB
Python
import discord
|
|
from discord.ext import commands
|
|
import yt_dlp as youtube_dl
|
|
import asyncio
|
|
import os
|
|
from dotenv import load_dotenv
|
|
import traceback
|
|
import ctypes.util
|
|
|
|
# Add these debug lines after the imports
|
|
print("Searching for opus library...")
|
|
opus_path = ctypes.util.find_library('opus')
|
|
print(f"Found opus path: {opus_path}")
|
|
|
|
# Try multiple known opus library locations
|
|
possible_opus_paths = [
|
|
'/opt/homebrew/lib/libopus.dylib', # Apple Silicon
|
|
'/usr/local/lib/libopus.dylib', # Intel Mac
|
|
'opus', # Default system path
|
|
'libopus', # Alternative name
|
|
'libopus.0.dylib', # Another possible name
|
|
opus_path if opus_path else '' # System detected path
|
|
]
|
|
|
|
opus_loaded = False
|
|
for path in possible_opus_paths:
|
|
if not path:
|
|
continue
|
|
try:
|
|
print(f"Attempting to load opus from: {path}")
|
|
discord.opus.load_opus(path)
|
|
print(f"Successfully loaded opus from {path}")
|
|
opus_loaded = True
|
|
break
|
|
except Exception as e:
|
|
print(f"Failed to load opus from {path}: {str(e)}")
|
|
|
|
if not opus_loaded:
|
|
print("Could not load opus from any location")
|
|
raise RuntimeError('Opus failed to load')
|
|
|
|
# Rest of your code remains the same
|
|
# Load environment variables
|
|
load_dotenv()
|
|
TOKEN = os.getenv('DISCORD_TOKEN')
|
|
|
|
# Suppress noise about console usage from errors
|
|
youtube_dl.utils.bug_reports_message = lambda: ''
|
|
|
|
ytdl_format_options = {
|
|
'format': 'bestaudio/best',
|
|
'outtmpl': '%(extractor)s-%(id)s-%(title)s.%(ext)s',
|
|
'restrictfilenames': True,
|
|
'noplaylist': True,
|
|
'nocheckcertificate': True,
|
|
'ignoreerrors': False,
|
|
'logtostderr': False,
|
|
'quiet': True,
|
|
'no_warnings': True,
|
|
'default_search': 'auto',
|
|
'source_address': '0.0.0.0', # bind to ipv4 since ipv6 addresses cause issues sometimes
|
|
}
|
|
|
|
ffmpeg_options = {
|
|
'options': '-vn',
|
|
'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5'
|
|
}
|
|
|
|
ytdl = youtube_dl.YoutubeDL(ytdl_format_options)
|
|
|
|
|
|
class YTDLSource(discord.PCMVolumeTransformer):
|
|
def __init__(self, source, *, data, volume=0.5):
|
|
super().__init__(source, volume)
|
|
self.data = data
|
|
self.title = data.get('title')
|
|
self.url = data.get('url')
|
|
|
|
@classmethod
|
|
async def from_url(cls, url, *, loop=None, stream=False):
|
|
loop = loop or asyncio.get_event_loop()
|
|
try:
|
|
data = await loop.run_in_executor(None, lambda: ytdl.extract_info(url, download=not stream))
|
|
|
|
if 'entries' in data:
|
|
# Take the first item from a playlist
|
|
data = data['entries'][0]
|
|
|
|
filename = data['url'] if stream else ytdl.prepare_filename(data)
|
|
try:
|
|
return cls(discord.FFmpegPCMAudio(filename, **ffmpeg_options), data=data)
|
|
except Exception as e:
|
|
raise Exception(f"Error creating FFmpeg audio: {str(e)}. Make sure FFmpeg is installed and accessible.")
|
|
|
|
except Exception as e:
|
|
raise Exception(f"Error extracting info from URL: {str(e)}")
|
|
|
|
|
|
class MusicBot(commands.Cog):
|
|
def __init__(self, bot):
|
|
self.bot = bot
|
|
self.queue = []
|
|
self.current = None
|
|
self.volume = 0.5
|
|
|
|
@commands.command(name='join', help='Joins the voice channel')
|
|
async def join(self, ctx):
|
|
if not ctx.message.author.voice:
|
|
await ctx.send("You are not connected to a voice channel")
|
|
return None
|
|
|
|
channel = ctx.message.author.voice.channel
|
|
if ctx.voice_client is not None:
|
|
return await ctx.voice_client.move_to(channel)
|
|
|
|
await channel.connect()
|
|
return None
|
|
|
|
@commands.command(name='play', help='Plays a song from YouTube')
|
|
async def play(self, ctx, *, url):
|
|
if not ctx.message.author.voice:
|
|
await ctx.send("You are not connected to a voice channel")
|
|
return
|
|
|
|
if ctx.voice_client is None:
|
|
await ctx.invoke(self.join)
|
|
|
|
async with ctx.typing():
|
|
try:
|
|
player = await YTDLSource.from_url(url, loop=self.bot.loop, stream=True)
|
|
|
|
if ctx.voice_client.is_playing():
|
|
self.queue.append(player)
|
|
await ctx.send(f"Added to queue: {player.title}")
|
|
else:
|
|
self.current = player
|
|
ctx.voice_client.play(player, after=lambda e: self.play_next(ctx))
|
|
await ctx.send(f"Now playing: {player.title}")
|
|
except Exception as e:
|
|
error_msg = f"An error occurred: {str(e)}\n```{traceback.format_exc()}```"
|
|
print(error_msg) # Print to console for debugging
|
|
await ctx.send(error_msg[:1900]) # Discord has a 2000 character limit
|
|
|
|
def play_next(self, ctx):
|
|
if len(self.queue) > 0:
|
|
self.current = self.queue.pop(0)
|
|
ctx.voice_client.play(self.current, after=lambda e: self.play_next(ctx))
|
|
asyncio.run_coroutine_threadsafe(ctx.send(f"Now playing: {self.current.title}"), self.bot.loop)
|
|
else:
|
|
self.current = None
|
|
asyncio.run_coroutine_threadsafe(ctx.send("Queue is empty"), self.bot.loop)
|
|
|
|
@commands.command(name='queue', help='Shows the current queue')
|
|
async def show_queue(self, ctx):
|
|
if not self.queue:
|
|
await ctx.send("The queue is empty")
|
|
return
|
|
|
|
queue_list = "\n".join([f"{i + 1}. {item.title}" for i, item in enumerate(self.queue)])
|
|
await ctx.send(f"Current queue:\n{queue_list}")
|
|
|
|
@commands.command(name='skip', help='Skips the current song')
|
|
async def skip(self, ctx):
|
|
if ctx.voice_client.is_playing():
|
|
ctx.voice_client.stop()
|
|
await ctx.send("Skipped current song")
|
|
else:
|
|
await ctx.send("Not playing anything")
|
|
|
|
@commands.command(name='pause', help='Pauses the current song')
|
|
async def pause(self, ctx):
|
|
if ctx.voice_client.is_playing():
|
|
ctx.voice_client.pause()
|
|
await ctx.send("Paused")
|
|
else:
|
|
await ctx.send("Not playing anything")
|
|
|
|
@commands.command(name='resume', help='Resumes the current song')
|
|
async def resume(self, ctx):
|
|
if ctx.voice_client.is_paused():
|
|
ctx.voice_client.resume()
|
|
await ctx.send("Resumed")
|
|
else:
|
|
await ctx.send("Not paused")
|
|
|
|
@commands.command(name='stop', help='Stops the bot and clears the queue')
|
|
async def stop(self, ctx):
|
|
if ctx.voice_client.is_playing():
|
|
ctx.voice_client.stop()
|
|
self.queue.clear()
|
|
self.current = None
|
|
await ctx.send("Stopped and cleared queue")
|
|
|
|
@commands.command(name='volume', help='Changes the volume (0-100)')
|
|
async def volume(self, ctx, volume: int):
|
|
if ctx.voice_client is None:
|
|
return await ctx.send("Not connected to a voice channel.")
|
|
|
|
if 0 < volume <= 100:
|
|
self.volume = volume / 100
|
|
ctx.voice_client.source.volume = self.volume
|
|
await ctx.send(f"Changed volume to {volume}%")
|
|
return None
|
|
else:
|
|
await ctx.send("Please enter a value between 1 and 100")
|
|
return None
|
|
|
|
@commands.command(name='nowplaying', help='Shows the currently playing song')
|
|
async def now_playing(self, ctx):
|
|
if self.current:
|
|
await ctx.send(f"Now playing: {self.current.title}")
|
|
else:
|
|
await ctx.send("Nothing is currently playing")
|
|
|
|
@commands.command(name='leave', help='Leaves the voice channel')
|
|
async def leave(self, ctx):
|
|
if ctx.voice_client is not None:
|
|
await ctx.voice_client.disconnect()
|
|
self.queue.clear()
|
|
self.current = None
|
|
await ctx.send("Left the voice channel")
|
|
else:
|
|
await ctx.send("I'm not in a voice channel")
|
|
|
|
@play.before_invoke
|
|
async def ensure_voice(self, ctx):
|
|
if ctx.voice_client is None:
|
|
if ctx.author.voice:
|
|
await ctx.author.voice.channel.connect()
|
|
else:
|
|
await ctx.send("You are not connected to a voice channel.")
|
|
raise commands.CommandError("Author not connected to a voice channel.")
|
|
|
|
|
|
bot = commands.Bot(command_prefix='!', intents=discord.Intents.all())
|
|
|
|
|
|
@bot.event
|
|
async def on_ready():
|
|
print(f'Logged in as {bot.user.name} ({bot.user.id})')
|
|
print('------')
|
|
await bot.add_cog(MusicBot(bot))
|
|
|
|
|
|
bot.run(TOKEN) |