aboutsummaryrefslogtreecommitdiffstats
path: root/cogs/downloader.py
blob: 5fb3d1cbfc06fd855310cc77518a87b304a7fadc (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
import os
import tempfile
from pathlib import Path

import discord
import yt_dlp
from discord.ext import commands
from dotenv import load_dotenv

# Load environment variables
load_dotenv()


class Downloader(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @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:
            # 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)

                try:
                    file = discord.File(actual_filename)
                    await ctx.followup.send("Pobran", file=file)
                except Exception as e:
                    await ctx.followup.send(f":(\n{str(e)}")

        except Exception as e:
            await ctx.followup.send(f":(\n{str(e)}")


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