Python Youtube ffmpeg 会话已失效

Python Youtube ffmpeg Session Has Been Invalidated

我在使用我的机器人播放 YouTube 音频时遇到以下错误

[tls @ 0000024ef8c4d480] Error in the pull function.
[matroska,webm @ 0000024ef8c4a400] Read error
[tls @ 0000024ef8c4d480] The specified session has been invalidated for some reason.
    Last message repeated 1 times

YouTube 链接好像过期了?我真的不知道,但我需要解决这个问题。这是我的代码:

    class YTDLSource(discord.PCMVolumeTransformer):

        def __init__(self, source, *, data, requester):
            super().__init__(source)
            self.requester = requester

            self.title = data['title']
            self.description = data['description']
            self.uploader = data['uploader']
            self.duration = data['duration']
            self.web_url = data['webpage_url']
            self.thumbnail = data['thumbnail']

        def __getitem__(self, item: str):
            return self.__getattribute__(item)

        @classmethod
        async def create_source(cls, ctx, player, search: str, *, loop, download=True):
            async with ctx.typing():
                loop = loop or asyncio.get_event_loop()
                to_run = partial(ytdl.extract_info, url=search, download=download)
                raw_data = await loop.run_in_executor(None, to_run)

                if 'entries' in raw_data:
                    # take first item from a playlist
                    if len(raw_data['entries']) == 1:
                        data = raw_data['entries'][0]
                    else:
                        data = raw_data['entries']
                        #loops entries to grab each video_url
                        total_duration = 0
                        try:
                            for i in data:
                                webpage = i['webpage_url']
                                title = i['title']
                                description = i['description']
                                uploader = i['uploader']
                                duration = i['duration']
                                thumbnail = i['thumbnail']
                                total_duration += duration

                                if download:
                                    source = ytdl.prepare_filename(i)
                                    source = cls(discord.FFmpegPCMAudio(source), data=i, requester=ctx.author)
                                else:
                                    source = {'webpage_url': webpage, 'requester': ctx.author, 'title': title, 'uploader': uploader, 'description': description, 'duration': duration, 'thumbnail': thumbnail}

                                player.queue.append(source)

                        except Exception as e:
                            print(e)
                            return

                        embed=discord.Embed(title="Playlist", description="Queued", color=0x30a4fb, timestamp=datetime.now(timezone.utc))
                        embed.set_author(name=ctx.author.display_name, icon_url=ctx.author.avatar_url)
                        embed.set_thumbnail(url=data[0]['thumbnail'])
                        embed.add_field(name=raw_data['title'], value=f"{len(data)} videos queued.", inline=True)
                        embed.set_footer(text=raw_data["uploader"] + ' - ' + '{0[0]}m {0[1]}s'.format(divmod(total_duration, 60)))
                        await ctx.send(embed=embed)
                        return

                embed=discord.Embed(title="Playlist", description="Queued", color=0x30a4fb, timestamp=datetime.now(timezone.utc))
                embed.set_author(name=ctx.author.display_name, icon_url=ctx.author.avatar_url)
                embed.set_thumbnail(url=data['thumbnail'])
                embed.add_field(name=data['title'], value=(data["description"][:72] + (data["description"][72:] and '...')), inline=True)
                embed.set_footer(text=data["uploader"] + ' - ' + '{0[0]}m {0[1]}s'.format(divmod(data["duration"], 60)))
                await ctx.send(embed=embed)

                if download:
                    source = ytdl.prepare_filename(data)
                else:
                    source = {'webpage_url': data['webpage_url'], 'requester': ctx.author, 'title': data['title'], 'uploader': data['uploader'], 'description': data['description'], 'duration': data['duration'], 'thumbnail': data['thumbnail']}
                    player.queue.append(source)
                    return

                source = cls(discord.FFmpegPCMAudio(source), data=data, requester=ctx.author)
                player.queue.append(source)


        @classmethod
        async def regather_stream(cls, data, *, loop):
            loop = loop or asyncio.get_event_loop()
            requester = data['requester']

            to_run = partial(ytdl.extract_info, url=data['webpage_url'], download=True)
            data = await loop.run_in_executor(None, to_run)

            return(cls(discord.FFmpegPCMAudio(data['url']), data=data, requester=requester))

我正在为机器人使用 discord.py 的重写分支。 我不确定是否需要提供更多详细信息?请让我知道,我真的需要解决这个问题...

实际上这并不是您的代码的问题(许多人抱怨此错误)。

这只是流式传输视频时可能出现的问题。如果你绝对想流式传输它,你必须接受这是一个潜在的问题。请注意(几乎)每个音乐机器人如何为您想听的 video/music 设置限制。

如果您需要确保不会遇到此问题,则必须完全下载音乐。 (这也会使机器人在播放前加载时间更长)。

你能post你所有的代码吗?如果我能够看到整个代码,我可能会为您提供解决方案。

我建议的解决方案是下载歌曲,然后将其删除。

您可以将下载设置为 true,然后将其添加到您的 player_loop

            try:
            # We are no longer playing this song...so, lets delete it!
            with YoutubeDL(ytdlopts) as ydl:
                info = ydl.extract_info(source.web_url, download=False)
                filename = ydl.prepare_filename(info)
                try:
                    if os.path.exists(filename):
                        os.remove(filename)
                    else:
                        pass
                except Exception as E:
                    print(E)
            await self.np.delete()
        except discord.HTTPException:
            pass

有点拙劣但可以清理,这是我找到的最好的解决方案。