Checking if a video is age restricted

1k Views Asked by At

Hello how am I able to search for video attributes to check if a video is an age-restricted and if it is then it launches an if statement

@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])

A little backstory: I submitted my bot to top.gg which is a bot hosting site and it got declined because the bot was able to send "NSFW" content in non NSFW channels, I really want to get with working so all help is much appreciated

1

There are 1 best solutions below

0
stvar On

According to YouTube's Data API docs, you have at your disposal the following property attached to age-restricted videos:

contentDetails.contentRating.ytRating (string)

A rating that YouTube uses to identify age-restricted content.

Valid values for this property are:

  • ytAgeRestricted

You'll have to invoke the Videos.list API endpoint, passing to it the parameter id as id=VIDEO_ID, where VIDEO_ID is the ID of the video of your interest. Also need not forget to have the parameter part containing the value contentDetails.

The JSON response text will contain the value you need at items[0].contentDetails.contentRating.ytRating; that value should be checked if equals with ytAgeRestricted. Note also that the property ytRating may well be absent; in this case the video is not age-restricted.


In the context of Python, if you're using the Google APIs Client Library for Python, then your call to the Videos.list endpoint would look like:

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'

Note that the code above is simplified quite much since there's no error handling.

Also note that the code above is using the parameter fields for to obtain from the endpoint only the ytRating property. It's always good to ask from the API only the info that is really needed.