【问题标题】:Python Youtube ffmpeg Session Has Been InvalidatedPython Youtube ffmpeg 会话已失效
【发布时间】:2019-06-05 22:35:54
【问题描述】:

我在使用机器人播放 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 的重写分支。 我不确定是否需要提供更多详细信息?请告诉我,我真的需要解决这个问题...

【问题讨论】:

  • 您尝试流式传输的音频的长度和质量是多少?

标签: ffmpeg discord.py youtube-dl


【解决方案1】:

事实上,你的代码并不是真正的问题(很多人抱怨这个错误)。

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

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

【讨论】:

  • 我看到你回答了你自己的问题,你能详细说明你是如何得出结论的吗?我是否正确地阅读它说问题不在于链接到期,而是 YouTube 正在终止连接,因为它认为您的代码是机器人?如果是这样,依据是什么?
  • 这不是我自己的问题,我只是编辑了它。它与 YouTube 的任何“检测”无关(尽管出于流/下载目的使用 youtube_dl 违反了 Youtube 服务条款)。
【解决方案2】:

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

我推荐的解决方案是下载这首歌曲,然后再将其删除。

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

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

【讨论】:

    猜你喜欢
    • 2023-03-26
    • 2013-08-29
    • 2012-02-11
    • 2018-09-28
    • 2013-06-29
    • 1970-01-01
    • 2020-06-23
    • 2015-04-26
    • 2017-05-24
    相关资源
    最近更新 更多