music.py 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. from __future__ import unicode_literals
  2. from urllib.parse import urlparse
  3. import os
  4. import youtube_dl
  5. from pyrogram import filters
  6. from pyrogram.types import Message
  7. from wbb.utils import cust_filter
  8. from wbb import app
  9. __MODULE__ = "Music"
  10. __HELP__ = "/music [link] To Download Music From Various Websites"
  11. ydl_opts = {
  12. 'format': 'bestaudio',
  13. 'writethumbnail': True
  14. }
  15. @app.on_message(cust_filter.command(commands=("music")) & ~filters.edited)
  16. async def music(_, message: Message):
  17. if len(message.command) != 2:
  18. await message.reply_text("`/music` needs a link as argument")
  19. return
  20. link = message.text.split(None, 1)[1]
  21. m = await message.reply_text(f"Downloading {link}",
  22. disable_web_page_preview=True)
  23. try:
  24. with youtube_dl.YoutubeDL(ydl_opts) as ydl:
  25. info_dict = ydl.extract_info(link, download=False)
  26. audio_file = ydl.prepare_filename(info_dict)
  27. ydl.process_info(info_dict)
  28. # .webm -> .weba
  29. basename = audio_file.rsplit(".", 1)[-2]
  30. thumbnail_url = info_dict['thumbnail']
  31. thumbnail_file = basename + "." + \
  32. get_file_extension_from_url(thumbnail_url)
  33. if info_dict['ext'] == 'webm':
  34. audio_file_weba = basename + ".weba"
  35. os.rename(audio_file, audio_file_weba)
  36. audio_file = audio_file_weba
  37. except Exception as e:
  38. await m.edit(str(e))
  39. return
  40. # info
  41. title = info_dict['title']
  42. webpage_url = info_dict['webpage_url']
  43. performer = info_dict['uploader']
  44. duration = int(float(info_dict['duration']))
  45. caption = f"[{title}]({webpage_url})"
  46. await m.delete()
  47. await message.reply_chat_action("upload_document")
  48. await message.reply_audio(audio_file, caption=caption,
  49. duration=duration, performer=performer,
  50. title=title, thumb=thumbnail_file)
  51. os.remove(audio_file)
  52. os.remove(thumbnail_file)
  53. def get_file_extension_from_url(url):
  54. url_path = urlparse(url).path
  55. basename = os.path.basename(url_path)
  56. return basename.split(".")[-1]