File size: 19,266 Bytes
5980447
1
2
{"repo": "Raptor123471/DingoLingo", "pull_number": 29, "instance_id": "Raptor123471__DingoLingo-29", "issue_numbers": "", "base_commit": "7f240327378e1aab157aed6ee9185674c15926ad", "patch": "diff --git a/config/config.py b/config/config.py\n--- a/config/config.py\n+++ b/config/config.py\n@@ -8,6 +8,8 @@\n \n SUPPORTED_EXTENSIONS = ('.webm', '.mp4', '.mp3', '.avi', '.wav', '.m4v', '.ogg', '.mov')\n \n+MAX_SONG_PRELOAD = 5  #maximum of 25\n+\n COOKIE_PATH = \"/config/cookies/cookies.txt\"\n \n STARTUP_MESSAGE = \"Starting Bot...\"\ndiff --git a/musicbot/audiocontroller.py b/musicbot/audiocontroller.py\n--- a/musicbot/audiocontroller.py\n+++ b/musicbot/audiocontroller.py\n@@ -1,5 +1,8 @@\n import discord\n-import youtube_dlc\n+import youtube_dl\n+\n+import asyncio\n+import concurrent.futures\n \n from musicbot import linkutils\n from musicbot import utils\n@@ -67,12 +70,12 @@ def next_song(self, error):\n     async def play_song(self, song):\n         \"\"\"Plays a song object\"\"\"\n \n-        if song.origin == linkutils.Origins.Playlist:\n+        if song.info.title == None:\n             if song.host == linkutils.Sites.Spotify:\n-                conversion = await self.search_youtube(linkutils.convert_spotify(song.info.webpage_url))\n+                conversion = self.search_youtube(await linkutils.convert_spotify(song.info.webpage_url))\n                 song.info.webpage_url = conversion\n \n-            downloader = youtube_dlc.YoutubeDL(\n+            downloader = youtube_dl.YoutubeDL(\n                 {'format': 'bestaudio', 'title': True, \"cookiefile\": config.COOKIE_PATH})\n             r = downloader.extract_info(\n                 song.info.webpage_url, download=False)\n@@ -94,6 +97,11 @@ async def play_song(self, song):\n             self.guild.voice_client.source)\n         self.voice_client.source.volume = float(self.volume) / 100.0\n \n+        self.playlist.playque.popleft()\n+\n+        for song in list(self.playlist.playque)[:config.MAX_SONG_PRELOAD]:\n+            asyncio.ensure_future(self.preload(song))\n+\n     async def process_song(self, track):\n         \"\"\"Adds the track to the playlist instance and plays it, if it is the first song\"\"\"\n \n@@ -102,11 +110,9 @@ async def process_song(self, track):\n \n         if is_playlist != linkutils.Playlist_Types.Unknown:\n \n-            queue_scan = len(self.playlist.playque)\n-\n             await self.process_playlist(is_playlist, track)\n \n-            if queue_scan == 0:\n+            if self.current_song == None:\n                 await self.play_song(self.playlist.playque[0])\n                 print(\"Playing {}\".format(track))\n \n@@ -118,22 +124,22 @@ async def process_song(self, track):\n             if linkutils.get_url(track) is not None:\n                 return None\n \n-            track = await self.search_youtube(track)\n+            track = self.search_youtube(track)\n \n         if host == linkutils.Sites.Spotify:\n-            title = linkutils.convert_spotify(track)\n-            track = await self.search_youtube(title)\n+            title = await linkutils.convert_spotify(track)\n+            track = self.search_youtube(title)\n \n         if host == linkutils.Sites.YouTube:\n             track = track.split(\"&list=\")[0]\n \n         try:\n-            downloader = youtube_dlc.YoutubeDL(\n+            downloader = youtube_dl.YoutubeDL(\n                 {'format': 'bestaudio', 'title': True, \"cookiefile\": config.COOKIE_PATH})\n             r = downloader.extract_info(\n                 track, download=False)\n         except:\n-            downloader = youtube_dlc.YoutubeDL(\n+            downloader = youtube_dl.YoutubeDL(\n                 {'title': True, \"cookiefile\": config.COOKIE_PATH})\n             r = downloader.extract_info(\n                 track, download=False)\n@@ -148,7 +154,7 @@ async def process_song(self, track):\n             'title'), duration=r.get('duration'), webpage_url=r.get('webpage_url'), thumbnail=thumbnail)\n \n         self.playlist.add(song)\n-        if len(self.playlist.playque) == 1:\n+        if self.current_song == None:\n             print(\"Playing {}\".format(track))\n             await self.play_song(song)\n \n@@ -171,7 +177,7 @@ async def process_playlist(self, playlist_type, url):\n                 \"cookiefile\": config.COOKIE_PATH\n             }\n \n-            with youtube_dlc.YoutubeDL(options) as ydl:\n+            with youtube_dl.YoutubeDL(options) as ydl:\n                 r = ydl.extract_info(url, download=False)\n \n                 for entry in r['entries']:\n@@ -185,7 +191,7 @@ async def process_playlist(self, playlist_type, url):\n                     self.playlist.add(song)\n \n         if playlist_type == linkutils.Playlist_Types.Spotify_Playlist:\n-            links = linkutils.get_spotify_playlist(url)\n+            links = await linkutils.get_spotify_playlist(url)\n             for link in links:\n                 song = Song(linkutils.Origins.Playlist,\n                             linkutils.Sites.Spotify, webpage_url=link)\n@@ -196,7 +202,7 @@ async def process_playlist(self, playlist_type, url):\n                 'format': 'bestaudio/best',\n                 'extract_flat': True\n             }\n-            with youtube_dlc.YoutubeDL(options) as ydl:\n+            with youtube_dl.YoutubeDL(options) as ydl:\n                 r = ydl.extract_info(url, download=False)\n \n                 for entry in r['entries']:\n@@ -208,7 +214,38 @@ async def process_playlist(self, playlist_type, url):\n \n                     self.playlist.add(song)\n \n-    async def search_youtube(self, title):\n+        for song in list(self.playlist.playque)[:config.MAX_SONG_PRELOAD]:\n+            asyncio.ensure_future(self.preload(song))\n+\n+    async def preload(self, song):\n+\n+        if song.info.title != None:\n+            return\n+\n+        def down(song):\n+\n+            if song.host == linkutils.Sites.Spotify:\n+                song.info.webpage_url = self.search_youtube(song.info.title)\n+\n+            downloader = youtube_dl.YoutubeDL(\n+                {'format': 'bestaudio', 'title': True, \"cookiefile\": config.COOKIE_PATH})\n+            r = downloader.extract_info(\n+                song.info.webpage_url, download=False)\n+            song.base_url = r.get('url')\n+            song.info.uploader = r.get('uploader')\n+            song.info.title = r.get('title')\n+            song.info.duration = r.get('duration')\n+            song.info.webpage_url = r.get('webpage_url')\n+            song.info.thumbnail = r.get('thumbnails')[0]['url']\n+\n+        if song.host == linkutils.Sites.Spotify:\n+            song.info.title = await linkutils.convert_spotify(song.info.webpage_url)\n+\n+        loop = asyncio.get_event_loop()\n+        executor = concurrent.futures.ThreadPoolExecutor(max_workers=config.MAX_SONG_PRELOAD)\n+        await asyncio.wait(fs={loop.run_in_executor(executor, down, song)}, return_when=asyncio.ALL_COMPLETED)\n+\n+    def search_youtube(self, title):\n         \"\"\"Searches youtube for the video title and returns the first results video link\"\"\"\n \n         # if title is already a link\n@@ -222,7 +259,7 @@ async def search_youtube(self, title):\n             \"cookiefile\": config.COOKIE_PATH\n         }\n \n-        with youtube_dlc.YoutubeDL(options) as ydl:\n+        with youtube_dl.YoutubeDL(options) as ydl:\n             r = ydl.extract_info(title, download=False)\n \n         videocode = r['entries'][0]['id']\ndiff --git a/musicbot/commands/general.py b/musicbot/commands/general.py\n--- a/musicbot/commands/general.py\n+++ b/musicbot/commands/general.py\n@@ -115,7 +115,7 @@ async def _change_channel(self, ctx):\n     async def _ping(self, ctx):\n         await ctx.send(\"Pong\")\n \n-    @commands.command(name='setting', description=config.HELP_SHUFFLE_LONG, help=config.HELP_SETTINGS_SHORT, aliases=['settings', 'set', 'st'])\n+    @commands.command(name='setting', description=config.HELP_SHUFFLE_LONG, help=config.HELP_SETTINGS_SHORT, aliases=['settings', 'set'])\n     @has_permissions(administrator=True)\n     async def _settings(self, ctx, *args):\n \ndiff --git a/musicbot/commands/music.py b/musicbot/commands/music.py\n--- a/musicbot/commands/music.py\n+++ b/musicbot/commands/music.py\n@@ -1,13 +1,14 @@\n import discord\n from discord.ext import commands\n \n+import asyncio\n+\n from musicbot import utils\n from musicbot import linkutils\n from config import config\n \n from musicbot.commands.general import General\n \n-import requests\n import datetime\n \n \n@@ -21,7 +22,7 @@ class Music(commands.Cog):\n     def __init__(self, bot):\n         self.bot = bot\n \n-    @commands.command(name='play', description=config.HELP_YT_LONG, help=config.HELP_YT_SHORT, aliases=['p', 'yt', 'P', 'pl'])\n+    @commands.command(name='play', description=config.HELP_YT_LONG, help=config.HELP_YT_SHORT, aliases=['p', 'yt', 'pl'])\n     async def _play_song(self, ctx, *, track: str):\n \n         if(await utils.is_connected(ctx) == None):\n@@ -47,7 +48,7 @@ async def _play_song(self, ctx, *, track: str):\n \n         if song.origin == linkutils.Origins.Default:\n \n-            if len(audiocontroller.playlist.playque) == 1:\n+            if audiocontroller.current_song != None and len(audiocontroller.playlist.playque) == 0:\n                 await ctx.send(embed=song.info.format_output(config.SONGINFO_NOW_PLAYING))\n             else:\n                 await ctx.send(embed=song.info.format_output(config.SONGINFO_QUEUE_ADDED))\n@@ -55,7 +56,7 @@ async def _play_song(self, ctx, *, track: str):\n         elif song.origin == linkutils.Origins.Playlist:\n             await ctx.send(config.SONGINFO_PLAYLIST_QUEUED)\n \n-    @commands.command(name='loop', description=config.HELP_LOOP_LONG, help=config.HELP_LOOP_SHORT, aliases=['l', 'L'])\n+    @commands.command(name='loop', description=config.HELP_LOOP_LONG, help=config.HELP_LOOP_SHORT, aliases=['l'])\n     async def _loop(self, ctx):\n \n         current_guild = utils.get_guild(self.bot, ctx.message)\n@@ -93,6 +94,9 @@ async def _shuffle(self, ctx):\n         audiocontroller.playlist.shuffle()\n         await ctx.send(\"Shuffled queue :twisted_rightwards_arrows:\")\n \n+        for song in list(audiocontroller.playlist.playque)[:config.MAX_SONG_PRELOAD]:\n+            asyncio.ensure_future(audiocontroller.preload(song))\n+\n     @commands.command(name='pause', description=config.HELP_PAUSE_LONG, help=config.HELP_PAUSE_SHORT)\n     async def _pause(self, ctx):\n         current_guild = utils.get_guild(self.bot, ctx.message)\n@@ -108,7 +112,7 @@ async def _pause(self, ctx):\n         current_guild.voice_client.pause()\n         await ctx.send(\"Playback Paused :pause_button:\")\n \n-    @commands.command(name='queue', description=config.HELP_QUEUE_LONG, help=config.HELP_QUEUE_SHORT, aliases=['playlist', 'q', 'Q'])\n+    @commands.command(name='queue', description=config.HELP_QUEUE_LONG, help=config.HELP_QUEUE_SHORT, aliases=['playlist', 'q'])\n     async def _queue(self, ctx):\n         current_guild = utils.get_guild(self.bot, ctx.message)\n \n@@ -124,13 +128,17 @@ async def _queue(self, ctx):\n \n         playlist = utils.guild_to_audiocontroller[current_guild].playlist\n \n+        #Embeds are limited to 25 fields\n+        if config.MAX_SONG_PRELOAD > 25:\n+            config.MAX_SONG_PRELOAD = 25\n+\n         embed = discord.Embed(title=\":scroll: Queue [{}]\".format(\n             len(playlist.playque)), color=config.EMBED_COLOR, inline=False)\n \n         counter = 1\n-        for song in list(playlist.playque)[:10]:\n+        for song in list(playlist.playque)[:config.MAX_SONG_PRELOAD]:\n             if song.info.title is None:\n-                embed.add_field(name=\"{}.\".format(str(counter)), value=\"[(PL) | {}]({})\".format(\n+                embed.add_field(name=\"{}.\".format(str(counter)), value=\"[{}]({})\".format(\n                     song.info.webpage_url, song.info.webpage_url), inline=False)\n             else:\n                 embed.add_field(name=\"{}.\".format(str(counter)), value=\"[{}]({})\".format(\n@@ -139,7 +147,7 @@ async def _queue(self, ctx):\n \n         await ctx.send(embed=embed)\n \n-    @commands.command(name='stop', description=config.HELP_STOP_LONG, help=config. HELP_STOP_SHORT)\n+    @commands.command(name='stop', description=config.HELP_STOP_LONG, help=config. HELP_STOP_SHORT, aliases=['st'])\n     async def _stop(self, ctx):\n         current_guild = utils.get_guild(self.bot, ctx.message)\n \n@@ -154,7 +162,7 @@ async def _stop(self, ctx):\n         await utils.guild_to_audiocontroller[current_guild].stop_player()\n         await ctx.send(\"Stopped all sessions :octagonal_sign:\")\n \n-    @commands.command(name='skip', description=config.HELP_SKIP_LONG, help=config.HELP_SKIP_SHORT, aliases=['s', 'S'])\n+    @commands.command(name='skip', description=config.HELP_SKIP_LONG, help=config.HELP_SKIP_SHORT, aliases=['s'])\n     async def _skip(self, ctx):\n         current_guild = utils.get_guild(self.bot, ctx.message)\n \ndiff --git a/musicbot/linkutils.py b/musicbot/linkutils.py\n--- a/musicbot/linkutils.py\n+++ b/musicbot/linkutils.py\n@@ -1,4 +1,4 @@\n-import requests\n+import aiohttp\n import re\n from bs4 import BeautifulSoup\n from enum import Enum\n@@ -15,6 +15,12 @@\n except:\n     api = False\n \n+url_regex = re.compile(\n+    \"http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\\(\\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+\")\n+\n+session = aiohttp.ClientSession(\n+    headers={'User-Agent': 'python-requests/2.20.0'})\n+\n \n def clean_sclink(track):\n     if track.startswith(\"https://m.\"):\n@@ -24,25 +30,25 @@ def clean_sclink(track):\n     return track\n \n \n-def convert_spotify(url):\n-    regex = re.compile(\n-        \"http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\\(\\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+\")\n+async def convert_spotify(url):\n \n-    if re.search(regex, url):\n-        result = regex.search(url)\n+    if re.search(url_regex, url):\n+        result = url_regex.search(url)\n         url = result.group(0)\n \n-    page = requests.get(url)\n-    soup = BeautifulSoup(page.content, 'html.parser')\n+    async with session.get(url) as response:\n \n-    title = soup.find('title')\n-    title = title.string\n-    title = title.replace(', a song by', '').replace(' on Spotify', '')\n+        page = await response.text()\n+        soup = BeautifulSoup(page, 'html.parser')\n+\n+        title = soup.find('title')\n+        title = title.string\n+        title = title.replace('Spotify \u2013 ', '')\n \n-    return title\n+        return title\n \n \n-def get_spotify_playlist(url):\n+async def get_spotify_playlist(url):\n     \"\"\"Return Spotify_Playlist class\"\"\"\n \n     code = url.split('/')[4].split('?')[0]\n@@ -92,11 +98,10 @@ def get_spotify_playlist(url):\n                 if config.SPOTIFY_ID != \"\" or config.SPOTIFY_SECRET != \"\":\n                     print(\"ERROR: Check spotify CLIENT_ID and SECRET\")\n \n-    headers = {\n-        \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36\"}\n+    async with session.get(url) as response:\n+         page = await response.text()\n \n-    page = requests.get(url, headers=headers)\n-    soup = BeautifulSoup(page.content, 'html.parser')\n+    soup = BeautifulSoup(page, 'html.parser')\n \n     results = soup.find_all(property=\"music:song\", attrs={\"content\": True})\n \n@@ -157,7 +162,7 @@ def identify_url(url):\n     if \"https://open.spotify.com/track\" in url:\n         return Sites.Spotify\n \n-    if \"https://open.spotify.com/playlist\"in url or \"https://open.spotify.com/album\" in url:\n+    if \"https://open.spotify.com/playlist\" in url or \"https://open.spotify.com/album\" in url:\n         return Sites.Spotify_Playlist\n \n     if \"bandcamp.com/track/\" in url:\n@@ -183,7 +188,7 @@ def identify_playlist(url):\n     if \"playlist?list=\" in url:\n         return Playlist_Types.YouTube_Playlist\n \n-    if \"https://open.spotify.com/playlist\"in url or \"https://open.spotify.com/album\" in url:\n+    if \"https://open.spotify.com/playlist\" in url or \"https://open.spotify.com/album\" in url:\n         return Playlist_Types.Spotify_Playlist\n \n     if \"bandcamp.com/album/\" in url:\ndiff --git a/musicbot/playlist.py b/musicbot/playlist.py\n--- a/musicbot/playlist.py\n+++ b/musicbot/playlist.py\n@@ -33,7 +33,7 @@ def next(self):\n         if len(self.playque) == 0:\n             return None\n \n-        song_played = self.playque.popleft()\n+        song_played = self.playque[0]\n \n         if self.loop == True:\n             if song_played != \"Dummy\":\ndiff --git a/musicbot/songinfo.py b/musicbot/songinfo.py\n--- a/musicbot/songinfo.py\n+++ b/musicbot/songinfo.py\n@@ -1,6 +1,7 @@\n import discord\n from discord.ext import commands\n from config import config\n+import datetime\n \n \n class Song():\n@@ -22,8 +23,7 @@ def __init__(self, uploader, title, duration, webpage_url, thumbnail):\n \n         def format_output(self, playtype):\n \n-            embed = discord.Embed(title=\":musical_note:  __**{}**__  :musical_note:\".format(\n-                self.title), description=\"***{}***\".format(playtype), url=self.webpage_url, color=config.EMBED_COLOR)\n+            embed = discord.Embed(title=playtype, description=\"[{}]({})\".format(self.title, self.webpage_url), color=config.EMBED_COLOR)\n \n             if self.thumbnail is not None:\n                 embed.set_thumbnail(url=self.thumbnail)\n@@ -31,11 +31,9 @@ def format_output(self, playtype):\n             embed.add_field(name=config.SONGINFO_UPLOADER,\n                             value=self.uploader, inline=False)\n \n-            print(self.duration)\n-\n             if self.duration is not None:\n                 embed.add_field(name=config.SONGINFO_DURATION,\n-                                value=\"{}{}\".format(self.duration, config.SONGINFO_SECONDS), inline=False)\n+                                value=\"{}\".format(str(datetime.timedelta(seconds=self.duration))), inline=False)\n             else:\n                 embed.add_field(name=config.SONGINFO_DURATION,\n                                 value=config.SONGINFO_UNKNOWN_DURATION , inline=False)\ndiff --git a/musicbot/utils.py b/musicbot/utils.py\n--- a/musicbot/utils.py\n+++ b/musicbot/utils.py\n@@ -49,7 +49,6 @@ async def connect_to_channel(guild, dest_channel_name, ctx, switch=False, defaul\n async def is_connected(ctx):\n     try:\n         voice_channel = ctx.guild.voice_client.channel\n-        print(voice_channel)\n         return voice_channel\n     except:\n         return None\ndiff --git a/run.py b/run.py\n--- a/run.py\n+++ b/run.py\n@@ -13,7 +13,7 @@\n \n initial_extensions = ['musicbot.commands.music',\n                       'musicbot.commands.general', 'musicbot.plugins.button']\n-bot = commands.Bot(command_prefix=config.BOT_PREFIX, pm_help=True)\n+bot = commands.Bot(command_prefix=config.BOT_PREFIX, pm_help=True, case_insensitive=True)\n \n \n if __name__ == '__main__':\n", "test_patch": "", "problem_statement": "", "hints_text": "", "created_at": "2021-03-21T02:38:53Z"}