I’m working on a Discord bot with music functionality. The bot can connect to voice channels properly, but it won’t actually play any audio when I give it YouTube URLs. Here’s my current implementation:
import asyncio
import discord
import youtube_dl
from discord.ext import commands
class AudioBot(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.currently_playing = False
self.paused_state = False
self.song_queue = []
self.YTDL_CONFIG = {'format': 'bestaudio/best', 'verbose': True}
self.FFMPEG_CONFIG = {'options': '-vn'}
self.voice_client = None
self.downloader = youtube_dl.YoutubeDL(self.YTDL_CONFIG)
async def start_playback(self, context):
if self.song_queue:
self.currently_playing = True
audio_url = self.song_queue.pop(0)
self.voice_client.play(discord.FFmpegPCMAudio(audio_url, **self.FFMPEG_CONFIG), after=lambda e: self.next_track(context))
async def next_track(self, context):
if self.song_queue:
audio_url = self.song_queue.pop(0)
self.voice_client.play(discord.FFmpegPCMAudio(audio_url, **self.FFMPEG_CONFIG), after=lambda e: self.next_track(context))
else:
self.currently_playing = False
asyncio.run_coroutine_threadsafe(self.voice_client.disconnect(), self.bot.loop)
@commands.command(name='music', aliases=['song', 'audio'])
async def music_command(self, ctx, *, link=None):
try:
if not ctx.author.voice:
error_msg = discord.Embed(
title='Connection Error',
description=f'{ctx.author.mention}, you need to be in a voice channel first.',
color=discord.Color.red()
)
await ctx.send(embed=error_msg)
return
if not link:
error_msg = discord.Embed(
title='Missing URL',
description=f'{ctx.author.mention}, please include a YouTube link.',
color=discord.Color.red()
)
await ctx.send(embed=error_msg)
return
user_channel = ctx.author.voice.channel
if self.voice_client is None or not self.voice_client.is_connected():
self.voice_client = await user_channel.connect()
else:
await self.voice_client.move_to(user_channel)
track_data = self.downloader.extract_info(link, download=False)
stream_url = track_data['formats'][0]['url']
track_name = track_data['title']
self.song_queue.append(stream_url)
if not self.currently_playing:
await self.start_playback(ctx)
success_msg = discord.Embed(
title='Now Playing',
description=f'🎵 Track: {track_name}\n🎤 Requested by: {ctx.author.mention}',
color=discord.Color.green()
)
await ctx.send(embed=success_msg)
except Exception as error:
print(f'Music command failed: {error}')
async def setup(bot):
await bot.add_cog(AudioBot(bot))
When I run the command, I get this error message:
ERROR: Unable to extract uploader id; please report this issue on https://yt-dl.org/bug
youtube_dl.utils.RegexNotFoundError: Unable to extract uploader id
The bot connects to the voice channel fine, but the audio never starts playing. I tried adding verbose logging and looking into ffmpeg path configuration but nothing worked. Any ideas on how to fix this YouTube extraction issue?