From 811e2cc7414eb78bb2bf964f986846f1f35e8748 Mon Sep 17 00:00:00 2001 From: Samlon Date: Wed, 20 Aug 2025 20:11:34 +0200 Subject: improved downloader.py --- cogs/downloader.py | 101 +++++++++++++++++++++++++++++++++++++++++++---------- cogs/math.py | 29 --------------- cogs/math_cog.py | 29 +++++++++++++++ main.py | 2 +- 4 files changed, 113 insertions(+), 48 deletions(-) delete mode 100644 cogs/math.py create mode 100644 cogs/math_cog.py diff --git a/cogs/downloader.py b/cogs/downloader.py index 7b338e9..e678575 100644 --- a/cogs/downloader.py +++ b/cogs/downloader.py @@ -1,7 +1,7 @@ import os import tempfile import logging - +import requests import discord import yt_dlp from discord.ext import commands @@ -19,37 +19,102 @@ class Downloader(commands.Cog): @commands.slash_command( name="download", - description="download video from internet", + description="Download and convert video/audio from internet" ) async def download( self, ctx: discord.ApplicationContext, - url: discord.Option(str, "url", required=True) + url: discord.Option(str, "URL of the video to download", required=True), + fformat: discord.Option(str, "Output format (mp4, mp3, wav, etc.)", + required=False, + default="mp4") ): + """Download and convert media from a URL to the specified format""" await ctx.defer() try: - logger.info(f"Downloading {url}") - # Create a temporary directory + logger.info(f"Downloading {url} as {fformat}") + with tempfile.TemporaryDirectory() as temp_dir: - # Configure yt-dlp to use the temp directory - outtmpl = os.path.join(temp_dir, '%(title)s.%(ext)s') + base_filename = os.path.join(temp_dir, 'output') + input_file = f"{base_filename}.%(ext)s" + output_file = f"{base_filename}.{fformat}" + + # Configure yt-dlp ydl_opts = { - 'outtmpl': outtmpl, + 'outtmpl': input_file, + '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': [], } + + # Add post-processing for audio formats + if fformat in ['mp3', 'wav', 'm4a']: + ydl_opts['postprocessors'].append({ + 'key': 'FFmpegExtractAudio', + 'preferredcodec': fformat, + 'preferredquality': '192', + }) + elif fformat != 'mp4': # For other video formats + ydl_opts['postprocessors'].append({ + 'key': 'FFmpegVideoConvertor', + 'preferedformat': fformat, + }) with yt_dlp.YoutubeDL(ydl_opts) as ydl: - info = ydl.extract_info(url, download=True) - actual_filename = ydl.prepare_filename(info) - - try: - file = discord.File(actual_filename) - await ctx.followup.send("Pobran", file=file) - logger.info(f"File downloaded: {actual_filename}") - except Exception as e: - await ctx.followup.send(f":(\n{str(e)}") - logger.error(f"Error in download command: {e}", exc_info=True) + 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ł...") + # 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 + ) + + 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) + + logger.info(f"File processed: {actual_file} ({file_size} bytes)") + except Exception as e: await ctx.followup.send(f":(\n{str(e)}") logger.error(f"Error in download command: {e}", exc_info=True) diff --git a/cogs/math.py b/cogs/math.py deleted file mode 100644 index 8a2644c..0000000 --- a/cogs/math.py +++ /dev/null @@ -1,29 +0,0 @@ -import logging -import subprocess - -from discord import ApplicationContext -from discord.ext import commands - -logger = logging.getLogger(__name__) - - -class Math(commands.Cog): - def __init__(self, bot): - self.bot = bot - - @commands.slash_command( - name="math", - description="wrug szyskih matfisuf" - ) - async def math(self, ctx: ApplicationContext, equation: str): - try: - math = subprocess.check_output(f"qalc -e '{equation}'", shell=True) - await ctx.respond(f"{equation} = {math.decode('utf-8').strip()}") - logger.info(f"Math command executed: {equation}") - except Exception as e: - await ctx.respond(e, ephemeral=True) - logger.error(f"Error in math command: {e}", exc_info=True) - - -def setup(bot): - bot.add_cog(Math(bot)) diff --git a/cogs/math_cog.py b/cogs/math_cog.py new file mode 100644 index 0000000..8a2644c --- /dev/null +++ b/cogs/math_cog.py @@ -0,0 +1,29 @@ +import logging +import subprocess + +from discord import ApplicationContext +from discord.ext import commands + +logger = logging.getLogger(__name__) + + +class Math(commands.Cog): + def __init__(self, bot): + self.bot = bot + + @commands.slash_command( + name="math", + description="wrug szyskih matfisuf" + ) + async def math(self, ctx: ApplicationContext, equation: str): + try: + math = subprocess.check_output(f"qalc -e '{equation}'", shell=True) + await ctx.respond(f"{equation} = {math.decode('utf-8').strip()}") + logger.info(f"Math command executed: {equation}") + except Exception as e: + await ctx.respond(e, ephemeral=True) + logger.error(f"Error in math command: {e}", exc_info=True) + + +def setup(bot): + bot.add_cog(Math(bot)) diff --git a/main.py b/main.py index 6ff471d..b75f212 100644 --- a/main.py +++ b/main.py @@ -37,7 +37,7 @@ if __name__ == "__main__": 'cogs.tts', 'cogs.web', 'cogs.ai', - 'cogs.math', + 'cogs.math_cog', 'cogs.downloader', 'cogs.music.play', 'cogs.music.play_compressed', -- cgit v1.2.3