music.py 6.4 KB

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