Skip to content

Instantly share code, notes, and snippets.

@JeffersGlass

JeffersGlass/youtube_stats.py Secret

Created Sep 13, 2020
Embed
What would you like to do?
import requests
import json
from natsort import natsorted, ns
from datetime import datetime, timedelta
from isodate import parse_duration
with open("ytkey.txt", 'r') as keyfile:
key = keyfile.readline()
jglassID = 'UCjgmTMVx2B5_DOB3bCZBq7A'
baseUrl = {'channels' : "https://www.googleapis.com/youtube/v3/channels",
'search' : "https://www.googleapis.com/youtube/v3/search",
'videos' : "https://www.googleapis.com/youtube/v3/videos"}
statsPayload = {'part':'statistics','id': jglassID, 'key':key}
print ("Channel stats")
print (requests.get(baseUrl['channels'], params=statsPayload).text)
searchPayload = {'part':'snippet','channelId': jglassID, 'order':'date',
'maxResults':'50','key':key}
result = requests.get(baseUrl['search'], params=searchPayload).json()
videoIDs = list()
for i in result['items']:
if i['id']['kind'] == "youtube#video":
videoIDs.append(i['id']['videoId'])
print (videoIDs[-1])
print ("Video IDs:" )
print (videoIDs)
viewCounts = list()
baseVideoPayload = {'channelId': jglassID, 'key':key}
for v in videoIDs:
thisVideoPayload = baseVideoPayload.copy()
thisVideoPayload['id'] = v
thisVideoPayload['part'] = 'snippet'
result = requests.get(baseUrl['videos'], params=thisVideoPayload).json()
name = result['items'][0]['snippet']['title']
thisVideoPayload['part'] = 'statistics'
result = requests.get(baseUrl['videos'], params=thisVideoPayload).json()
views = result['items'][0]['statistics']['viewCount']
thisVideoPayload['part'] = 'contentDetails'
result = requests.get(baseUrl['videos'], params=thisVideoPayload).json()
#print(result)
d = result['items'][0]['contentDetails']['duration']
if d != "P0D":
duration = parse_duration(d)
else: duration = None;
viewCounts.append({'name':name,'views':views,'duration':duration})
print ("Processed " + name)
sortedByViews = list(natsorted(viewCounts, key = lambda x: x['views']))
#sortedByViews.reverse()
totalTime = timedelta()
ebashTime = timedelta()
formatString = "{:<8}{:<60}{:<10}"
print(formatString.format("Views", "Name", "Duration"))
for v in sortedByViews:
if v['duration'] != None:
totalTime += v['duration']
if "electronics" in v['name'].lower():
ebashTime += v['duration']
print (formatString.format(v['views'],v['name'],str(v['duration'])))
#print ("Total Time: " + str(totalTime))
print ("Total E-Bash Class Time: " + str(ebashTime))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.