aboutsummaryrefslogtreecommitdiffstats
path: root/cogs/downloader.py
blob: b992e822f10f52c6defb84f8a5438f9ffa1bc497 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
import base64
import os
import discord
from discord.ext import commands
import requests
import yt_dlp
from dotenv import load_dotenv

# Load environment variables
load_dotenv()
PIXELDRAIN_API_KEY = os.getenv('PIXELDRAIN_API_KEY')

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",
    )
    async def download(
        self,
        ctx: discord.ApplicationContext,
        url: discord.Option(str, "url", required=True)
    ):
        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
                        
                        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:
                            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)
        except Exception as e:
            await ctx.followup.send(f"Error: {str(e)}")

def setup(bot):
    bot.add_cog(Downloader(bot))