-
Notifications
You must be signed in to change notification settings - Fork 0
/
twitch_rest_api.py
372 lines (324 loc) · 12.4 KB
/
twitch_rest_api.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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
import secrets
from pprint import pprint
from datetime import datetime
from dateutil.relativedelta import relativedelta
import requests
import yaml
TWTICH = "twitch"
CLIENT_ID = "client_id"
CLIENT_SECRET = "client_secret"
REDIRECT_URI = "oauth_redirect_uri"
CALLBACK_URI = "eventsub_callback_uri"
OAUTH_TOKEN = "oauth_token"
REFRESH_TOKEN = "refresh_token"
USER_OAUTH = "user_oauth"
USER_REFRESH = "user_refresh"
APP_TOKEN = "app_token"
SCOPES = "scopes"
EVENTSUB_SECRET = "eventsub_secret"
API_BASE = "https://api.twitch.tv/helix/"
AUTH_API_BASE = "https://id.twitch.tv/oauth2/"
class TwitchRestApi:
def __init__(self, auth_filename=None):
self.auth_filename = auth_filename
self.auth_props = yaml.safe_load(open(self.auth_filename))
self.props = self.auth_props[TWTICH]
self.client_id = self.props[CLIENT_ID]
self.client_secret = self.props[CLIENT_SECRET]
self.redirect_uri = self.props[REDIRECT_URI]
self.callback_uri = self.props[CALLBACK_URI]
self.oauth_token = self.props.get(OAUTH_TOKEN, "")
self.refresh_token = self.props.get(REFRESH_TOKEN, "")
self.user_oauth = self.props.get(USER_OAUTH, "")
self.user_refresh = self.props.get(USER_REFRESH, "")
self.app_token = self.props.get(APP_TOKEN, "")
self.scopes = self.props.get(SCOPES, [])
self.eventsub_secret = self.props.get(EVENTSUB_SECRET, "")
if not self.eventsub_secret:
self.eventsub_secret = secrets.token_urlsafe()
self.props[EVENTSUB_SECRET] = self.eventsub_secret
self.auth_props[TWTICH] = self.props
with open(self.auth_filename, 'w') as f:
yaml.dump(self.auth_props, f)
def oauth_request_url(self):
url = AUTH_API_BASE + "authorize"
params = {
"client_id": self.client_id,
"redirect_uri": self.redirect_uri,
"response_type": "code",
"scope": " ".join(self.scopes)
}
final_url = requests.Request('GET', url, params=params).prepare()
return final_url.url
def get_oauth_token_from_code(self, code):
url = AUTH_API_BASE + "token"
params = {
CLIENT_ID: self.client_id,
CLIENT_SECRET: self.client_secret,
"code": code,
"grant_type": "authorization_code",
"redirect_uri": self.redirect_uri
}
r = requests.post(url, params=params)
data = r.json()
if r.status_code == 200:
self.oauth_token = data.get("access_token")
self.refresh_token = data.get(REFRESH_TOKEN)
self.props[OAUTH_TOKEN] = self.oauth_token
self.props[REFRESH_TOKEN] = self.refresh_token
self.auth_props[TWTICH] = self.props
with open(self.auth_filename, 'w') as f:
yaml.dump(self.auth_props, f)
return True
return False
def validate_oauth_token(self, user=False):
token = self.user_oauth if user else self.oauth_token
url = AUTH_API_BASE + "validate"
headers = {"Authorization": "Bearer " + token}
response = requests.get(url, headers=headers)
if response != 200:
self.refresh_oauth_token(user=user)
return False
return True
def validate_app_token(self):
url = AUTH_API_BASE + "validate"
headers = {"Authorization": "Bearer " + self.app_token}
response = requests.get(url, headers=headers)
if response.status_code != 200:
return self.refresh_app_token()
return True
def refresh_oauth_token(self, user=False):
token = self.user_oauth if user else self.oauth_token
refresh = self.user_refresh if user else self.refresh_token
url = AUTH_API_BASE + "token"
params = {
"client_id": self.client_id,
"client_secret": self.client_secret,
"grant_type": "refresh_token",
REFRESH_TOKEN: refresh
}
r = requests.post(url, params=params)
data = r.json()
if r.status_code == 200:
refresh = data.get(REFRESH_TOKEN)
token = data.get("access_token")
if user:
self.props[USER_REFRESH] = refresh
self.props[USER_OAUTH] = token
self.user_refresh = refresh
self.user_oauth = token
else:
self.props[REFRESH_TOKEN] = refresh
self.props[OAUTH_TOKEN] = token
self.refresh_token = refresh
self.oauth_token = token
self.auth_props[TWTICH] = self.props
with open(self.auth_filename, 'w') as f:
yaml.dump(self.auth_props, f)
return True
return False
def refresh_app_token(self):
url = AUTH_API_BASE + "token"
params = {
"client_id": self.client_id,
"client_secret": self.client_secret,
"grant_type": "client_credentials",
"scope": " ".join(self.scopes)
}
r = requests.post(url, params=params)
data = r.json()
if r.status_code == 200:
self.app_token = data.get("access_token")
self.props[APP_TOKEN] = self.app_token
self.auth_props[TWTICH] = self.props
with open(self.auth_filename, 'w') as f:
yaml.dump(self.auth_props, f)
return True
return False
def get_app_token(self):
self.validate_app_token()
return self.app_token
def get_oauth_token(self):
self.validate_oauth_token()
return self.oauth_token
def get_user_oauth(self):
self.validate_oauth_token(user=True)
return self.user_oauth
def get_channel_id(self, channel_name):
self.validate_app_token()
url = API_BASE + "users?login=" + channel_name
headers = {
"Authorization": "Bearer " + self.app_token,
"Client-Id": self.client_id
}
r = requests.get(url, headers=headers).json()
try:
return r['data'][0]['id']
except (KeyError, IndexError):
return False
def get_last_game_played(self, channel_id):
self.validate_app_token()
url = API_BASE + "channels"
headers = {
"Authorization": "Bearer " + self.app_token,
"Client-Id": self.client_id
}
r = requests.get(url, headers=headers, params={"broadcaster_id": channel_id}).json()
try:
return r['data'][0]['game_name']
except (KeyError, IndexError):
return False
def get_stream_info(self, channel_name):
self.validate_app_token()
url = API_BASE + "streams"
headers = {
"Authorization": "Bearer " + self.app_token,
"Client-Id": self.client_id
}
r = requests.get(url, headers=headers, params={"user_login": channel_name})
if r.status_code == 200:
data = r.json().get('data')
if len(data) == 1:
return data[0]
return False
def get_clips(self, channel_name, started_at: str=None) -> list:
self.validate_app_token()
url = API_BASE + "clips"
headers = {
"Authorization": "Bearer " + self.app_token,
"Client-Id": self.client_id
}
channel_id = self.get_channel_id(channel_name)
params = {
"broadcaster_id": channel_id,
"started_at": started_at
}
r = requests.get(url, headers=headers, params=params)
if r.status_code == 200:
return r.json()['data']
def create_clip(self, channel_name):
self.validate_oauth_token()
url = API_BASE + "clips"
headers = {
"Authorization": "Bearer " + self.oauth_token,
"Client-Id": self.client_id
}
channel_id = self.get_channel_id(channel_name)
params = {
"broadcaster_id": channel_id,
}
r = requests.post(url, headers=headers, params=params)
return r
def get_eventsub_subscriptions(self):
self.validate_app_token()
headers = {
"Authorization": "Bearer " + self.app_token,
"Client-Id": self.client_id
}
url = API_BASE + "eventsub/subscriptions"
r = requests.get(url, headers=headers)
if r.status_code == 200:
return r.json()
return False
def delete_all_eventsub_subscriptions(self):
self.validate_app_token()
del_url = API_BASE + "eventsub/subscriptions"
headers = {
"Authorization": "Bearer " + self.app_token,
"Client-Id": self.client_id
}
subscriptions = self.get_eventsub_subscriptions()
print(subscriptions)
for sub in subscriptions.get('data', {}):
sub_id = sub.get('id')
requests.delete(del_url, headers=headers, params={"id": sub_id})
def eventsub_delete_subscription(self, subscription_id):
self.validate_app_token()
url = API_BASE + "eventsub/subscriptions"
headers = {
"Authorization": "Bearer " + self.app_token,
"Client-Id": self.client_id
}
r = requests.delete(url, headers=headers, params={'id': subscription_id})
return r
def eventsub_add_subscription(self, condition):
self.validate_app_token()
url = API_BASE + "eventsub/subscriptions"
headers = {
"Authorization": "Bearer " + self.app_token,
"Client-ID": self.client_id,
"Content-Type": "application/json"
}
def eventsub_add_subscription(self, condition, subscription_type, version='1'):
self.validate_app_token()
url = API_BASE + "eventsub/subscriptions"
headers = {
"Authorization": "Bearer " + self.app_token,
"Client-ID": self.client_id,
"Content-Type": "application/json"
}
payload = {
"type": subscription_type,
"version": version,
"condition": condition,
"transport": {
"method": "webhook",
"callback": self.callback_uri,
"secret": self.eventsub_secret
}
}
r = requests.post(url, headers=headers, json=payload)
return r
def get_subscribers(self, channel_name):
self.validate_oauth_token(user=True)
url = API_BASE + "subscriptions"
headers = {
"Authorization": "Bearer " + self.user_oauth,
"Client-ID": self.client_id,
"Content-Type": "application/json"
}
channel_id = self.get_channel_id(channel_name)
r = requests.get(url, headers=headers, params={"broadcaster_id": channel_id})
return r.json()
def get_followage(self, channel_name, follower_name) -> relativedelta:
self.validate_oauth_token()
url = API_BASE + "channels/followers"
headers = {
"Authorization": "Bearer " + self.oauth_token,
"Client-ID": self.client_id,
"Content-Type": "application/json"
}
channel_id = self.get_channel_id(channel_name)
follower_id = self.get_channel_id(follower_name)
if not follower_id:
return False
parameters = {
"broadcaster_id": channel_id,
"user_id": follower_id
}
r = requests.get(url, headers=headers, params=parameters).json()
if len(r['data']) == 0:
return False
followed_at = r['data'][0]['followed_at']
datetime_format = "%Y-%m-%dT%H:%M:%SZ"
followed_datetime = datetime.strptime(followed_at, datetime_format)
follow_age = relativedelta(datetime.now(), followed_datetime)
return follow_age
def get_chatters(self, channel_name):
self.validate_oauth_token(user=True) # use broadcaster id
url = API_BASE + "chat/chatters"
headers = {
"Authorization": "Bearer " + self.user_oauth,
"Client-ID": self.client_id
}
channel_id = self.get_channel_id(channel_name)
parameters = {
"broadcaster_id": channel_id,
"moderator_id": channel_id
}
r = requests.get(url, headers=headers, params=parameters).json()
return r
if __name__ == "__main__":
twitch_api = TwitchRestApi(auth_filename="config/botjamin_auth.yaml")
res = twitch_api.get_chatters("beanjamin25")
pprint(res)