music.py 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  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.http import get
  34. from wbb.utils.pastebin import paste
  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
  71. + "."
  72. + get_file_extension_from_url(thumbnail_url)
  73. )
  74. title = info_dict["title"]
  75. performer = info_dict["uploader"]
  76. duration = int(float(info_dict["duration"]))
  77. return [title, performer, duration, audio_file, thumbnail_file]
  78. @app.on_message(filters.command("ytmusic"))
  79. @capture_err
  80. async def music(_, message):
  81. global is_downloading
  82. if len(message.command) != 2:
  83. return await message.reply_text(
  84. "/ytmusic needs a link as argument"
  85. )
  86. url = message.text.split(None, 1)[1]
  87. if is_downloading:
  88. return await message.reply_text(
  89. "Another download is in progress, try again after sometime."
  90. )
  91. is_downloading = True
  92. m = await message.reply_text(
  93. f"Downloading {url}", disable_web_page_preview=True
  94. )
  95. try:
  96. loop = get_running_loop()
  97. music = await loop.run_in_executor(
  98. None, partial(download_youtube_audio, url, message)
  99. )
  100. if not music:
  101. await m.edit("Too Long, Can't Download.")
  102. (
  103. title,
  104. performer,
  105. duration,
  106. audio_file,
  107. thumbnail_file,
  108. ) = music
  109. except Exception as e:
  110. is_downloading = False
  111. return await m.edit(str(e))
  112. await message.reply_audio(
  113. audio_file,
  114. duration=duration,
  115. performer=performer,
  116. title=title,
  117. thumb=thumbnail_file,
  118. )
  119. await m.delete()
  120. os.remove(audio_file)
  121. os.remove(thumbnail_file)
  122. is_downloading = False
  123. # Funtion To Download Song
  124. async def download_song(url):
  125. song_name = f"{randint(6969, 6999)}.mp3"
  126. async with aiohttp.ClientSession() as session:
  127. async with session.get(url) as resp:
  128. if resp.status != 200:
  129. return
  130. f = await aiofiles.open(song_name, mode="wb")
  131. await f.write(await resp.read())
  132. await f.close()
  133. return song_name
  134. # Jiosaavn Music
  135. @app.on_message(filters.command("saavn") & ~filters.edited)
  136. @capture_err
  137. async def jssong(_, message):
  138. global is_downloading
  139. if len(message.command) < 2:
  140. return await message.reply_text(
  141. "/saavn requires an argument."
  142. )
  143. if is_downloading:
  144. return await message.reply_text(
  145. "Another download is in progress, try again after sometime."
  146. )
  147. is_downloading = True
  148. text = message.text.split(None, 1)[1]
  149. m = await message.reply_text("Searching...")
  150. try:
  151. songs = await arq.saavn(text)
  152. if not songs.ok:
  153. await m.edit(songs.result)
  154. is_downloading = False
  155. return
  156. sname = songs.result[0].song
  157. slink = songs.result[0].media_url
  158. ssingers = songs.result[0].singers
  159. await m.edit("Downloading")
  160. song = await download_song(slink)
  161. await m.edit("Uploading")
  162. await message.reply_audio(
  163. audio=song,
  164. title=sname,
  165. performer=ssingers,
  166. )
  167. os.remove(song)
  168. await m.delete()
  169. except Exception as e:
  170. is_downloading = False
  171. return await m.edit(str(e))
  172. is_downloading = False
  173. # Deezer Music
  174. @app.on_message(filters.command("deezer") & ~filters.edited)
  175. @capture_err
  176. async def deezsong(_, message):
  177. global is_downloading
  178. if len(message.command) < 2:
  179. return await message.reply_text(
  180. "/deezer requires an argument."
  181. )
  182. if is_downloading:
  183. return await message.reply_text(
  184. "Another download is in progress, try again after sometime."
  185. )
  186. is_downloading = True
  187. text = message.text.split(None, 1)[1]
  188. m = await message.reply_text("Searching...")
  189. try:
  190. songs = await arq.deezer(text, 1, 9)
  191. if not songs.ok:
  192. await m.edit(songs.result)
  193. is_downloading = False
  194. return
  195. title = songs.result[0].title
  196. url = songs.result[0].url
  197. artist = songs.result[0].artist
  198. await m.edit("Downloading")
  199. proxy = "http://52.187.67.188:5000"
  200. try:
  201. song = await download_song(
  202. f"{proxy}/mirror?url={url}.mp3"
  203. )
  204. except Exception:
  205. song = await download_song(url)
  206. if not song:
  207. song = await download_song(url)
  208. await m.edit("Uploading")
  209. await message.reply_audio(
  210. audio=song,
  211. title=title,
  212. performer=artist,
  213. )
  214. os.remove(song)
  215. await m.delete()
  216. except Exception as e:
  217. is_downloading = False
  218. return await m.edit(str(e))
  219. is_downloading = False
  220. try:
  221. await get(f"{proxy}/remove")
  222. except Exception:
  223. pass
  224. # Lyrics
  225. @app.on_message(filters.command("lyrics"))
  226. async def lyrics_func(_, message):
  227. if len(message.command) < 2:
  228. return await message.reply_text("**Usage:**\n/lyrics [QUERY]")
  229. m = await message.reply_text("**Searching**")
  230. query = message.text.strip().split(None, 1)[1]
  231. song = await arq.lyrics(query)
  232. lyrics = song.result
  233. if len(lyrics) < 4095:
  234. return await m.edit(f"__{lyrics}__")
  235. lyrics = await paste(lyrics)
  236. await m.edit(f"**LYRICS_TOO_LONG:** [URL]({lyrics})")