music.py 7.2 KB

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