music.py 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  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 + "." + get_file_extension_from_url(thumbnail_url)
  70. )
  71. title = info_dict["title"]
  72. performer = info_dict["uploader"]
  73. duration = int(float(info_dict["duration"]))
  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 link 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(
  88. f"Downloading {url}", disable_web_page_preview=True
  89. )
  90. try:
  91. loop = get_running_loop()
  92. music = await loop.run_in_executor(
  93. None, partial(download_youtube_audio, url)
  94. )
  95. if not music:
  96. await m.edit("Too Long, Can't Download.")
  97. (
  98. title,
  99. performer,
  100. duration,
  101. audio_file,
  102. thumbnail_file,
  103. ) = music
  104. except Exception as e:
  105. is_downloading = False
  106. return await m.edit(str(e))
  107. await message.reply_audio(
  108. audio_file,
  109. duration=duration,
  110. performer=performer,
  111. title=title,
  112. thumb=thumbnail_file,
  113. )
  114. await m.delete()
  115. os.remove(audio_file)
  116. os.remove(thumbnail_file)
  117. is_downloading = False
  118. # Funtion To Download Song
  119. async def download_song(url):
  120. async with session.get(url) as resp:
  121. song = await resp.read()
  122. song = BytesIO(song)
  123. song.name = "a.mp3"
  124. return song
  125. # Jiosaavn Music
  126. @app.on_message(filters.command("saavn") & ~filters.edited)
  127. @capture_err
  128. async def jssong(_, message):
  129. global is_downloading
  130. if len(message.command) < 2:
  131. return await message.reply_text("/saavn requires an argument.")
  132. if is_downloading:
  133. return await message.reply_text(
  134. "Another download is in progress, try again after sometime."
  135. )
  136. is_downloading = True
  137. text = message.text.split(None, 1)[1]
  138. m = await message.reply_text("Searching...")
  139. try:
  140. songs = await arq.saavn(text)
  141. if not songs.ok:
  142. await m.edit(songs.result)
  143. is_downloading = False
  144. return
  145. sname = songs.result[0].song
  146. slink = songs.result[0].media_url
  147. ssingers = songs.result[0].singers
  148. sduration = songs.result[0].duration
  149. await m.edit("Downloading")
  150. song = await download_song(slink)
  151. await m.edit("Uploading")
  152. await message.reply_audio(
  153. audio=song,
  154. title=sname,
  155. performer=ssingers,
  156. duration=sduration,
  157. )
  158. await m.delete()
  159. except Exception as e:
  160. is_downloading = False
  161. return await m.edit(str(e))
  162. is_downloading = False
  163. song.close()
  164. # Lyrics
  165. @app.on_message(filters.command("lyrics"))
  166. async def lyrics_func(_, message):
  167. if len(message.command) < 2:
  168. return await message.reply_text("**Usage:**\n/lyrics [QUERY]")
  169. m = await message.reply_text("**Searching**")
  170. query = message.text.strip().split(None, 1)[1]
  171. song = await arq.lyrics(query)
  172. lyrics = song.result
  173. if len(lyrics) < 4095:
  174. return await m.edit(f"__{lyrics}__")
  175. lyrics = await paste(lyrics)
  176. await m.edit(f"**LYRICS_TOO_LONG:** [URL]({lyrics})")