music.py 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  1. """
  2. MIT License
  3. Copyright (c) 2021 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. from __future__ import unicode_literals
  21. import os
  22. from asyncio import get_running_loop
  23. from functools import partial
  24. from io import BytesIO
  25. from urllib.parse import urlparse
  26. import ffmpeg
  27. import youtube_dl
  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 get_file_extension_from_url(url):
  41. url_path = urlparse(url).path
  42. basename = os.path.basename(url_path)
  43. return basename.split(".")[-1]
  44. def download_youtube_audio(url: str):
  45. global is_downloading
  46. with youtube_dl.YoutubeDL(
  47. {
  48. "format": "bestaudio",
  49. "writethumbnail": True,
  50. "quiet": True,
  51. }
  52. ) as ydl:
  53. info_dict = ydl.extract_info(url, download=False)
  54. if int(float(info_dict["duration"])) > 600:
  55. is_downloading = False
  56. return []
  57. ydl.process_info(info_dict)
  58. audio_file = ydl.prepare_filename(info_dict)
  59. basename = audio_file.rsplit(".", 1)[-2]
  60. if info_dict["ext"] == "webm":
  61. audio_file_opus = basename + ".opus"
  62. ffmpeg.input(audio_file).output(
  63. audio_file_opus, codec="copy", loglevel="error"
  64. ).overwrite_output().run()
  65. os.remove(audio_file)
  66. audio_file = audio_file_opus
  67. thumbnail_url = info_dict["thumbnail"]
  68. thumbnail_file = (
  69. basename
  70. + "."
  71. + get_file_extension_from_url(thumbnail_url)
  72. )
  73. title = info_dict["title"]
  74. performer = info_dict["uploader"]
  75. duration = int(float(info_dict["duration"]))
  76. return [title, performer, duration, audio_file, thumbnail_file]
  77. @app.on_message(filters.command("ytmusic"))
  78. @capture_err
  79. async def music(_, message):
  80. global is_downloading
  81. if len(message.command) != 2:
  82. return await message.reply_text(
  83. "/ytmusic needs a link as argument"
  84. )
  85. url = message.text.split(None, 1)[1]
  86. if is_downloading:
  87. return await message.reply_text(
  88. "Another download is in progress, try again after sometime."
  89. )
  90. is_downloading = True
  91. m = await message.reply_text(
  92. f"Downloading {url}", disable_web_page_preview=True
  93. )
  94. try:
  95. loop = get_running_loop()
  96. music = await loop.run_in_executor(
  97. None, partial(download_youtube_audio, url)
  98. )
  99. if not music:
  100. await m.edit("Too Long, Can't Download.")
  101. (
  102. title,
  103. performer,
  104. duration,
  105. audio_file,
  106. thumbnail_file,
  107. ) = music
  108. except Exception as e:
  109. is_downloading = False
  110. return await m.edit(str(e))
  111. await message.reply_audio(
  112. audio_file,
  113. duration=duration,
  114. performer=performer,
  115. title=title,
  116. thumb=thumbnail_file,
  117. )
  118. await m.delete()
  119. os.remove(audio_file)
  120. os.remove(thumbnail_file)
  121. is_downloading = False
  122. # Funtion To Download Song
  123. async def download_song(url):
  124. async with session.get(url) as resp:
  125. song = await resp.read()
  126. song = BytesIO(song)
  127. song.name = "a.mp3"
  128. return song
  129. # Jiosaavn Music
  130. @app.on_message(filters.command("saavn") & ~filters.edited)
  131. @capture_err
  132. async def jssong(_, message):
  133. global is_downloading
  134. if len(message.command) < 2:
  135. return await message.reply_text(
  136. "/saavn requires an argument."
  137. )
  138. if is_downloading:
  139. return await message.reply_text(
  140. "Another download is in progress, try again after sometime."
  141. )
  142. is_downloading = True
  143. text = message.text.split(None, 1)[1]
  144. m = await message.reply_text("Searching...")
  145. try:
  146. songs = await arq.saavn(text)
  147. if not songs.ok:
  148. await m.edit(songs.result)
  149. is_downloading = False
  150. return
  151. sname = songs.result[0].song
  152. slink = songs.result[0].media_url
  153. ssingers = songs.result[0].singers
  154. sduration = songs.result[0].duration
  155. await m.edit("Downloading")
  156. song = await download_song(slink)
  157. await m.edit("Uploading")
  158. await message.reply_audio(
  159. audio=song,
  160. title=sname,
  161. performer=ssingers,
  162. duration=sduration,
  163. )
  164. await m.delete()
  165. except Exception as e:
  166. is_downloading = False
  167. return await m.edit(str(e))
  168. is_downloading = False
  169. song.close()
  170. # Lyrics
  171. @app.on_message(filters.command("lyrics"))
  172. async def lyrics_func(_, message):
  173. if len(message.command) < 2:
  174. return await message.reply_text("**Usage:**\n/lyrics [QUERY]")
  175. m = await message.reply_text("**Searching**")
  176. query = message.text.strip().split(None, 1)[1]
  177. song = await arq.lyrics(query)
  178. lyrics = song.result
  179. if len(lyrics) < 4095:
  180. return await m.edit(f"__{lyrics}__")
  181. lyrics = await paste(lyrics)
  182. await m.edit(f"**LYRICS_TOO_LONG:** [URL]({lyrics})")