aboutsummaryrefslogtreecommitdiffstats
path: root/cogs/downloader.py
diff options
context:
space:
mode:
authorsalmonik <raisersoft@proton.me>2025-10-08 18:34:08 +0200
committersalmonik <raisersoft@proton.me>2025-10-08 18:34:08 +0200
commitc53afdeb167ec647a2ef840bcfc1b6127591707d (patch)
treeeea3afbbf3db584e47a18c6fbaa0e35c91a7a93f /cogs/downloader.py
parentfixed file overwrite (diff)
downloadsenator-sperma-c53afdeb167ec647a2ef840bcfc1b6127591707d.tar.gz
senator-sperma-c53afdeb167ec647a2ef840bcfc1b6127591707d.zip
send to discord if size is sufficient for downloader.py
Diffstat (limited to 'cogs/downloader.py')
-rw-r--r--cogs/downloader.py121
1 files changed, 64 insertions, 57 deletions
diff --git a/cogs/downloader.py b/cogs/downloader.py
index 251a9af..535615d 100644
--- a/cogs/downloader.py
+++ b/cogs/downloader.py
@@ -43,24 +43,25 @@ class Downloader(commands.Cog):
43 self, 43 self,
44 ctx: discord.ApplicationContext, 44 ctx: discord.ApplicationContext,
45 url: discord.Option(str, "URL of the video to download", required=True), 45 url: discord.Option(str, "URL of the video to download", required=True),
46 fformat: discord.Option(str, "Output format (mp4, mp3, wav, etc.)", 46 fformat: discord.Option(str, "Output format (mp4, mp3, wav, etc.)",
47 required=False, 47 required=False,
48 default="mp4") 48 default="mp4")
49 ): 49 ):
50 """Download and convert media from a URL to the specified format""" 50 """Download and convert media from a URL to the specified format"""
51 await ctx.defer() 51 await ctx.defer()
52 try: 52 try:
53 logger.info(f"Downloading {url} as {fformat}") 53 logger.info(f"Downloading {url} as {fformat}")
54 54
55 with tempfile.TemporaryDirectory() as temp_dir: 55 with tempfile.TemporaryDirectory() as temp_dir:
56 # Configure yt-dlp to use the original filename 56 # Configure yt-dlp to use the original filename
57 ydl_opts = { 57 ydl_opts = {
58 'outtmpl': os.path.join(temp_dir, '%(title)s.%(ext)s'), 58 'outtmpl': os.path.join(temp_dir, '%(title)s.%(ext)s'),
59 'format': 'bestaudio/best' if fformat in ['mp3', 'wav', 'm4a'] else 'bestvideo[ext=mp4]+bestaudio[ext=m4a]/best[ext=mp4]/best', 59 'format': 'bestaudio/best' if fformat in ['mp3', 'wav',
60 'm4a'] else 'bestvideo[ext=mp4]+bestaudio[ext=m4a]/best[ext=mp4]/best',
60 'merge_output_format': 'mp4', 61 'merge_output_format': 'mp4',
61 'postprocessors': [], 62 'postprocessors': [],
62 } 63 }
63 64
64 # Add post-processing for audio formats 65 # Add post-processing for audio formats
65 if fformat in ['mp3', 'wav', 'm4a']: 66 if fformat in ['mp3', 'wav', 'm4a']:
66 ydl_opts['postprocessors'].append({ 67 ydl_opts['postprocessors'].append({
@@ -76,66 +77,72 @@ class Downloader(commands.Cog):
76 77
77 with yt_dlp.YoutubeDL(ydl_opts) as ydl: 78 with yt_dlp.YoutubeDL(ydl_opts) as ydl:
78 ydl.download([url]) 79 ydl.download([url])
79 80
80 # Find the downloaded file (should be the only file in the temp directory) 81 # Find the downloaded file (should be the only file in the temp directory)
81 files = [f for f in os.listdir(temp_dir) if os.path.isfile(os.path.join(temp_dir, f))] 82 files = [f for f in os.listdir(temp_dir) if os.path.isfile(os.path.join(temp_dir, f))]
82 if not files: 83 if not files:
83 raise Exception(f"No file was downloaded") 84 raise Exception(f"No file was downloaded")
84 85
85 actual_file = os.path.join(temp_dir, files[0]) 86 actual_file = os.path.join(temp_dir, files[0])
86 if not os.path.exists(actual_file): 87 if not os.path.exists(actual_file):
87 raise Exception(f"Downloaded file not found: {actual_file}") 88 raise Exception(f"Downloaded file not found: {actual_file}")
88 89
89 try: 90 if os.path.getsize(actual_file) > 1024*1024*10:
90 # Get file info 91 try:
91 filename = f"output.{fformat}" 92 # Get file info
92 93 filename = f"output.{fformat}"
93 # Upload to Copyparty 94
94 with open(actual_file, 'rb') as f: 95 # Upload to Copyparty
95 files = { 96 with open(actual_file, 'rb') as f:
96 'f': (filename, f, 'application/octet-stream') 97 files = {
97 } 98 'f': (filename, f, 'application/octet-stream')
98 headers = { 99 }
99 'Cookie': f'cppwd={os.getenv("COPYPARTY_PASSWORD")}' 100 headers = {
100 } 101 'Cookie': f'cppwd={os.getenv("COPYPARTY_PASSWORD")}'
101 params = { 102 }
102 'j': '1', # Return JSON response 103 params = {
103 'ck': 'b2' # Use blake2b checksum 104 'j': '1', # Return JSON response
104 } 105 'ck': 'b2' # Use blake2b checksum
105 106 }
106 # Ensure the URL ends with a single slash 107
107 base_url = "https://catbox.2137697.xyz/sperma/" 108 # Ensure the URL ends with a single slash
108 109 base_url = "https://catbox.2137697.xyz/sperma/"
109 response = requests.post( 110
110 base_url, 111 response = requests.post(
111 files=files, 112 base_url,
112 headers=headers, 113 files=files,
113 params=params 114 headers=headers,
114 ) 115 params=params
115 116 )
116 if response.status_code == 200 or response.status_code == 201: 117
117 try: 118 if response.status_code == 200 or response.status_code == 201:
118 result = response.json() 119 try:
119 if 'fileurl' in result: 120 result = response.json()
120 dl_url = result['fileurl'] 121 if 'fileurl' in result:
121 await ctx.followup.send( 122 dl_url = result['fileurl']
122 f"wysyłon\n" 123 await ctx.followup.send(
123 f"{dl_url}\n" 124 f"wysyłon\n"
124 ) 125 f"{dl_url}\n"
125 else: 126 )
126 await ctx.followup.send(f"Odpowiedź serwera nie zawiera wymaganych danych: {result}") 127 else:
127 except ValueError: 128 await ctx.followup.send(
128 await ctx.followup.send(f"Nieprawidłowa odpowiedź z serwera: {response.text}") 129 f"Odpowiedź serwera nie zawiera wymaganych danych: {result}")
129 else: 130 except ValueError:
130 error_msg = response.text if response.text else 'Unknown error' 131 await ctx.followup.send(f"Nieprawidłowa odpowiedź z serwera: {response.text}")
131 await ctx.followup.send(f"nie udało się wysłać pliku (HTTP {response.status_code}): {error_msg}") 132 else:
132 133 error_msg = response.text if response.text else 'Unknown error'
133 except Exception as upload_error: 134 await ctx.followup.send(
134 await ctx.followup.send(f"copyparty mnie nienawidzi :cccc\n {str(upload_error)}") 135 f"nie udało się wysłać pliku (HTTP {response.status_code}): {error_msg}")
135 logger.error(f"copyparty upload error: {upload_error}", exc_info=True) 136
136 137 except Exception as upload_error:
138 await ctx.followup.send(f"copyparty mnie nienawidzi :cccc\n {str(upload_error)}")
139 logger.error(f"copyparty upload error: {upload_error}", exc_info=True)
140
141 else:
142 await ctx.followup.send("wysyłon na discord\n", file=discord.File(actual_file))
143
137 logger.info(f"File processed: {actual_file}") 144 logger.info(f"File processed: {actual_file}")
138 145
139 except Exception as e: 146 except Exception as e:
140 await ctx.followup.send(f":(\n{str(e)}") 147 await ctx.followup.send(f":(\n{str(e)}")
141 logger.error(f"Error in download command: {e}", exc_info=True) 148 logger.error(f"Error in download command: {e}", exc_info=True)