music.py 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  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("This music cannot be downloaded as it's too long.")
  54. is_downloading = False
  55. return
  56. ydl.process_info(info_dict)
  57. audio_file = ydl.prepare_filename(info_dict)
  58. basename = audio_file.rsplit(".", 1)[-2]
  59. if info_dict["ext"] == "webm":
  60. audio_file_opus = basename + ".opus"
  61. ffmpeg.input(audio_file).output(
  62. audio_file_opus, codec="copy", loglevel="error"
  63. ).overwrite_output().run()
  64. os.remove(audio_file)
  65. audio_file = audio_file_opus
  66. thumbnail_url = info_dict["thumbnail"]
  67. thumbnail_file = basename + "." + get_file_extension_from_url(thumbnail_url)
  68. title = info_dict["title"]
  69. performer = info_dict["uploader"]
  70. duration = int(float(info_dict["duration"]))
  71. return [title, performer, duration, audio_file, thumbnail_file]
  72. @app.on_message(filters.command("ytmusic") & ~filters.edited & filters.user(SUDOERS))
  73. @capture_err
  74. async def music(_, message):
  75. global is_downloading
  76. if len(message.command) != 2:
  77. await message.reply_text("/ytmusic needs a link as argument")
  78. return
  79. url = message.text.split(None, 1)[1]
  80. if is_downloading:
  81. await message.reply_text(
  82. "Another download is in progress, try again after sometime."
  83. )
  84. return
  85. is_downloading = True
  86. m = await message.reply_text(f"Downloading {url}", disable_web_page_preview=True)
  87. try:
  88. (
  89. title,
  90. performer,
  91. duration,
  92. audio_file,
  93. thumbnail_file,
  94. ) = await download_youtube_audio(url, message)
  95. except Exception as e:
  96. is_downloading = False
  97. await m.edit(str(e))
  98. return
  99. await message.reply_audio(
  100. audio_file,
  101. duration=duration,
  102. performer=performer,
  103. title=title,
  104. thumb=thumbnail_file,
  105. )
  106. await m.delete()
  107. os.remove(audio_file)
  108. os.remove(thumbnail_file)
  109. is_downloading = False
  110. # Funtion To Download Song
  111. async def download_song(url):
  112. song_name = f"{randint(6969, 6999)}.mp3"
  113. async with aiohttp.ClientSession() as session:
  114. async with session.get(url) as resp:
  115. if resp.status == 200:
  116. f = await aiofiles.open(song_name, mode="wb")
  117. await f.write(await resp.read())
  118. await f.close()
  119. return song_name
  120. # Jiosaavn Music
  121. @app.on_message(filters.command("saavn") & ~filters.edited)
  122. @capture_err
  123. async def jssong(_, message):
  124. global is_downloading
  125. if len(message.command) < 2:
  126. await message.reply_text("/saavn requires an argument.")
  127. return
  128. if is_downloading:
  129. await message.reply_text(
  130. "Another download is in progress, try again after sometime."
  131. )
  132. return
  133. is_downloading = True
  134. text = message.text.split(None, 1)[1]
  135. query = text.replace(" ", "%20")
  136. m = await message.reply_text("Searching...")
  137. try:
  138. songs = await arq.saavn(query)
  139. sname = songs[0].song
  140. slink = songs[0].media_url
  141. ssingers = songs[0].singers
  142. await m.edit("Downloading")
  143. song = await download_song(slink)
  144. await m.edit("Uploading")
  145. await message.reply_audio(
  146. audio=song,
  147. title=sname,
  148. performer=ssingers,
  149. )
  150. os.remove(song)
  151. await m.delete()
  152. except Exception as e:
  153. is_downloading = False
  154. await m.edit(str(e))
  155. return
  156. is_downloading = False
  157. # Deezer Music
  158. @app.on_message(filters.command("deezer") & ~filters.edited)
  159. @capture_err
  160. async def deezsong(_, message):
  161. global is_downloading
  162. if len(message.command) < 2:
  163. await message.reply_text("/deezer requires an argument.")
  164. return
  165. if is_downloading:
  166. await message.reply_text(
  167. "Another download is in progress, try again after sometime."
  168. )
  169. return
  170. is_downloading = True
  171. text = message.text.split(None, 1)[1]
  172. query = text.replace(" ", "%20")
  173. m = await message.reply_text("Searching...")
  174. try:
  175. songs = await arq.deezer(query, 1)
  176. title = songs[0].title
  177. url = songs[0].url
  178. artist = songs[0].artist
  179. await m.edit("Downloading")
  180. song = await download_song(url)
  181. await m.edit("Uploading")
  182. await message.reply_audio(
  183. audio=song,
  184. title=title,
  185. performer=artist,
  186. )
  187. os.remove(song)
  188. await m.delete()
  189. except Exception as e:
  190. is_downloading = False
  191. await m.edit(str(e))
  192. return
  193. is_downloading = False
  194. # Lyrics
  195. @app.on_message(filters.command("lyrics"))
  196. async def lyrics_func(_, message):
  197. if len(message.command) < 2:
  198. await message.reply_text("**Usage:**\n/lyrics [QUERY]")
  199. return
  200. m = await message.reply_text("**Searching**")
  201. query = message.text.strip().split(None, 1)[1]
  202. song = await arq.lyrics(query)
  203. lyrics = song.lyrics
  204. if len(lyrics) < 4095:
  205. await m.edit(f"__{lyrics}__")
  206. return
  207. lyrics = await paste(lyrics)
  208. await m.edit(f"**LYRICS_TOO_LONG:** [URL]({lyrics})")