-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtwitch.py
78 lines (61 loc) · 2.24 KB
/
twitch.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import requests
import json
import datetime
import os
import sys
import time
if os.path.exists("auth.json"):
f = open('auth.json')
auth_json = json.load(f)
TWITCH_CLIENT_ID = auth_json["TWITCH_CLIENT_ID"]
TWITCH_CLIENT_SECRET = auth_json["TWITCH_CLIENT_SECRET"]
else:
TWITCH_CLIENT_ID = os.environ.get("TWITCH_CLIENT_ID")
TWITCH_CLIENT_SECRET = os.environ.get("TWITCH_CLIENT_SECRET")
r = requests.post('https://id.twitch.tv/oauth2/token?client_id='+TWITCH_CLIENT_ID +
'&client_secret='+TWITCH_CLIENT_SECRET+'&grant_type=client_credentials')
resp = json.loads(r.text)
token = resp.get("access_token", None)
def get_clips(twitch_game_name):
r = requests.get(
"https://api.twitch.tv/helix/games?name="+twitch_game_name,
headers={
'Authorization': 'Bearer '+token,
'Client-Id': TWITCH_CLIENT_ID
}
)
resp = json.loads(r.text)
print(resp)
gameId = resp["data"][0]["id"]
clips = {}
for j in range(7):
print(str(j) + " days back")
startTime = (datetime.datetime.utcnow() -
datetime.timedelta(days=(j+2))).isoformat("T") + "Z"
endTime = (datetime.datetime.utcnow() -
datetime.timedelta(days=(j+1))).isoformat("T") + "Z"
print(startTime)
print(endTime)
pagination = ""
for i in range(10):
r = requests.get(
"https://api.twitch.tv/helix/clips?game_id=" +
str(gameId)+"&started_at="+startTime+"&ended_at=" +
endTime+"&first=100&after="+pagination,
headers={
'Authorization': 'Bearer '+token,
'Client-Id': TWITCH_CLIENT_ID
}
)
resp = json.loads(r.text)
pagination = resp.get("pagination", {}).get("cursor", None)
for c in resp.get("data", {}):
if c["language"] not in clips:
clips[c["language"]] = []
clips[c["language"]].append(c)
print(i, end="\r")
if pagination == None:
break
for lang in clips.keys():
clips[lang].sort(key=lambda clip: clip["view_count"], reverse=True)
return clips