music.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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(
  19. "`/music` needs a link as argument")
  20. return
  21. link = message.text.split(None, 1)[1]
  22. m = await message.reply_text(f"Downloading {link}",
  23. disable_web_page_preview=True)
  24. try:
  25. with youtube_dl.YoutubeDL(ydl_opts) as ydl:
  26. info_dict = ydl.extract_info(link, download=False)
  27. audio_file = ydl.prepare_filename(info_dict)
  28. ydl.process_info(info_dict)
  29. # .webm -> .weba
  30. basename = audio_file.rsplit(".", 1)[-2]
  31. thumbnail_url = info_dict['thumbnail']
  32. thumbnail_file = basename + "." + \
  33. get_file_extension_from_url(thumbnail_url)
  34. if info_dict['ext'] == 'webm':
  35. audio_file_weba = basename + ".weba"
  36. os.rename(audio_file, audio_file_weba)
  37. audio_file = audio_file_weba
  38. except Exception as e:
  39. await m.edit(str(e))
  40. return
  41. # info
  42. title = info_dict['title']
  43. webpage_url = info_dict['webpage_url']
  44. performer = info_dict['uploader']
  45. duration = int(float(info_dict['duration']))
  46. caption = f"[{title}]({webpage_url})"
  47. await m.delete()
  48. await message.reply_chat_action("upload_document")
  49. await message.reply_audio(audio_file, caption=caption,
  50. duration=duration, performer=performer,
  51. title=title, thumb=thumbnail_file)
  52. os.remove(audio_file)
  53. os.remove(thumbnail_file)
  54. def get_file_extension_from_url(url):
  55. url_path = urlparse(url).path
  56. basename = os.path.basename(url_path)
  57. return basename.split(".")[-1]