music.py 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  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. __MODULE__ = "Music"
  35. __HELP__ = """/ytmusic [link] To Download Music From Various Websites Including Youtube. [SUDOERS]
  36. /saavn [query] To Download Music From Saavn.
  37. /deezer [query] To Download Music From Deezer.
  38. /lyrics [query] To Get Lyrics Of A Song."""
  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, m=0):
  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. await message.reply_text("/ytmusic needs a link as argument")
  81. return
  82. url = message.text.split(None, 1)[1]
  83. if is_downloading:
  84. await message.reply_text(
  85. "Another download is in progress, try again after sometime."
  86. )
  87. return
  88. is_downloading = True
  89. m = await message.reply_text(
  90. f"Downloading {url}", disable_web_page_preview=True
  91. )
  92. try:
  93. loop = get_running_loop()
  94. music = await loop.run_in_executor(None, partial(download_youtube_audio, url, message))
  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. await m.edit(str(e))
  107. return
  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. f = await aiofiles.open(song_name, mode="wb")
  126. await f.write(await resp.read())
  127. await f.close()
  128. return song_name
  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. await message.reply_text("/saavn requires an argument.")
  136. return
  137. if is_downloading:
  138. await message.reply_text(
  139. "Another download is in progress, try again after sometime."
  140. )
  141. return
  142. is_downloading = True
  143. text = message.text.split(None, 1)[1]
  144. query = text.replace(" ", "%20")
  145. m = await message.reply_text("Searching...")
  146. try:
  147. songs = await arq.saavn(query)
  148. if not songs.ok:
  149. await message.reply_text(songs.result)
  150. return
  151. sname = songs.result[0].song
  152. slink = songs.result[0].media_url
  153. ssingers = songs.result[0].singers
  154. await m.edit("Downloading")
  155. song = await download_song(slink)
  156. await m.edit("Uploading")
  157. await message.reply_audio(
  158. audio=song,
  159. title=sname,
  160. performer=ssingers,
  161. )
  162. os.remove(song)
  163. await m.delete()
  164. except Exception as e:
  165. is_downloading = False
  166. await m.edit(str(e))
  167. return
  168. is_downloading = False
  169. # Deezer Music
  170. @app.on_message(filters.command("deezer") & ~filters.edited)
  171. @capture_err
  172. async def deezsong(_, message):
  173. global is_downloading
  174. if len(message.command) < 2:
  175. await message.reply_text("/deezer requires an argument.")
  176. return
  177. if is_downloading:
  178. await message.reply_text(
  179. "Another download is in progress, try again after sometime."
  180. )
  181. return
  182. is_downloading = True
  183. text = message.text.split(None, 1)[1]
  184. query = text.replace(" ", "%20")
  185. m = await message.reply_text("Searching...")
  186. try:
  187. songs = await arq.deezer(query, 1)
  188. if not songs.ok:
  189. await message.reply_text(songs.result)
  190. return
  191. title = songs.result[0].title
  192. url = songs.result[0].url
  193. artist = songs.result[0].artist
  194. await m.edit("Downloading")
  195. song = await download_song(url)
  196. await m.edit("Uploading")
  197. await message.reply_audio(
  198. audio=song,
  199. title=title,
  200. performer=artist,
  201. )
  202. os.remove(song)
  203. await m.delete()
  204. except Exception as e:
  205. is_downloading = False
  206. await m.edit(str(e))
  207. return
  208. is_downloading = False
  209. # Lyrics
  210. @app.on_message(filters.command("lyrics"))
  211. async def lyrics_func(_, message):
  212. if len(message.command) < 2:
  213. await message.reply_text("**Usage:**\n/lyrics [QUERY]")
  214. return
  215. m = await message.reply_text("**Searching**")
  216. query = message.text.strip().split(None, 1)[1]
  217. song = await arq.lyrics(query)
  218. lyrics = song.result
  219. if len(lyrics) < 4095:
  220. await m.edit(f"__{lyrics}__")
  221. return
  222. lyrics = await paste(lyrics)
  223. await m.edit(f"**LYRICS_TOO_LONG:** [URL]({lyrics})")