Python Youtube ffmpeg会话已失效

时间:2019-01-11 01:22:54

标签: ffmpeg discord.py youtube-dl

在我的漫游器中播放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的重写分支。 我不确定是否需要提供更多详细信息?请让我知道,我真的需要修复此问题...

2 个答案:

答案 0 :(得分:0)

实际上,您的代码并不是真正的问题(很多人抱怨此错误)。

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

如果需要确保没有出现此问题,则必须完全下载音乐。 (这还会使机器人在游戏之前加载更长的时间。)

答案 1 :(得分:0)

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

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

您可以将下载设置为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

有点烂,但可以清理,这是我为我找到的最佳解决方案。