aboutsummaryrefslogtreecommitdiffstats
path: root/cogs/music/play_utils.py
blob: e21d6d903c5a91ec12f30f020cf274b4206f4dbd (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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
import logging
from youtubesearchpython import VideosSearch
import yt_dlp
import discord
import asyncio
import os

logger = logging.getLogger(__name__)

class PlayUtils:
    def __init__(self, bot):
        self.bot = bot

    async def download(self, ctx, url):

        # Create temp directory if it doesn't exist
        temp_dir = os.path.join('cogs', 'temp', 'music')
        os.makedirs(temp_dir, exist_ok=True)
        
        ytdl_opts = {
            "format": "bestaudio/best",
            "outtmpl": os.path.join(temp_dir, "%(title)s.%(ext)s"),
            "postprocessors": [
                {
                    "key": "FFmpegExtractAudio",
                    "preferredcodec": "mp3",
                    "preferredquality": "192",
                }
            ],
        }

        try:
            with yt_dlp.YoutubeDL(ytdl_opts) as ydl:
                info_dict = ydl.extract_info(url, download=True)
                # Get the base filename without extension
                base_filename = os.path.splitext(ydl.prepare_filename(info_dict))[0]
                # Add .mp3 extension since we're extracting audio
                filename = f"{base_filename}.mp3"
                logger.info(f"Downloaded file: {filename}")
                return filename
        except Exception as e:
            logger.error(f"Error downloading video: {e}")
            await ctx.respond("eror pobirajync wideło", ephemeral=True)

    async def get_url(self, ctx, query):
        search = VideosSearch(query, limit=1)
        if search.result()["result"]:
            title = search.result()["result"][0]["title"]
            url = search.result()["result"][0]["link"]
            logger.info(f"Found video: {title}")
            return url, title
        else:
            logger.warning("No results found for the query.")
            await ctx.respond("nic ni ma", ephemeral=True)
            return None

    async def compress(self, ctx, filename):
        if not filename:
            await ctx.respond("dzie wideło", ephemeral=True)
            return

        ffmpeg_command = f"ffmpeg -i {filename} -ac 1 -b:a 500 -acodec libopus {filename}"
        try:
            process = await asyncio.create_subprocess_shell(
                ffmpeg_command,
                stdout=asyncio.subprocess.PIPE,
                stderr=asyncio.subprocess.PIPE
            )
            stdout, stderr = await process.communicate()
            if process.returncode != 0:
                logger.error(f"FFmpeg error: {stderr.decode()}")
                await ctx.respond("eror kompresujync pilk", ephemeral=True)
            else:
                logger.info(f"Compressed file: {filename}")
        except Exception as e:
            logger.error(f"Error compressing file: {e}")
            await ctx.respond("eror kompresujync pilk", ephemeral=True)

    async def play(self, ctx, filename, title):
        # Check if user is in a voice channel
        if not ctx.author.voice or not ctx.author.voice.channel:
            await ctx.respond("Musisz być na kanale głosowym, żebym mógł dołączyć!", ephemeral=True)
            return

        # Get or create voice client
        vc = ctx.voice_client
        target_channel = ctx.author.voice.channel

        try:
            # Connect to voice channel if not connected
            if vc is None:
                vc = await target_channel.connect()
                logger.info(f"Connected to voice channel: {target_channel.name}")
            # Move to user's channel if in a different one
            elif vc.channel != target_channel:
                await vc.move_to(target_channel)
                logger.info(f"Moved to voice channel: {target_channel.name}")

            if not filename or not os.path.exists(filename):
                await ctx.respond("Nie znaleziono pliku do odtworzenia", ephemeral=True)
                logger.warning(f"No file to play, filename: {filename}")
                return

            # Stop any currently playing audio
            if vc.is_playing() or vc.is_paused():
                vc.stop()

            # Play the audio
            source = discord.FFmpegPCMAudio(source=filename)
            vc.play(source)

            logger.info(f"Playing file: {title}")
            await ctx.respond(f"grom: {title}")

        except Exception as e:
            logger.error(f"Error in play: {str(e)}", exc_info=True)
            await ctx.respond(f"eror: {str(e)}", ephemeral=True)