aboutsummaryrefslogtreecommitdiffstats
path: root/cogs/downloader.py
diff options
context:
space:
mode:
authorSamlonDev <stankiewiczgracjan2019@gmail.com>2025-06-14 17:47:21 +0200
committerSamlonDev <stankiewiczgracjan2019@gmail.com>2025-06-14 17:47:21 +0200
commit3846579818420c1e639cb018d31ad812c2d95a03 (patch)
tree8446b7cc629ddc1938fefa24ad03f959795d93e2 /cogs/downloader.py
parentvolume control and fixes to math (diff)
downloadsenator-sperma-3846579818420c1e639cb018d31ad812c2d95a03.tar.gz
senator-sperma-3846579818420c1e639cb018d31ad812c2d95a03.zip
temp downloads the files instead
Diffstat (limited to '')
-rw-r--r--cogs/downloader.py119
1 files 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
5import requests 5import requests
6import yt_dlp 6import yt_dlp
7from dotenv import load_dotenv 7from dotenv import load_dotenv
8import tempfile
9import os.path
8 10
9# Load environment variables 11# Load environment variables
10load_dotenv() 12load_dotenv()
11PIXELDRAIN_API_KEY = os.getenv('PIXELDRAIN_API_KEY') 13PIXELDRAIN_API_KEY = os.getenv('PIXELDRAIN_API_KEY')
12 14
15
16def _get_auth_headers():
17 """Generate authentication headers for Pixeldrain API"""
18 if not PIXELDRAIN_API_KEY:
19 raise Exception("Pixeldrain API key not found in environment variables")
20
21 auth_string = f":{PIXELDRAIN_API_KEY}"
22 auth_bytes = auth_string.encode('ascii')
23 base64_auth = base64.b64encode(auth_bytes).decode('ascii')
24 return {"Authorization": f"Basic {base64_auth}"}
25
26
13class Downloader(commands.Cog): 27class Downloader(commands.Cog):
14 def __init__(self, bot): 28 def __init__(self, bot):
15 self.bot = bot 29 self.bot = bot
16 self.pixeldrain_url = "https://pixeldrain.com/api/file" 30 self.pixeldrain_url = "https://pixeldrain.com/api/file"
17 31
18 def _get_auth_headers(self):
19 """Generate authentication headers for Pixeldrain API"""
20 if not PIXELDRAIN_API_KEY:
21 raise Exception("Pixeldrain API key not found in environment variables")
22
23 auth_string = f":{PIXELDRAIN_API_KEY}"
24 auth_bytes = auth_string.encode('ascii')
25 base64_auth = base64.b64encode(auth_bytes).decode('ascii')
26 return {"Authorization": f"Basic {base64_auth}"}
27
28 @commands.slash_command( 32 @commands.slash_command(
29 name="download", 33 name="download",
30 description="download video from internet", 34 description="download video from internet",
@@ -36,53 +40,56 @@ class Downloader(commands.Cog):
36 ): 40 ):
37 await ctx.defer() 41 await ctx.defer()
38 try: 42 try:
39 # pass link to yt-dlp 43 # Create a temporary directory
40 outtmpl = '%(title)s.%(ext)s' 44 with tempfile.TemporaryDirectory() as temp_dir:
41 ydl_opts = { 45 # Configure yt-dlp to use the temp directory
42 'outtmpl': outtmpl, 46 outtmpl = os.path.join(temp_dir, '%(title)s.%(ext)s')
43 'merge_output_format': 'mp4', 47 ydl_opts = {
44 } 48 'outtmpl': outtmpl,
45 with yt_dlp.YoutubeDL(ydl_opts) as ydl: 49 'merge_output_format': 'mp4',
46 info = ydl.extract_info(url, download=True) 50 }
47 actual_filename = ydl.prepare_filename(info) 51
48 52 with yt_dlp.YoutubeDL(ydl_opts) as ydl:
49 await ctx.followup.send("Video downloaded successfully, Uploading to pixeldrain...") 53 info = ydl.extract_info(url, download=True)
50 # upload to pixeldrain 54 actual_filename = ydl.prepare_filename(info)
51 try: 55
52 with open(actual_filename, 'rb') as f: 56 await ctx.followup.send("Video downloaded successfully, Uploading to pixeldrain...")
53 files = {'file': f} 57 # upload to pixeldrain
54 response = requests.post( 58 try:
55 self.pixeldrain_url, 59 with open(actual_filename, 'rb') as f:
56 files=files, 60 files = {'file': f}
57 headers={"Authorization": f"Basic {base64.b64encode((':' + PIXELDRAIN_API_KEY).encode()).decode()}"} 61 response = requests.post(
58 ) 62 self.pixeldrain_url,
59 63 files=files,
60 try: 64 headers={"Authorization": f"Basic {base64.b64encode((':' + PIXELDRAIN_API_KEY).encode()).decode()}"}
61 response_data = response.json() 65 )
62 print("Pixeldrain response:", response_data) # Debug log
63 66
64 if response.status_code == 201: # 201 means successful upload 67 try:
65 file_id = response_data.get('id') 68 response_data = response.json()
66 if file_id: 69 print("Pixeldrain response:", response_data) # Debug log
67 file_link = f"https://pixeldrain.com/u/{file_id}" 70
68 await ctx.followup.send(f"oto twoje videło\n {file_link}") 71 if response.status_code == 201: # 201 means successful upload
72 file_id = response_data.get('id')
73 if file_id:
74 file_link = f"https://pixeldrain.com/u/{file_id}"
75 await ctx.followup.send(f"oto twoje videło\n {file_link}")
76 else:
77 await ctx.followup.send(f"⚠️ Upload successful but no file ID returned. Response: {response_data}")
69 else: 78 else:
70 await ctx.followup.send(f"⚠️ Upload successful but no file ID returned. Response: {response_data}") 79 error_msg = response_data.get('error', 'Unknown error')
71 else: 80 if response.status_code == 401:
72 error_msg = response_data.get('error', 'Unknown error') 81 error_msg = "Invalid API key. Please check your PIXELDRAIN_API_KEY in .env file."
73 if response.status_code == 401: 82 await ctx.followup.send(f"❌ Upload failed (Status {response.status_code}): {error_msg}")
74 error_msg = "Invalid API key. Please check your PIXELDRAIN_API_KEY in .env file." 83 except ValueError as e:
75 await ctx.followup.send(f"❌ Upload failed (Status {response.status_code}): {error_msg}") 84 # If response is not JSON
76 except ValueError as e: 85 error_msg = f"Failed to parse server response: {str(e)}"
77 # If response is not JSON 86 if response.text:
78 error_msg = f"Failed to parse server response: {str(e)}" 87 error_msg += f"\nResponse: {response.text[:200]}"
79 if response.text: 88 await ctx.followup.send(f"❌ {error_msg}")
80 error_msg += f"\nResponse: {response.text[:200]}" 89 except Exception as e:
81 await ctx.followup.send(f"❌ {error_msg}") 90 await ctx.followup.send(f"Error: {str(e)}")
82 finally: 91 # No need for explicit cleanup as tempfile.TemporaryDirectory handles it automatically
83 # Clean up the downloaded file 92
84 if os.path.exists(actual_filename):
85 os.remove(actual_filename)
86 except Exception as e: 93 except Exception as e:
87 await ctx.followup.send(f"Error: {str(e)}") 94 await ctx.followup.send(f"Error: {str(e)}")
88 95