music.py 7.5 KB

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