From 8756947298e1e0f4240199be5c087c61111da217 Mon Sep 17 00:00:00 2001 From: phixxy Date: Thu, 5 Sep 2024 18:43:40 -0700 Subject: [PATCH] make function async --- cogs/ytdl.py | 41 ++++++++++++++++++++++++++++++++++++++--- 1 file changed, 38 insertions(+), 3 deletions(-) diff --git a/cogs/ytdl.py b/cogs/ytdl.py index c068872..09d2b06 100644 --- a/cogs/ytdl.py +++ b/cogs/ytdl.py @@ -1,6 +1,6 @@ import os import subprocess -import logging +import asyncio from discord.ext import commands, tasks from cogs.base_cog.bot_base_cog import BotBaseCog @@ -12,7 +12,7 @@ class YoutubeDL(BotBaseCog): self.setup(__class__.__name__) self.check_for_downloads.start() - @commands.command() + ''' @commands.command() async def youtubedl(self, ctx): try: # Expecting the command format to be !youtubedl @@ -42,8 +42,43 @@ class YoutubeDL(BotBaseCog): except Exception as e: #await ctx.send(f"Error: {e}") - await ctx.send("Usage: !youtubedl ") + await ctx.send("Usage: !youtubedl ")''' + + @commands.command() + async def youtubedl(self, ctx): + try: + # Expecting the command format to be !youtubedl + parts = ctx.message.content.split(" ") + if len(parts) < 3: + await ctx.send("Usage: !youtubedl ") + return + + url = parts[1] + video_or_audio = parts[2] + # Create a subprocess + process = await asyncio.create_subprocess_exec( + "python3", "youtubedl.py", url, video_or_audio, + cwd="data/ytdl", + stdout=asyncio.subprocess.PIPE, + stderr=asyncio.subprocess.PIPE + ) + + # Write a message that the download has started + await ctx.send(f"Downloading {video_or_audio} from {url}...") + + # Read stdout and stderr (non-blocking) + stdout, stderr = await process.communicate() + + # Send the output back to the user + if stdout: + await ctx.send(f"std out: {stdout.decode('utf-8')}") + if stderr: + await ctx.send(f"std err: {stderr.decode('utf-8')}") + + except Exception as e: + await ctx.send(f"Error: {e}") + #create a task @tasks.loop(seconds=10) async def check_for_downloads(self):