首页 > 解决方案 > discord.py 音乐机器人中的一个奇怪错误

问题描述

我正在制作一个可以播放音乐的 discord.py 机器人。当我在本地计算机上运行它时,有时一切正常,但有时当我尝试使用播放列表运行它时,它只是无法在播放列表中找到歌曲。

这是播放命令:

@commands.command(name='play',aliases=["p","sing"])
async def _play(self, ctx: commands.Context, *, song1: str):
    """Plays a song.
    If there are songs in the queue, this will be queued until the
    other songs finished playing.
    This command automatically searches from various sites if no URL is provided.
    A list of these sites can be found here: https://rg3.github.io/youtube-dl/supportedsites.html
    """

    if not ctx.voice_state.voice:
        await ctx.invoke(self._join)
    x = False
    if "playlist?" not in song1:
        songs = [song1]
    else:
        x = True
        """html_content = urllib.request.urlopen(song1)
        html_content = html_content.read().decode()"""
        r = requests.get(song1)
        html_content = r.text
        pattern = "href=\"\/watch\?v=(.{11})"
        songs = re.findall(pattern,html_content)
        print(f"Before: {songs}")

        songs = list(dict.fromkeys(songs))
        print(f"after: {songs}")
            #songs.append(f"https://www.youtube.com/watch?v={code}")

    for search in songs:
        s = search if not x else f"https://www.youtube.com/watch?v={search}"
        try:

            source = await YTDLSource.create_source(ctx, s, loop=self.bot.loop)
        except YTDLError as e:
            await ctx.send('An error occurred while processing this request: {}'.format(str(e)))
        else:
            song = Song(source)

            await ctx.voice_state.songs.put(song)
            if not x:
                await ctx.send('Enqueued {}'.format(str(source)))
    if x:
        await ctx.send(f"Succesfully queued the playlist `{song1}`")

这是控制台中的内容

我运行的命令不和谐:

pplay https://www.youtube.com/playlist?list=PL2n_fVXKImKlfv3PlcHZTzLk3CoGUV9Hm

工作时输出:

Before: ['gEbRqpFkTBk', 'gEbRqpFkTBk', 'gEbRqpFkTBk', 'gEbRqpFkTBk', '4ZvnbsfXRk0', '4ZvnbsfXRk0', 'besNDPvEwQw', 'besNDPvEwQw', 'QglaLzo_aPk', 'QglaLzo_aPk', 'YJTae5ScvQA', 'YJTae5ScvQA', '9Va88Kt0NN0', '9Va88Kt0NN0']
after: ['gEbRqpFkTBk', '4ZvnbsfXRk0', 'besNDPvEwQw', 'QglaLzo_aPk', 'YJTae5ScvQA', '9Va88Kt0NN0']

大部分时间输出:

Before: []
after: []

它没有给出任何错误。

标签: python-3.xpython-requestsdiscord.pyre

解决方案


您可以使用extract_infoyoutube-dl 中的方法:

video_list = []

with youtube_dl.YoutubeDL() as ydl:
    playlist = ydl.extract_info(url='playlist url', download=False)['entries']

for video in playlist:
    video_list.append(video['webpage_url'])

video_list将包含播放列表视频中的每个 URL。


推荐阅读