From 3846579818420c1e639cb018d31ad812c2d95a03 Mon Sep 17 00:00:00 2001 From: SamlonDev Date: Sat, 14 Jun 2025 17:47:21 +0200 Subject: temp downloads the files instead --- cogs/downloader.py | 119 ++++++++++++++++++++++++++++------------------------- 1 file changed, 63 insertions(+), 56 deletions(-) diff --git a/cogs/downloader.py b/cogs/downloader.py index b992e82..7f48e57 100644 --- a/cogs/downloader.py +++ b/cogs/downloader.py @@ -5,26 +5,30 @@ from discord.ext import commands import requests import yt_dlp from dotenv import load_dotenv +import tempfile +import os.path # Load environment variables load_dotenv() PIXELDRAIN_API_KEY = os.getenv('PIXELDRAIN_API_KEY') + +def _get_auth_headers(): + """Generate authentication headers for Pixeldrain API""" + if not PIXELDRAIN_API_KEY: + raise Exception("Pixeldrain API key not found in environment variables") + + auth_string = f":{PIXELDRAIN_API_KEY}" + auth_bytes = auth_string.encode('ascii') + base64_auth = base64.b64encode(auth_bytes).decode('ascii') + return {"Authorization": f"Basic {base64_auth}"} + + class Downloader(commands.Cog): def __init__(self, bot): self.bot = bot self.pixeldrain_url = "https://pixeldrain.com/api/file" - - def _get_auth_headers(self): - """Generate authentication headers for Pixeldrain API""" - if not PIXELDRAIN_API_KEY: - raise Exception("Pixeldrain API key not found in environment variables") - - auth_string = f":{PIXELDRAIN_API_KEY}" - auth_bytes = auth_string.encode('ascii') - base64_auth = base64.b64encode(auth_bytes).decode('ascii') - return {"Authorization": f"Basic {base64_auth}"} - + @commands.slash_command( name="download", description="download video from internet", @@ -36,53 +40,56 @@ class Downloader(commands.Cog): ): await ctx.defer() try: - # pass link to yt-dlp - outtmpl = '%(title)s.%(ext)s' - ydl_opts = { - 'outtmpl': outtmpl, - 'merge_output_format': 'mp4', - } - with yt_dlp.YoutubeDL(ydl_opts) as ydl: - info = ydl.extract_info(url, download=True) - actual_filename = ydl.prepare_filename(info) - - await ctx.followup.send("Video downloaded successfully, Uploading to pixeldrain...") - # upload to pixeldrain - try: - with open(actual_filename, 'rb') as f: - files = {'file': f} - response = requests.post( - self.pixeldrain_url, - files=files, - headers={"Authorization": f"Basic {base64.b64encode((':' + PIXELDRAIN_API_KEY).encode()).decode()}"} - ) - - try: - response_data = response.json() - print("Pixeldrain response:", response_data) # Debug log + # Create a temporary directory + with tempfile.TemporaryDirectory() as temp_dir: + # Configure yt-dlp to use the temp directory + outtmpl = os.path.join(temp_dir, '%(title)s.%(ext)s') + ydl_opts = { + 'outtmpl': outtmpl, + 'merge_output_format': 'mp4', + } + + with yt_dlp.YoutubeDL(ydl_opts) as ydl: + info = ydl.extract_info(url, download=True) + actual_filename = ydl.prepare_filename(info) + + await ctx.followup.send("Video downloaded successfully, Uploading to pixeldrain...") + # upload to pixeldrain + try: + with open(actual_filename, 'rb') as f: + files = {'file': f} + response = requests.post( + self.pixeldrain_url, + files=files, + headers={"Authorization": f"Basic {base64.b64encode((':' + PIXELDRAIN_API_KEY).encode()).decode()}"} + ) - if response.status_code == 201: # 201 means successful upload - file_id = response_data.get('id') - if file_id: - file_link = f"https://pixeldrain.com/u/{file_id}" - await ctx.followup.send(f"oto twoje videło\n {file_link}") + try: + response_data = response.json() + print("Pixeldrain response:", response_data) # Debug log + + if response.status_code == 201: # 201 means successful upload + file_id = response_data.get('id') + if file_id: + file_link = f"https://pixeldrain.com/u/{file_id}" + await ctx.followup.send(f"oto twoje videło\n {file_link}") + else: + await ctx.followup.send(f"⚠️ Upload successful but no file ID returned. Response: {response_data}") else: - await ctx.followup.send(f"⚠️ Upload successful but no file ID returned. Response: {response_data}") - else: - error_msg = response_data.get('error', 'Unknown error') - if response.status_code == 401: - error_msg = "Invalid API key. Please check your PIXELDRAIN_API_KEY in .env file." - await ctx.followup.send(f"❌ Upload failed (Status {response.status_code}): {error_msg}") - except ValueError as e: - # If response is not JSON - error_msg = f"Failed to parse server response: {str(e)}" - if response.text: - error_msg += f"\nResponse: {response.text[:200]}" - await ctx.followup.send(f"❌ {error_msg}") - finally: - # Clean up the downloaded file - if os.path.exists(actual_filename): - os.remove(actual_filename) + error_msg = response_data.get('error', 'Unknown error') + if response.status_code == 401: + error_msg = "Invalid API key. Please check your PIXELDRAIN_API_KEY in .env file." + await ctx.followup.send(f"❌ Upload failed (Status {response.status_code}): {error_msg}") + except ValueError as e: + # If response is not JSON + error_msg = f"Failed to parse server response: {str(e)}" + if response.text: + error_msg += f"\nResponse: {response.text[:200]}" + await ctx.followup.send(f"❌ {error_msg}") + except Exception as e: + await ctx.followup.send(f"Error: {str(e)}") + # No need for explicit cleanup as tempfile.TemporaryDirectory handles it automatically + except Exception as e: await ctx.followup.send(f"Error: {str(e)}") -- cgit v1.2.3