Run an async function when youtube-dl finishes downloading (python)

怎甘沉沦 提交于 2019-12-12 07:18:11

问题


I've been writing a music bot for python using the discord.py rewrite. It downloads videos via youtube-dl and plays them back in a voice chat. I've been working hard on a music extension, and recently realized I've completely overlooked something. The progress hooks option of youtube-dl is synchronous, while discord.py is async. youtube-dl spawns a subprocess when downloading a video rather than running it on the current thread, so it does not hang the program. The function I need to run on the completion of a download is a coroutine, as it is part of discord.py

TL;DR I need to run a coroutine when a youtube-dl download finishes

I know this is possible, I've seen it done before, but don't quite understand it.

Here's what I have so far:

def log(text):
  print(Style.BRIGHT + Fore.WHITE + '[' + Fore.RED + 'Music' + Fore.WHITE + '] ' + Style.RESET_ALL + text)
def sync_config():
  raw_config.seek(0)
  raw_config.write(json.dumps(config))
  raw_config.truncate()
lookup_opts = {
    "simulate": True,
    "quiet" : True, #TODO: make this part of config.json
}

if not os.path.exists("plugins/music"):
  log("Config does not exist! Creating it for you..")
  os.makedirs("plugins/music")
if not os.path.exists("plugins/music/cache"):
  os.makedirs("plugins/music/cache")
if not os.path.exists("plugins/music/config.json"):
    with open('plugins/music/config.json', 'w+') as f:
      f.write('{}')
      log('Created config.json')
raw_config = open('plugins/music/config.json', 'r+')
config = json.load(raw_config)

class Music:
  def __init__(self, bot):
      self.bot = bot
  @commands.command(hidden=True)
  async def clearcache(self, ctx):
    if ctx.author.id in ctx.bot.config["admins"]:
      log("Cache cleared!")
      await ctx.message.add_reaction("✅")
      shutil.rmtree("plugins/music/cache")
      os.makedirs("plugins/music/cache")
    else:
      await ctx.send(ctx.bot.denied())
  @commands.command()
  async def play(self, ctx, url):
    """Download and play a link from youtube"""
    message = await ctx.send(f"Downloading <{url}>..")
    with youtube_dl.YoutubeDL(lookup_opts) as ydl:
      try:
        info = ydl.extract_info(url)
        await message.edit(content=f"Downloading {info['title']}..")
      except:
        await ctx.send("An error occured downloading that video! Are you sure that URL is correct?")
      def callback(d):
        if d['status'] == 'finished':
              loop = asyncio.new_event_loop()
              asyncio.set_event_loop(loop)
              loop.run_until_complete(ctx.send("Done!"))
              print("Done!")
      download_opts = {
        "format": 'm4a/bestaudio/best',
        "quiet" : True, #TODO: make this part of config.json
        'progress_hooks': [callback],
      }
      with youtube_dl.YoutubeDL(download_opts) as ydl:
          ydl.download([url])

回答1:


The easiest way to schedule asynchronous execution of a coroutine from blocking code is loop.create_task. Since callback inherits the scope of the enclosing play method, we can use self.bot.loop directly:

  def callback(d):
    if d['status'] == 'finished':
          self.bot.loop.create_task(ctx.send("Done!"))
          print("Done!")


来源:https://stackoverflow.com/questions/52360088/run-an-async-function-when-youtube-dl-finishes-downloading-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!