music.py 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  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 random import randint
  25. from urllib.parse import urlparse
  26. import aiofiles
  27. import aiohttp
  28. import ffmpeg
  29. import youtube_dl
  30. from pyrogram import filters
  31. from wbb import app, arq
  32. from wbb.core.decorators.errors import capture_err
  33. from wbb.utils.pastebin import paste
  34. from wbb.utils.fetch import fetch
  35. __MODULE__ = "Music"
  36. __HELP__ = """/ytmusic [link] To Download Music From Various Websites Including Youtube. [SUDOERS]
  37. /saavn [query] To Download Music From Saavn.
  38. /deezer [query] To Download Music From Deezer.
  39. /lyrics [query] To Get Lyrics Of A Song."""
  40. is_downloading = False
  41. def get_file_extension_from_url(url):
  42. url_path = urlparse(url).path
  43. basename = os.path.basename(url_path)
  44. return basename.split(".")[-1]
  45. def download_youtube_audio(url: str, m=0):
  46. global is_downloading
  47. with youtube_dl.YoutubeDL(
  48. {
  49. "format": "bestaudio",
  50. "writethumbnail": True,
  51. "quiet": True,
  52. }
  53. ) as ydl:
  54. info_dict = ydl.extract_info(url, download=False)
  55. if int(float(info_dict["duration"])) > 600:
  56. is_downloading = False
  57. return []
  58. ydl.process_info(info_dict)
  59. audio_file = ydl.prepare_filename(info_dict)
  60. basename = audio_file.rsplit(".", 1)[-2]
  61. if info_dict["ext"] == "webm":
  62. audio_file_opus = basename + ".opus"
  63. ffmpeg.input(audio_file).output(
  64. audio_file_opus, codec="copy", loglevel="error"
  65. ).overwrite_output().run()
  66. os.remove(audio_file)
  67. audio_file = audio_file_opus
  68. thumbnail_url = info_dict["thumbnail"]
  69. thumbnail_file = (
  70. basename + "." + get_file_extension_from_url(thumbnail_url)
  71. )
  72. title = info_dict["title"]
  73. performer = info_dict["uploader"]
  74. duration = int(float(info_dict["duration"]))
  75. return [title, performer, duration, audio_file, thumbnail_file]
  76. @app.on_message(filters.command("ytmusic"))
  77. @capture_err
  78. async def music(_, message):
  79. global is_downloading
  80. if len(message.command) != 2:
  81. return await message.reply_text("/ytmusic needs a link as argument")
  82. url = message.text.split(None, 1)[1]
  83. if is_downloading:
  84. return await message.reply_text(
  85. "Another download is in progress, try again after sometime."
  86. )
  87. is_downloading = True
  88. m = await message.reply_text(
  89. f"Downloading {url}", disable_web_page_preview=True
  90. )
  91. try:
  92. loop = get_running_loop()
  93. music = await loop.run_in_executor(
  94. None, partial(download_youtube_audio, url, message)
  95. )
  96. if not music:
  97. await m.edit("Too Long, Can't Download.")
  98. (
  99. title,
  100. performer,
  101. duration,
  102. audio_file,
  103. thumbnail_file,
  104. ) = music
  105. except Exception as e:
  106. is_downloading = False
  107. return await m.edit(str(e))
  108. await message.reply_audio(
  109. audio_file,
  110. duration=duration,
  111. performer=performer,
  112. title=title,
  113. thumb=thumbnail_file,
  114. )
  115. await m.delete()
  116. os.remove(audio_file)
  117. os.remove(thumbnail_file)
  118. is_downloading = False
  119. # Funtion To Download Song
  120. async def download_song(url):
  121. song_name = f"{randint(6969, 6999)}.mp3"
  122. async with aiohttp.ClientSession() as session:
  123. async with session.get(url) as resp:
  124. if resp.status != 200:
  125. return
  126. f = await aiofiles.open(song_name, mode="wb")
  127. await f.write(await resp.read())
  128. await f.close()
  129. return song_name
  130. # Jiosaavn Music
  131. @app.on_message(filters.command("saavn") & ~filters.edited)
  132. @capture_err
  133. async def jssong(_, message):
  134. global is_downloading
  135. if len(message.command) < 2:
  136. return await message.reply_text("/saavn requires an argument.")
  137. if is_downloading:
  138. return await message.reply_text(
  139. "Another download is in progress, try again after sometime."
  140. )
  141. is_downloading = True
  142. text = message.text.split(None, 1)[1]
  143. m = await message.reply_text("Searching...")
  144. try:
  145. songs = await arq.saavn(text)
  146. if not songs.ok:
  147. await m.edit(songs.result)
  148. is_downloading = False
  149. return
  150. sname = songs.result[0].song
  151. slink = songs.result[0].media_url
  152. ssingers = songs.result[0].singers
  153. await m.edit("Downloading")
  154. song = await download_song(slink)
  155. await m.edit("Uploading")
  156. await message.reply_audio(
  157. audio=song,
  158. title=sname,
  159. performer=ssingers,
  160. )
  161. os.remove(song)
  162. await m.delete()
  163. except Exception as e:
  164. is_downloading = False
  165. return await m.edit(str(e))
  166. is_downloading = False
  167. # Deezer Music
  168. @app.on_message(filters.command("deezer") & ~filters.edited)
  169. @capture_err
  170. async def deezsong(_, message):
  171. global is_downloading
  172. if len(message.command) < 2:
  173. return await message.reply_text("/deezer requires an argument.")
  174. if is_downloading:
  175. return await message.reply_text(
  176. "Another download is in progress, try again after sometime."
  177. )
  178. is_downloading = True
  179. text = message.text.split(None, 1)[1]
  180. m = await message.reply_text("Searching...")
  181. try:
  182. songs = await arq.deezer(text, 1, 9)
  183. if not songs.ok:
  184. await m.edit(songs.result)
  185. is_downloading = False
  186. return
  187. title = songs.result[0].title
  188. url = songs.result[0].url
  189. artist = songs.result[0].artist
  190. await m.edit("Downloading")
  191. proxy = "http://52.187.67.188:5000"
  192. try:
  193. song = await download_song(f"{proxy}/mirror?url={url}.mp3")
  194. except Exception:
  195. song = await download_song(url)
  196. if not song:
  197. song = await download_song(url)
  198. await m.edit("Uploading")
  199. await message.reply_audio(
  200. audio=song,
  201. title=title,
  202. performer=artist,
  203. )
  204. os.remove(song)
  205. await m.delete()
  206. except Exception as e:
  207. is_downloading = False
  208. return await m.edit(str(e))
  209. is_downloading = False
  210. try:
  211. await fetch(f"{proxy}/remove")
  212. except Exception:
  213. pass
  214. # Lyrics
  215. @app.on_message(filters.command("lyrics"))
  216. async def lyrics_func(_, message):
  217. if len(message.command) < 2:
  218. return await message.reply_text("**Usage:**\n/lyrics [QUERY]")
  219. m = await message.reply_text("**Searching**")
  220. query = message.text.strip().split(None, 1)[1]
  221. song = await arq.lyrics(query)
  222. lyrics = song.result
  223. if len(lyrics) < 4095:
  224. return await m.edit(f"__{lyrics}__")
  225. lyrics = await paste(lyrics)
  226. await m.edit(f"**LYRICS_TOO_LONG:** [URL]({lyrics})")