music.py 6.7 KB

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