music.py 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  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 random import randint
  23. from urllib.parse import urlparse
  24. import aiofiles
  25. import aiohttp
  26. import ffmpeg
  27. import youtube_dl
  28. from pyrogram import filters
  29. from wbb import SUDOERS, app, arq
  30. from wbb.core.decorators.errors import capture_err
  31. from wbb.utils.pastebin import paste
  32. __MODULE__ = "Music"
  33. __HELP__ = """/ytmusic [link] To Download Music From Various Websites Including Youtube. [SUDOERS]
  34. /saavn [query] To Download Music From Saavn.
  35. /deezer [query] To Download Music From Deezer.
  36. /lyrics [query] To Get Lyrics Of A Song."""
  37. is_downloading = False
  38. def get_file_extension_from_url(url):
  39. url_path = urlparse(url).path
  40. basename = os.path.basename(url_path)
  41. return basename.split(".")[-1]
  42. async def download_youtube_audio(url: str, m=0):
  43. global is_downloading
  44. with youtube_dl.YoutubeDL(
  45. {
  46. "format": "bestaudio",
  47. "writethumbnail": True,
  48. }
  49. ) as ydl:
  50. info_dict = ydl.extract_info(url, download=False)
  51. if int(float(info_dict["duration"])) > 600:
  52. if m != 0:
  53. await m.edit(
  54. "This music cannot be downloaded as it's too long."
  55. )
  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(
  77. filters.command("ytmusic") & ~filters.edited & filters.user(SUDOERS)
  78. )
  79. @capture_err
  80. async def music(_, message):
  81. global is_downloading
  82. if len(message.command) != 2:
  83. await message.reply_text("/ytmusic needs a link as argument")
  84. return
  85. url = message.text.split(None, 1)[1]
  86. if is_downloading:
  87. await message.reply_text(
  88. "Another download is in progress, try again after sometime."
  89. )
  90. return
  91. is_downloading = True
  92. m = await message.reply_text(
  93. f"Downloading {url}", disable_web_page_preview=True
  94. )
  95. try:
  96. (
  97. title,
  98. performer,
  99. duration,
  100. audio_file,
  101. thumbnail_file,
  102. ) = await download_youtube_audio(url, message)
  103. except Exception as e:
  104. is_downloading = False
  105. await m.edit(str(e))
  106. return
  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. song_name = f"{randint(6969, 6999)}.mp3"
  121. async with aiohttp.ClientSession() as session:
  122. async with session.get(url) as resp:
  123. if resp.status == 200:
  124. f = await aiofiles.open(song_name, mode="wb")
  125. await f.write(await resp.read())
  126. await f.close()
  127. return song_name
  128. # Jiosaavn Music
  129. @app.on_message(filters.command("saavn") & ~filters.edited)
  130. @capture_err
  131. async def jssong(_, message):
  132. global is_downloading
  133. if len(message.command) < 2:
  134. await message.reply_text("/saavn requires an argument.")
  135. return
  136. if is_downloading:
  137. await message.reply_text(
  138. "Another download is in progress, try again after sometime."
  139. )
  140. return
  141. is_downloading = True
  142. text = message.text.split(None, 1)[1]
  143. query = text.replace(" ", "%20")
  144. m = await message.reply_text("Searching...")
  145. try:
  146. songs = await arq.saavn(query)
  147. if not songs.ok:
  148. await message.reply_text(songs.result)
  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. await m.edit(str(e))
  166. return
  167. is_downloading = False
  168. # Deezer Music
  169. @app.on_message(filters.command("deezer") & ~filters.edited)
  170. @capture_err
  171. async def deezsong(_, message):
  172. global is_downloading
  173. if len(message.command) < 2:
  174. await message.reply_text("/deezer requires an argument.")
  175. return
  176. if is_downloading:
  177. await message.reply_text(
  178. "Another download is in progress, try again after sometime."
  179. )
  180. return
  181. is_downloading = True
  182. text = message.text.split(None, 1)[1]
  183. query = text.replace(" ", "%20")
  184. m = await message.reply_text("Searching...")
  185. try:
  186. songs = await arq.deezer(query, 1)
  187. if not songs.ok:
  188. await message.reply_text(songs.result)
  189. return
  190. title = songs.result[0].title
  191. url = songs.result[0].url
  192. artist = songs.result[0].artist
  193. await m.edit("Downloading")
  194. song = await download_song(url)
  195. await m.edit("Uploading")
  196. await message.reply_audio(
  197. audio=song,
  198. title=title,
  199. performer=artist,
  200. )
  201. os.remove(song)
  202. await m.delete()
  203. except Exception as e:
  204. is_downloading = False
  205. await m.edit(str(e))
  206. return
  207. is_downloading = False
  208. # Lyrics
  209. @app.on_message(filters.command("lyrics"))
  210. async def lyrics_func(_, message):
  211. if len(message.command) < 2:
  212. await message.reply_text("**Usage:**\n/lyrics [QUERY]")
  213. return
  214. m = await message.reply_text("**Searching**")
  215. query = message.text.strip().split(None, 1)[1]
  216. song = await arq.lyrics(query)
  217. lyrics = song.result
  218. if len(lyrics) < 4095:
  219. await m.edit(f"__{lyrics}__")
  220. return
  221. lyrics = await paste(lyrics)
  222. await m.edit(f"**LYRICS_TOO_LONG:** [URL]({lyrics})")