diff options
| author | Samlon <stankiewiczgracjan2019@gmail.com> | 2025-08-21 12:21:53 +0200 |
|---|---|---|
| committer | Samlon <stankiewiczgracjan2019@gmail.com> | 2025-08-21 12:21:53 +0200 |
| commit | 47180d6ffe94ca97576476d7b635f393de0293e0 (patch) | |
| tree | e2a835b806c5a46034464974c647391ea02d4f51 /cogs/music/play_utils.py | |
| parent | play.py fixing (diff) | |
| download | senator-sperma-47180d6ffe94ca97576476d7b635f393de0293e0.tar.gz senator-sperma-47180d6ffe94ca97576476d7b635f393de0293e0.zip | |
play.py rework
Diffstat (limited to 'cogs/music/play_utils.py')
| -rw-r--r-- | cogs/music/play_utils.py | 117 |
1 files changed, 117 insertions, 0 deletions
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 @@ | |||
| 1 | import logging | ||
| 2 | from youtubesearchpython import VideosSearch | ||
| 3 | import yt_dlp | ||
| 4 | import discord | ||
| 5 | import asyncio | ||
| 6 | import os | ||
| 7 | |||
| 8 | logger = logging.getLogger(__name__) | ||
| 9 | |||
| 10 | class PlayUtils: | ||
| 11 | def __init__(self, bot): | ||
| 12 | self.bot = bot | ||
| 13 | |||
| 14 | async def download(self, ctx, url): | ||
| 15 | |||
| 16 | # Create temp directory if it doesn't exist | ||
| 17 | temp_dir = os.path.join('cogs', 'temp', 'music') | ||
| 18 | os.makedirs(temp_dir, exist_ok=True) | ||
| 19 | |||
| 20 | ytdl_opts = { | ||
| 21 | "format": "bestaudio/best", | ||
| 22 | "outtmpl": os.path.join(temp_dir, "%(title)s.%(ext)s"), | ||
| 23 | "postprocessors": [ | ||
| 24 | { | ||
| 25 | "key": "FFmpegExtractAudio", | ||
| 26 | "preferredcodec": "mp3", | ||
| 27 | "preferredquality": "192", | ||
| 28 | } | ||
| 29 | ], | ||
| 30 | } | ||
| 31 | |||
| 32 | try: | ||
| 33 | with yt_dlp.YoutubeDL(ytdl_opts) as ydl: | ||
| 34 | info_dict = ydl.extract_info(url, download=True) | ||
| 35 | # Get the base filename without extension | ||
| 36 | base_filename = os.path.splitext(ydl.prepare_filename(info_dict))[0] | ||
| 37 | # Add .mp3 extension since we're extracting audio | ||
| 38 | filename = f"{base_filename}.mp3" | ||
| 39 | logger.info(f"Downloaded file: {filename}") | ||
| 40 | return filename | ||
| 41 | except Exception as e: | ||
| 42 | logger.error(f"Error downloading video: {e}") | ||
| 43 | await ctx.respond("eror pobirajync wideło", ephemeral=True) | ||
| 44 | |||
| 45 | async def get_url(self, ctx, query): | ||
| 46 | search = VideosSearch(query, limit=1) | ||
| 47 | if search.result()["result"]: | ||
| 48 | title = search.result()["result"][0]["title"] | ||
| 49 | url = search.result()["result"][0]["link"] | ||
| 50 | logger.info(f"Found video: {title}") | ||
| 51 | return url, title | ||
| 52 | else: | ||
| 53 | logger.warning("No results found for the query.") | ||
| 54 | await ctx.respond("nic ni ma", ephemeral=True) | ||
| 55 | return None | ||
| 56 | |||
| 57 | async def compress(self, ctx, filename): | ||
| 58 | if not filename: | ||
| 59 | await ctx.respond("dzie wideło", ephemeral=True) | ||
| 60 | return | ||
| 61 | |||
| 62 | ffmpeg_command = f"ffmpeg -i {filename} -ac 1 -b:a 500 -acodec libopus {filename}" | ||
| 63 | try: | ||
| 64 | process = await asyncio.create_subprocess_shell( | ||
| 65 | ffmpeg_command, | ||
| 66 | stdout=asyncio.subprocess.PIPE, | ||
| 67 | stderr=asyncio.subprocess.PIPE | ||
| 68 | ) | ||
| 69 | stdout, stderr = await process.communicate() | ||
| 70 | if process.returncode != 0: | ||
| 71 | logger.error(f"FFmpeg error: {stderr.decode()}") | ||
| 72 | await ctx.respond("eror kompresujync pilk", ephemeral=True) | ||
| 73 | else: | ||
| 74 | logger.info(f"Compressed file: {filename}") | ||
| 75 | except Exception as e: | ||
| 76 | logger.error(f"Error compressing file: {e}") | ||
| 77 | await ctx.respond("eror kompresujync pilk", ephemeral=True) | ||
| 78 | |||
| 79 | async def play(self, ctx, filename, title): | ||
| 80 | # Check if user is in a voice channel | ||
| 81 | if not ctx.author.voice or not ctx.author.voice.channel: | ||
| 82 | await ctx.respond("Musisz być na kanale głosowym, żebym mógł dołączyć!", ephemeral=True) | ||
| 83 | return | ||
| 84 | |||
| 85 | # Get or create voice client | ||
| 86 | vc = ctx.voice_client | ||
| 87 | target_channel = ctx.author.voice.channel | ||
| 88 | |||
| 89 | try: | ||
| 90 | # Connect to voice channel if not connected | ||
| 91 | if vc is None: | ||
| 92 | vc = await target_channel.connect() | ||
| 93 | logger.info(f"Connected to voice channel: {target_channel.name}") | ||
| 94 | # Move to user's channel if in a different one | ||
| 95 | elif vc.channel != target_channel: | ||
| 96 | await vc.move_to(target_channel) | ||
| 97 | logger.info(f"Moved to voice channel: {target_channel.name}") | ||
| 98 | |||
| 99 | if not filename or not os.path.exists(filename): | ||
| 100 | await ctx.respond("Nie znaleziono pliku do odtworzenia", ephemeral=True) | ||
| 101 | logger.warning(f"No file to play, filename: {filename}") | ||
| 102 | return | ||
| 103 | |||
| 104 | # Stop any currently playing audio | ||
| 105 | if vc.is_playing() or vc.is_paused(): | ||
| 106 | vc.stop() | ||
| 107 | |||
| 108 | # Play the audio | ||
| 109 | source = discord.FFmpegPCMAudio(source=filename) | ||
| 110 | await vc.play(source) | ||
| 111 | |||
| 112 | logger.info(f"Playing file: {title}") | ||
| 113 | await ctx.respond(f"grom: {title}") | ||
| 114 | |||
| 115 | except Exception as e: | ||
| 116 | logger.error(f"Error in play: {str(e)}", exc_info=True) | ||
| 117 | await ctx.respond(f"eror: {str(e)}", ephemeral=True) \ No newline at end of file | ||
