From 47180d6ffe94ca97576476d7b635f393de0293e0 Mon Sep 17 00:00:00 2001 From: Samlon Date: Thu, 21 Aug 2025 12:21:53 +0200 Subject: play.py rework --- cogs/music/play.py | 89 +++++++------------------------- cogs/music/play_compressed.py | 101 ------------------------------------ cogs/music/play_utils.py | 117 ++++++++++++++++++++++++++++++++++++++++++ main.py | 1 - 4 files changed, 135 insertions(+), 173 deletions(-) delete mode 100644 cogs/music/play_compressed.py create mode 100644 cogs/music/play_utils.py diff --git a/cogs/music/play.py b/cogs/music/play.py index f18afa8..7066ae8 100644 --- a/cogs/music/play.py +++ b/cogs/music/play.py @@ -1,83 +1,30 @@ -import logging import discord -import yt_dlp +from . import play_utils from discord.ext import commands -from youtubesearchpython import VideosSearch +import logging logger = logging.getLogger(__name__) -# Suppress noise about console usage from yt-dlp -yt_dlp.utils.bug_reports_message = lambda: '' - - class Play(commands.Cog): def __init__(self, bot): self.bot = bot - self.ydl_opts = { - 'extract_audio': True, - 'noplaylist': True, - 'quiet': True, - 'default_search': 'auto', - } - - async def play_audio(self, ctx, vc, url, title): - try: - with yt_dlp.YoutubeDL(self.ydl_opts) as ydl: - info = await self.bot.loop.run_in_executor( - None, - lambda: ydl.extract_info(url, download=False) - ) - if 'entries' in info: - info = info['entries'][0] - url2 = info['url'] - - ffmpeg_options = { - 'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5', - 'options': '-vn' - } - - source = discord.FFmpegPCMAudio(url2, **ffmpeg_options) - vc.play(source) - await ctx.followup.send(f"gra: {title}") - logger.info(f"Playing: {title}") - except Exception as e: - await ctx.followup.send(f"Wystąpił błąd podczas odtwarzania: {str(e)}") - logger.error(f"Error playing audio: {e}", exc_info=True) - - @commands.slash_command(name="grajcuj", description="grajcuj melodyje") - async def play(self, ctx, *, search: str): + @discord.slash_command(name="grajcuj", description="grajcujmy wszyscy!") + async def play(self, ctx: discord.ApplicationContext, query: str = discord.Option(str, "co zagrać??", required=True)): await ctx.defer() - - if not (ctx.author.voice and ctx.author.voice.channel): - await ctx.followup.send("nie jesteś w kanale głosowym") - logger.info("User is not in a voice channel") - return - - channel = ctx.author.voice.channel - vc = ctx.voice_client or await channel.connect() - - if vc.channel != channel: - await vc.move_to(channel) - - # Search for the video - videos_search = VideosSearch(search, limit=1) - result = videos_search.result() - - if not result['result']: - await ctx.followup.send("nie znaleziono wideo dla twojego wyszukiwania.", ephemeral=True) - logger.info(f"Could not find a video for search: {search}") - return - - video = result['result'][0] - title = video['title'] - url = video['link'] - - # Play the audio directly - if vc.is_playing() or vc.is_paused(): - vc.stop() - await self.play_audio(ctx, vc, url, title) - + url, title = await play_utils.PlayUtils(self.bot).get_url(ctx, query) + logger.info(f"Found video: {title}") + filename = await play_utils.PlayUtils(self.bot).download(ctx, url) + logger.info(f"Downloaded file: {filename}") + await play_utils.PlayUtils(self.bot).play(ctx, filename, title) + + @discord.slash_command(name="grajcuj_zkompresowane", description="grajcujmy wszyscy w wysokiej jakosci!") + async def play_compressed(self, ctx: discord.ApplicationContext, url: str = discord.Option(str, "co zagrać??", required=True)): + await ctx.defer() + url, title = await play_utils.PlayUtils(self.bot).get_url(ctx, url) + filename = await play_utils.PlayUtils(self.bot).download(ctx, url) + filename = await play_utils.PlayUtils(self.bot).compress(ctx, filename) + await play_utils.PlayUtils(self.bot).play(ctx, filename, title) def setup(bot): - bot.add_cog(Play(bot)) + bot.add_cog(Play(bot)) \ No newline at end of file diff --git a/cogs/music/play_compressed.py b/cogs/music/play_compressed.py deleted file mode 100644 index 2bae269..0000000 --- a/cogs/music/play_compressed.py +++ /dev/null @@ -1,101 +0,0 @@ -import asyncio -import logging -import os -import subprocess - -import discord -from discord.ext import commands -from youtubesearchpython import VideosSearch - -logger = logging.getLogger(__name__) - - -class GrajcujZkompresowane(commands.Cog): - def __init__(self, bot): - self.bot = bot - - @staticmethod - def prepend_title_to_file(file_path, title): - try: - with open(file_path, 'rb') as original: - data = original.read() - with open(file_path, 'wb') as modified: - modified.write(f"{title}\n".encode('utf-8')) - modified.write(data) - except Exception as e: - logger.error(f"Failed to prepend title: {e}", exc_info=True) - - @staticmethod - def compress_audio(input_path): - base, ext = os.path.splitext(input_path) - output_path = f"{base}_compressed.opus" - ffmpeg_command = f"ffmpeg -i {input_path} -ac 1 -b:a 500 -acodec libopus {output_path}" - subprocess.run(ffmpeg_command, check=True, shell=True) - logger.info(f"Audio compressed to {output_path}") - return output_path - - @commands.slash_command(name="grajcuj_zkompresowane", description="grajcuj zkompresowane melodyje") - async def grajcuj_zkompresowane(self, ctx, *, search: str): - await ctx.defer() - if not (ctx.author.voice and ctx.author.voice.channel): - await ctx.followup.send("nie jesteś w kanale głosowym") - logger.info("User is not in a voice channel") - return - channel = ctx.author.voice.channel - if ctx.voice_client is not None: - vc = ctx.voice_client - logger.info(f"User is already in a voice channel, moving to new {channel}") - await vc.move_to(channel) - else: - vc = await channel.connect() - bot_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) - music_dir = os.path.join(bot_dir, "temp", "music") - if not os.path.exists(music_dir): - os.makedirs(music_dir) - videos_search = VideosSearch(search, limit=1) - result = videos_search.result() - if not result['result']: - await ctx.followup.send("Could not find a video for your search.", ephemeral=True) - return - video = result['result'][0] - video_id = video['id'] - title = video['title'] - url = video['link'] - filename = f"{video_id}.mp3" - file_path = os.path.join(music_dir, filename) - compressed_file_path = os.path.join(music_dir, f"{video_id}_compressed.opus") - if os.path.exists(compressed_file_path): - found_file = compressed_file_path - found_title = title - else: - if not os.path.exists(file_path): - cmd = [ - "yt-dlp", - "-x", - "--audio-format", "mp3", - "-o", file_path, - url - ] - process = await asyncio.create_subprocess_exec(*cmd) - await process.communicate() - self.prepend_title_to_file(file_path, title) - if not os.path.exists(compressed_file_path): - try: - compressed_file_path = self.compress_audio(file_path) - except subprocess.CalledProcessError as e: - await ctx.followup.send(f"skompresowanie nie powiodło się: {str(e)}", ephemeral=True) - logger.error(f"Failed to compress audio: {e}", exc_info=True) - return - found_file = compressed_file_path - found_title = title - title = found_title - - if vc.is_playing() or vc.is_paused(): - vc.stop() - vc.play(discord.FFmpegPCMAudio(found_file)) - await ctx.followup.send(f"gra (zkompresowane): {title}") - logger.info(f"Playing audio: {title}") - - -def setup(bot): - bot.add_cog(GrajcujZkompresowane(bot)) diff --git a/cogs/music/play_utils.py b/cogs/music/play_utils.py new file mode 100644 index 0000000..1e46594 --- /dev/null +++ b/cogs/music/play_utils.py @@ -0,0 +1,117 @@ +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 = { + "format": "bestaudio/best", + "outtmpl": os.path.join(temp_dir, "%(title)s.%(ext)s"), + "postprocessors": [ + { + "key": "FFmpegExtractAudio", + "preferredcodec": "mp3", + "preferredquality": "192", + } + ], + } + + 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) + await 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) \ No newline at end of file diff --git a/main.py b/main.py index b75f212..81c9bdb 100644 --- a/main.py +++ b/main.py @@ -40,7 +40,6 @@ if __name__ == "__main__": 'cogs.math_cog', 'cogs.downloader', 'cogs.music.play', - 'cogs.music.play_compressed', 'cogs.music.stop', 'cogs.music.join', ] -- cgit v1.2.3