music.py 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171
  1. """
  2. MIT License
  3. Copyright (c) 2024 TheHamkerCat
  4. Permission is hereby granted, free of charge, to any person obtaining a copy
  5. of this software and associated documentation files (the "Software"), to deal
  6. in the Software without restriction, including without limitation the rights
  7. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. copies of the Software, and to permit persons to whom the Software is
  9. furnished to do so, subject to the following conditions:
  10. The above copyright notice and this permission notice shall be included in all
  11. copies or substantial portions of the Software.
  12. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  13. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  14. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  15. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  16. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  17. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  18. SOFTWARE.
  19. """
  20. import os
  21. import re
  22. from asyncio import get_running_loop
  23. from functools import partial
  24. from io import BytesIO
  25. import yt_dlp
  26. from pyrogram import filters
  27. from wbb import aiohttpsession as session
  28. from wbb import app, arq
  29. from wbb.core.decorators.errors import capture_err
  30. from wbb.utils.pastebin import paste
  31. __MODULE__ = "Music"
  32. __HELP__ = """
  33. /ytmusic [link] To Download Music From Various Websites Including Youtube. [SUDOERS]
  34. /saavn [query] To Download Music From Saavn.
  35. /lyrics [query] To Get Lyrics Of A Song.
  36. """
  37. is_downloading = False
  38. def download_youtube_audio(query):
  39. # Prefix bare search terms with ytsearch1: so yt-dlp resolves them.
  40. is_url = query.startswith("http://") or query.startswith("https://")
  41. target = query if is_url else f"ytsearch1:{query}"
  42. ydl_opts = {
  43. "format": "bestaudio/best",
  44. "outtmpl": "%(id)s.%(ext)s",
  45. "postprocessors": [{
  46. "key": "FFmpegExtractAudio",
  47. "preferredcodec": "mp3",
  48. "preferredquality": "192",
  49. }],
  50. "writethumbnail": True,
  51. "quiet": True,
  52. "no_warnings": True,
  53. "noplaylist": True,
  54. }
  55. with yt_dlp.YoutubeDL(ydl_opts) as ydl:
  56. info = ydl.extract_info(target, download=True)
  57. # For search results yt-dlp wraps entries in a playlist dict.
  58. if "entries" in info:
  59. info = info["entries"][0]
  60. duration = int(info.get("duration") or 0)
  61. if duration > 1800:
  62. return None
  63. title = info.get("title", "Unknown")
  64. performer = info.get("uploader") or info.get("channel", "Unknown")
  65. # Sanitize ID to prevent path traversal.
  66. safe_id = re.sub(r"[^\w\-]", "_", info["id"])
  67. audio_file = f"{safe_id}.mp3"
  68. # yt-dlp writes the thumbnail as <id>.<ext>; find whatever it wrote.
  69. thumbnail_file = next(
  70. (f"{safe_id}.{ext}" for ext in ("webp", "jpg", "png")
  71. if os.path.exists(f"{safe_id}.{ext}")),
  72. None,
  73. )
  74. return [title, performer, duration, audio_file, thumbnail_file]
  75. @app.on_message(filters.command("ytmusic"))
  76. @capture_err
  77. async def music(_, message):
  78. global is_downloading
  79. if len(message.command) < 2:
  80. return await message.reply_text("/ytmusic needs a query as argument")
  81. url = message.text.split(None, 1)[1]
  82. if is_downloading:
  83. return await message.reply_text(
  84. "Another download is in progress, try again after sometime."
  85. )
  86. is_downloading = True
  87. m = await message.reply_text(f"Downloading {url}", disable_web_page_preview=True)
  88. try:
  89. loop = get_running_loop()
  90. music = await loop.run_in_executor(
  91. None, partial(download_youtube_audio, url)
  92. )
  93. if not music:
  94. return await message.reply_text("[ERROR]: MUSIC TOO LONG")
  95. (
  96. title,
  97. performer,
  98. duration,
  99. audio_file,
  100. thumbnail_file,
  101. ) = music
  102. except Exception as e:
  103. is_downloading = False
  104. return await m.edit(str(e))
  105. await message.reply_audio(
  106. audio_file,
  107. duration=duration,
  108. performer=performer,
  109. title=title,
  110. thumb=thumbnail_file,
  111. )
  112. await m.delete()
  113. os.remove(audio_file)
  114. if thumbnail_file and os.path.exists(thumbnail_file):
  115. os.remove(thumbnail_file)
  116. is_downloading = False
  117. async def download_song(url):
  118. async with session.get(url) as resp:
  119. song = await resp.read()
  120. song = BytesIO(song)
  121. song.name = "a.mp3"
  122. return song
  123. # Lyrics
  124. @app.on_message(filters.command("lyrics"))
  125. async def lyrics_func(_, message):
  126. if len(message.command) < 2:
  127. return await message.reply_text("**Usage:**\n/lyrics [QUERY]")
  128. m = await message.reply_text("**Searching**")
  129. query = message.text.strip().split(None, 1)[1]
  130. resp = await arq.lyrics(query)
  131. if not (resp.ok and resp.result):
  132. return await m.edit("No lyrics found.")
  133. song = resp.result[0]
  134. song_name = song["song"]
  135. artist = song["artist"]
  136. lyrics = song["lyrics"]
  137. msg = f"**{song_name}** | **{artist}**\n\n__{lyrics}__"
  138. if len(msg) > 4095:
  139. msg = await paste(msg)
  140. msg = f"**LYRICS_TOO_LONG:** [URL]({msg})"
  141. return await m.edit(msg)