From 51fcdc490d3e731adca3566cb2f9ee45b28c729f Mon Sep 17 00:00:00 2001 From: Samlon Date: Mon, 1 Sep 2025 16:55:09 +0200 Subject: add context commands --- cogs/compression.py | 11 +++++ cogs/downloader.py | 129 ++++++++++++++++++++++++++++++---------------------- 2 files changed, 86 insertions(+), 54 deletions(-) (limited to 'cogs') diff --git a/cogs/compression.py b/cogs/compression.py index 2ee36bb..db47d46 100644 --- a/cogs/compression.py +++ b/cogs/compression.py @@ -24,6 +24,17 @@ class Compression(commands.Cog): def __init__(self, bot): self.bot = bot + @commands.message_command( + name="kompresja", + description="skompresuj wideło albo dźwienk :)", + ) + async def message_compression(self, ctx, message: discord.Message): + if message.attachments: + for attachment in message.attachments: + await self.compression(ctx, attachment) + else: + await ctx.respond("Brak załączników w wiadomości", ephemeral=True) + @commands.slash_command( name="kompresja", description="skompresuj wideło albo dźwienk :)", diff --git a/cogs/downloader.py b/cogs/downloader.py index e678575..251a9af 100644 --- a/cogs/downloader.py +++ b/cogs/downloader.py @@ -3,6 +3,7 @@ import tempfile import logging import requests import discord +import re import yt_dlp from discord.ext import commands from dotenv import load_dotenv @@ -17,6 +18,23 @@ class Downloader(commands.Cog): def __init__(self, bot): self.bot = bot + URL_PATTERN = re.compile( + r'https://(?:[A-Za-z0-9-]+\.)*[A-Za-z0-9-]{1,63}\.[A-Za-z]{2,63}/\S*' + ) + + @commands.message_command( + name="download", + description="Download and convert video/audio from internet" + ) + async def message_download(self, ctx, message: discord.Message): + # check if message has a valid url + url = [m.group(0) for m in self.URL_PATTERN.finditer(message.content)] + if url: + for url in url: + await self.download(ctx, url, "mp4") + else: + await ctx.respond("Brak załączników w wiadomości", ephemeral=True) + @commands.slash_command( name="download", description="Download and convert video/audio from internet" @@ -35,13 +53,9 @@ class Downloader(commands.Cog): logger.info(f"Downloading {url} as {fformat}") with tempfile.TemporaryDirectory() as temp_dir: - base_filename = os.path.join(temp_dir, 'output') - input_file = f"{base_filename}.%(ext)s" - output_file = f"{base_filename}.{fformat}" - - # Configure yt-dlp + # Configure yt-dlp to use the original filename ydl_opts = { - 'outtmpl': input_file, + 'outtmpl': os.path.join(temp_dir, '%(title)s.%(ext)s'), 'format': 'bestaudio/best' if fformat in ['mp3', 'wav', 'm4a'] else 'bestvideo[ext=mp4]+bestaudio[ext=m4a]/best[ext=mp4]/best', 'merge_output_format': 'mp4', 'postprocessors': [], @@ -63,57 +77,64 @@ class Downloader(commands.Cog): with yt_dlp.YoutubeDL(ydl_opts) as ydl: ydl.download([url]) - # Find the downloaded file (yt-dlp might add a number if filename exists) - actual_file = None - for file in os.listdir(temp_dir): - if file.startswith('output') and file.endswith(fformat): - actual_file = os.path.join(temp_dir, file) - break - - if not actual_file or not os.path.exists(actual_file): - raise Exception(f"{fformat} ze mno wygroł...") + # Find the downloaded file (should be the only file in the temp directory) + files = [f for f in os.listdir(temp_dir) if os.path.isfile(os.path.join(temp_dir, f))] + if not files: + raise Exception(f"No file was downloaded") + + actual_file = os.path.join(temp_dir, files[0]) + if not os.path.exists(actual_file): + raise Exception(f"Downloaded file not found: {actual_file}") - # Check file size and handle accordingly - file_size = os.path.getsize(actual_file) - if file_size < 10 * 1024 * 1024: # Under 10MB - file = discord.File(actual_file, filename=f"output.{fformat}") - await ctx.followup.send("pobran", file=file) - else: # 10MB or larger - upload to Pixeldrain - try: - # Get file info - filename = f"output.{fformat}" - file_size_mb = file_size / (1024 * 1024) - - # Upload to Litterbox Catbox - with open(actual_file, 'rb') as f: - files = { - 'reqtype': (None, 'fileupload'), - 'time': (None, '24h'), - 'fileToUpload': (filename, f, 'application/octet-stream') - } - - await ctx.followup.send(f"plik jest {file_size_mb:.1f} megabajtów... wysyłanie do gorzowa...") - - response = requests.post( - 'https://litterbox.catbox.moe/resources/internals/api.php', - files=files - ) + try: + # Get file info + filename = f"output.{fformat}" + + # Upload to Copyparty + with open(actual_file, 'rb') as f: + files = { + 'f': (filename, f, 'application/octet-stream') + } + headers = { + 'Cookie': f'cppwd={os.getenv("COPYPARTY_PASSWORD")}' + } + params = { + 'j': '1', # Return JSON response + 'ck': 'b2' # Use blake2b checksum + } + + # Ensure the URL ends with a single slash + base_url = "https://catbox.2137697.xyz/sperma/" - if response.status_code == 200 and response.text.startswith('http'): - dl_url = response.text.strip() - await ctx.followup.send( - f"wysyłon\n" - f"pobrań: {dl_url}\n" - ) - else: - error_msg = response.text if response.text else 'Unknown error' - await ctx.followup.send(f"nie udało się wysłać pliku: {error_msg}") - - except Exception as upload_error: - await ctx.followup.send(f"litterbox mnie nienawidzi :cccc\n {str(upload_error)}") - logger.error(f"litterbox upload error: {upload_error}", exc_info=True) + response = requests.post( + base_url, + files=files, + headers=headers, + params=params + ) + + if response.status_code == 200 or response.status_code == 201: + try: + result = response.json() + if 'fileurl' in result: + dl_url = result['fileurl'] + await ctx.followup.send( + f"wysyłon\n" + f"{dl_url}\n" + ) + else: + await ctx.followup.send(f"Odpowiedź serwera nie zawiera wymaganych danych: {result}") + except ValueError: + await ctx.followup.send(f"Nieprawidłowa odpowiedź z serwera: {response.text}") + else: + error_msg = response.text if response.text else 'Unknown error' + await ctx.followup.send(f"nie udało się wysłać pliku (HTTP {response.status_code}): {error_msg}") + + except Exception as upload_error: + await ctx.followup.send(f"copyparty mnie nienawidzi :cccc\n {str(upload_error)}") + logger.error(f"copyparty upload error: {upload_error}", exc_info=True) - logger.info(f"File processed: {actual_file} ({file_size} bytes)") + logger.info(f"File processed: {actual_file}") except Exception as e: await ctx.followup.send(f":(\n{str(e)}") -- cgit v1.2.3