music.py 7.1 KB

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