import logging from youtubesearchpython import VideosSearch import yt_dlp import discord import asyncio import os logger = logging.getLogger(__name__) class PlayUtils: def __init__(self, bot): self.bot = bot async def download(self, ctx, url): # Create temp directory if it doesn't exist temp_dir = os.path.join('cogs', 'temp', 'music') os.makedirs(temp_dir, exist_ok=True) ytdl_opts = { "outtmpl": os.path.join(temp_dir, "%(title)s.%(ext)s"), "postprocessors": [ { "key": "FFmpegExtractAudio", "preferredcodec": "mp3", "preferredquality": "192", } ], "force_ipv4": True, } try: with yt_dlp.YoutubeDL(ytdl_opts) as ydl: info_dict = ydl.extract_info(url, download=True) # Get the base filename without extension base_filename = os.path.splitext(ydl.prepare_filename(info_dict))[0] # Add .mp3 extension since we're extracting audio filename = f"{base_filename}.mp3" logger.info(f"Downloaded file: {filename}") return filename except Exception as e: logger.error(f"Error downloading video: {e}") await ctx.respond("eror pobirajync wideło", ephemeral=True) async def get_url(self, ctx, query): search = VideosSearch(query, limit=1) if search.result()["result"]: title = search.result()["result"][0]["title"] url = search.result()["result"][0]["link"] logger.info(f"Found video: {title}") return url, title else: logger.warning("No results found for the query.") await ctx.respond("nic ni ma", ephemeral=True) return None async def compress(self, ctx, filename): if not filename: await ctx.respond("dzie wideło", ephemeral=True) return ffmpeg_command = f"ffmpeg -i {filename} -ac 1 -b:a 500 -acodec libopus {filename}" try: process = await asyncio.create_subprocess_shell( ffmpeg_command, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE ) stdout, stderr = await process.communicate() if process.returncode != 0: logger.error(f"FFmpeg error: {stderr.decode()}") await ctx.respond("eror kompresujync pilk", ephemeral=True) else: logger.info(f"Compressed file: {filename}") except Exception as e: logger.error(f"Error compressing file: {e}") await ctx.respond("eror kompresujync pilk", ephemeral=True) async def play(self, ctx, filename, title): # Check if user is in a voice channel if not ctx.author.voice or not ctx.author.voice.channel: await ctx.respond("Musisz być na kanale głosowym, żebym mógł dołączyć!", ephemeral=True) return # Get or create voice client vc = ctx.voice_client target_channel = ctx.author.voice.channel try: # Connect to voice channel if not connected if vc is None: vc = await target_channel.connect() logger.info(f"Connected to voice channel: {target_channel.name}") # Move to user's channel if in a different one elif vc.channel != target_channel: await vc.move_to(target_channel) logger.info(f"Moved to voice channel: {target_channel.name}") if not filename or not os.path.exists(filename): await ctx.respond("Nie znaleziono pliku do odtworzenia", ephemeral=True) logger.warning(f"No file to play, filename: {filename}") return # Stop any currently playing audio if vc.is_playing() or vc.is_paused(): vc.stop() # Play the audio source = discord.FFmpegPCMAudio(source=filename) vc.play(source) logger.info(f"Playing file: {title}") await ctx.respond(f"grom: {title}") except Exception as e: logger.error(f"Error in play: {str(e)}", exc_info=True) await ctx.respond(f"eror: {str(e)}", ephemeral=True)