import discord import yt_dlp voice_clients = {} # Track active voice connections async def join_voice(interaction: discord.Interaction): if interaction.user.voice is None or interaction.user.voice.channel is None: await interaction.response.send_message("You must be in a voice channel to use this command.", ephemeral=True) return channel = interaction.user.voice.channel if interaction.guild.id in voice_clients: await interaction.response.send_message("Amber is already in a voice channel.") else: voice_client = await channel.connect() voice_clients[interaction.guild.id] = voice_client await interaction.response.send_message(f"Amber joined {channel.name}!") async def leave_voice(interaction: discord.Interaction): guild_id = interaction.guild.id if guild_id not in voice_clients: await interaction.response.send_message("Amber is not connected to a voice channel.") return voice_client = voice_clients[guild_id] await voice_client.disconnect() voice_clients.pop(guild_id, None) await interaction.response.send_message("Amber has left the voice channel.") async def play_audio(interaction: discord.Interaction, query: str): guild_id = interaction.guild.id if guild_id not in voice_clients: await interaction.response.send_message("Amber is not connected to a voice channel.") return voice_client = voice_clients[guild_id] if not voice_client.is_connected(): await interaction.response.send_message("Amber is not in a voice channel.") return await interaction.response.defer() # Indicate the bot is processing the request # yt-dlp options ydl_opts = { 'format': 'bestaudio/best', 'quiet': True, } # Search for the query on YouTube with yt_dlp.YoutubeDL(ydl_opts) as ydl: try: info = ydl.extract_info(f"ytsearch:{query}", download=False)['entries'][0] except Exception as e: await interaction.followup.send(f"Failed to find or play the requested audio. Error: {str(e)}") return # Extract the audio URL and metadata url2 = info['url'] title = info.get('title', 'Unknown Title') # Stop any existing audio and play the new one voice_client.stop() ffmpeg_options = { 'options': '-vn', } voice_client.play(discord.FFmpegPCMAudio(url2, **ffmpeg_options)) await interaction.followup.send(f"Now playing: {title}")