music.py 2.0 KB

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