【问题标题】:Checking if a video is age restricted检查视频是否有年龄限制
【发布时间】:2021-01-13 08:13:21
【问题描述】:

您好,我如何能够搜索视频属性以检查视频是否有年龄限制,如果是则启动 if 语句

@commands.command()
    async def yt(self, ctx, *, search):
        query_string = urllib.parse.urlencode({'search_query': search})
        htm_content = urllib.request.urlopen('http://www.youtube.com/results?' + query_string)
        search_results = re.findall(r'/watch\?v=(.{11})',htm_content.read().decode())
        await ctx.send('http://www.youtube.com/watch?v=' + search_results[0])

一个小背景故事:我将我的机器人提交给 top.gg 这是一个机器人托管站点,但它被拒绝了,因为该机器人能够在非 NSFW 频道中发送“NSFW”内容,我真的很想继续工作非常感谢您的帮助

【问题讨论】:

    标签: python-3.x youtube discord discord.py youtube-data-api


    【解决方案1】:

    根据 YouTube 的数据 API 文档,您可以使用以下属性附加到有年龄限制的视频:

    contentDetails.contentRating.ytRating(字符串)

    YouTube 用来识别有年龄限制的内容的分级。

    此属性的有效值为:

    • ytAgeRestricted

    您必须调用Videos.list API 端点,将参数id 作为id=VIDEO_ID 传递给它,其中VIDEO_ID 是您感兴趣的视频的ID。也不要忘记让参数part 包含值contentDetails

    JSON 响应文本将包含您在 items[0].contentDetails.contentRating.ytRating 处所需的值;如果等于ytAgeRestricted,则应检查该值。另请注意,ytRating 属性很可能不存在;在这种情况下,视频不受年龄限制。


    在 Python 的上下文中,如果您使用的是 Google APIs Client Library for Python,那么您对 ​​Videos.list 端点的调用将如下所示:

    from googleapiclient.discovery import build
    youtube = build('youtube', 'v3', developerKey = APP_KEY)
    
    response = youtube.videos().list(
        id = VIDEO_ID,
        part = 'contentDetails',
        fields = 'items(contentDetails(contentRating(ytRating)))',
        maxResults = 1
    ).execute()
    
    age_restricted = response['items'][0] \
        ['contentDetails'] \
        ['contentRating'] \
        .get('ytRating') == \
        'ytAgeRestricted'
    

    请注意,上面的代码已大大简化,因为没有错误处理。

    另请注意,上面的代码使用参数fields 从端点获取ytRating 属性。从 API 中只询问真正需要的信息总是好的。

    【讨论】:

      猜你喜欢
      • 2012-10-08
      • 2021-05-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-22
      • 2016-12-02
      • 2022-11-10
      • 2012-03-21
      相关资源
      最近更新 更多