music.py 5.0 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 datetime
  21. import os
  22. import re
  23. from asyncio import get_running_loop
  24. from functools import partial
  25. from io import BytesIO
  26. import httpx
  27. import yt_dlp
  28. from pyrogram import filters
  29. from wbb import aiohttpsession as session
  30. from wbb import app, arq
  31. from wbb.core.decorators.errors import capture_err
  32. from wbb.utils.pastebin import paste
  33. __MODULE__ = "Music"
  34. __HELP__ = """
  35. /ytmusic [link] To Download Music From Various Websites Including Youtube. [SUDOERS]
  36. /saavn [query] To Download Music From Saavn.
  37. /lyrics [query] To Get Lyrics Of A Song.
  38. """
  39. is_downloading = False
  40. def download_youtube_audio(arq_resp):
  41. r = arq_resp.result[0]
  42. title = r.title
  43. performer = r.channel
  44. m, s = r.duration.split(":")
  45. duration = int(datetime.timedelta(minutes=int(m), seconds=int(s)).total_seconds())
  46. if duration > 1800:
  47. return
  48. thumb = httpx.get(r.thumbnails[0]).content
  49. with open("thumbnail.png", "wb") as f:
  50. f.write(thumb)
  51. thumbnail_file = "thumbnail.png"
  52. url = f"https://youtube.com{r.url_suffix}"
  53. ydl_opts = {
  54. "format": "bestaudio/best",
  55. "outtmpl": "%(id)s.%(ext)s",
  56. "postprocessors": [{
  57. "key": "FFmpegExtractAudio",
  58. "preferredcodec": "mp3",
  59. "preferredquality": "192",
  60. }],
  61. "quiet": True,
  62. "no_warnings": True,
  63. "noplaylist": True,
  64. }
  65. with yt_dlp.YoutubeDL(ydl_opts) as ydl:
  66. info = ydl.extract_info(url, download=True)
  67. # Sanitize the video ID before using it as a filename to prevent
  68. # path traversal in case a non-standard extractor returns a dirty ID.
  69. safe_id = re.sub(r"[^\w\-]", "_", info["id"])
  70. audio_file = f"{safe_id}.mp3"
  71. return [title, performer, duration, audio_file, thumbnail_file]
  72. @app.on_message(filters.command("ytmusic"))
  73. @capture_err
  74. async def music(_, message):
  75. global is_downloading
  76. if len(message.command) < 2:
  77. return await message.reply_text("/ytmusic needs a query as argument")
  78. url = message.text.split(None, 1)[1]
  79. if is_downloading:
  80. return await message.reply_text(
  81. "Another download is in progress, try again after sometime."
  82. )
  83. is_downloading = True
  84. m = await message.reply_text(f"Downloading {url}", disable_web_page_preview=True)
  85. try:
  86. loop = get_running_loop()
  87. arq_resp = await arq.youtube(url)
  88. music = await loop.run_in_executor(
  89. None, partial(download_youtube_audio, arq_resp)
  90. )
  91. if not music:
  92. return await message.reply_text("[ERROR]: MUSIC TOO LONG")
  93. (
  94. title,
  95. performer,
  96. duration,
  97. audio_file,
  98. thumbnail_file,
  99. ) = music
  100. except Exception as e:
  101. is_downloading = False
  102. return await m.edit(str(e))
  103. await message.reply_audio(
  104. audio_file,
  105. duration=duration,
  106. performer=performer,
  107. title=title,
  108. thumb=thumbnail_file,
  109. )
  110. await m.delete()
  111. os.remove(audio_file)
  112. os.remove(thumbnail_file)
  113. is_downloading = False
  114. async def download_song(url):
  115. async with session.get(url) as resp:
  116. song = await resp.read()
  117. song = BytesIO(song)
  118. song.name = "a.mp3"
  119. return song
  120. # Lyrics
  121. @app.on_message(filters.command("lyrics"))
  122. async def lyrics_func(_, message):
  123. if len(message.command) < 2:
  124. return await message.reply_text("**Usage:**\n/lyrics [QUERY]")
  125. m = await message.reply_text("**Searching**")
  126. query = message.text.strip().split(None, 1)[1]
  127. resp = await arq.lyrics(query)
  128. if not (resp.ok and resp.result):
  129. return await m.edit("No lyrics found.")
  130. song = resp.result[0]
  131. song_name = song["song"]
  132. artist = song["artist"]
  133. lyrics = song["lyrics"]
  134. msg = f"**{song_name}** | **{artist}**\n\n__{lyrics}__"
  135. if len(msg) > 4095:
  136. msg = await paste(msg)
  137. msg = f"**LYRICS_TOO_LONG:** [URL]({msg})"
  138. return await m.edit(msg)