-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathtwitchapi.lua
330 lines (278 loc) · 8.34 KB
/
twitchapi.lua
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
-- Copyright (C) 2018 Jérôme Leclercq
-- This file is part of the "Not a Bot" application
-- For conditions of distribution and use, see copyright notice in LICENSE
local http = require("coro-http")
local json = require("json")
local querystring = require("querystring")
local timer = require("timer")
local decode, encode = json.decode, json.encode
local insert = table.insert
local max, random = math.max, math.random
local ipairs = ipairs
local request = http.request
local resume = coroutine.resume
local running = coroutine.running
local setTimeout = timer.setTimeout
local sleep = timer.sleep
local tostring = tostring
local urlencode = querystring.urlencode
local yield = coroutine.yield
local endpoints = {
EventSubSubscriptions = "https://api.twitch.tv/helix/eventsub/subscriptions",
GetGames = "https://api.twitch.tv/helix/games",
GetStreams = "https://api.twitch.tv/helix/streams",
GetUsers = "https://api.twitch.tv/helix/users",
}
local function tprint (tbl, indent)
if not indent then indent = 0 end
for k, v in pairs(tbl) do
local formatting = string.rep(" ", indent) .. k .. ": "
if type(v) == "table" then
print(formatting)
tprint(v, indent+1)
elseif type(v) == 'boolean' then
print(formatting .. tostring(v))
else
print(formatting .. v)
end
end
end
local TwitchApi = {}
TwitchApi.__index = TwitchApi
function TwitchApi:__init(discordia, client, appId, appSecret)
self._client = client
self._discordia = discordia
self._clientId = appId
self._clientSecret = appSecret
self._isRequesting = false
self._waitingCoroutines = {}
end
function TwitchApi:Authenticate()
local parameters = {
client_id = self._clientId,
client_secret = self._clientSecret,
grant_type = "client_credentials"
}
local success, headerOrErr, body = pcall(http.request, "POST", "https://id.twitch.tv/oauth2/token", {{"Content-Type", "application/x-www-form-urlencoded"}}, querystring.stringify(parameters))
if (not success) then
print("Failed to request Twitch Token (is network down?): " .. headerOrErr)
return false, "NetworkError"
end
if (headerOrErr.code < 200 or headerOrErr.code > 299) then
p(body)
print("Failed to request Twitch Token (are credentials still valid?) (code " .. headerOrErr.code .. ")")
return false, body
end
local tokenData = assert(json.decode(body))
self.token = {
accessToken = tokenData.access_token,
expirationTime = os.time() + tonumber(tokenData.expires_in),
tokenType = tokenData.token_type
}
-- Twitch, vous êtes des baltringues nucléaires
self.token.tokenType = self.token.tokenType:sub(1, 1):upper() .. self.token.tokenType:sub(2)
return true
end
function TwitchApi:Commit(method, url, headers, body, retries, forceAuth)
if (forceAuth or not self.token or os.time() > self.token.expirationTime) then
local success, err = self:Authenticate()
if (not success) then
error("Twitch authentication failed: " .. err)
end
end
headers = headers or {}
-- Discard authorization header if any
for k, header in pairs(headers) do
local key = header[1]:lower()
if (key == "authorization" or key == "client-id") then
headers[k] = nil
end
end
insert(headers, {"Authorization", self.token.tokenType .. " " .. self.token.accessToken})
insert(headers, {"Client-ID", self._clientId})
local success, res, msg = pcall(request, method, url, headers, body)
if (not success) then
self._client:error("Request failed : %s %s", method, url)
return nil, res, 100
end
for i, v in ipairs(res) do
res[string.lower(v[1])] = v[2]
res[i] = nil
end
local reset = res["ratelimit-reset"]
local remaining = res["ratelimit-remaining"]
local delay = 0 -- ?
if (reset and remaining == "0") then
local dt = os.difftime(reset, self._discordia.Date.parseHeader(res["date"]))
delay = max(dt * 1000, delay)
end
local contentType = res["content-type"]
local data = (contentType and contentType:find("application/json")) and decode(msg) or msg
if (res.code < 300) then
self._client:info("%i - %s : %s %s", res.code, res.reason, method, url)
return data, nil, delay
else
local maxRetries = 5
local retry
if (res.code == 429) then -- Too Many Requests
retry = retries < maxRetries
elseif (res.code >= 500) then -- Server error
delay = delay + random(2000)
retry = retries < maxRetries
elseif (res.code == 401) then -- Token error
delay = 100
retry = retries < maxRetries
forceAuth = true
end
if (retry) then
self._client:warning("%i - %s : retrying after %i ms : %s %s", res.code, res.reason, delay, method, url)
sleep(delay)
return self:Commit(method, url, headers, body, retries + 1, forceAuth)
end
p(msg)
self._client:error('%i - %s : %s %s', res.code, res.reason, method, url)
return nil, {code=res.code, msg=msg}, delay
end
end
function TwitchApi:Request(method, endpoint, parameters, headers)
headers = headers or {}
local body
if (parameters and not table.empty(parameters)) then
if (method == "GET" or method == "DELETE") then
local url = {endpoint}
for k, v in pairs(parameters) do
insert(url, #url == 1 and '?' or '&')
insert(url, urlencode(k))
insert(url, '=')
insert(url, urlencode(v))
end
endpoint = table.concat(url)
elseif (method == "POST") then
body = encode(parameters)
insert(headers, {"Content-Type", "application/json; charset=utf-8"})
insert(headers, {"Content-Length", #body})
else
error("Invalid method " .. method)
end
end
self:Lock()
local succeeded, data, err, delay = pcall(function () return self:Commit(method, endpoint, headers, body, 0) end)
self:Unlock(delay)
if (not succeeded) then
return nil, data
end
if (data) then
return data
else
return nil, err
end
end
function TwitchApi:Lock()
if (self._isRequesting) then
local co = running()
insert(self._waitingCoroutines, co)
yield(co)
end
self._isRequesting = true
end
function TwitchApi:Unlock()
if (#self._waitingCoroutines > 0) then
local co = table.remove(self._waitingCoroutines, 1)
assert(resume(co))
else
self._isRequesting = false
end
end
local unlock = TwitchApi.Unlock
function TwitchApi:UnlockAfter(delay)
setTimeout(delay, unlock, self)
end
function TwitchApi:GetGameById(gameId)
local body, err = self:Request("GET", endpoints.GetGames, {id = gameId})
if (body and body.data) then
return body.data[1]
else
return nil, err
end
end
function TwitchApi:GetGameByName(gameName)
local body, err = self:Request("GET", endpoints.GetGames, {name = gameName})
if (body and body.data) then
return body.data[1]
else
return nil, err
end
end
function TwitchApi:GetStreamByUserId(userId)
local body, err = self:Request("GET", endpoints.GetStreams, {user_id = userId})
if (body and body.data) then
return body.data[1]
else
return nil, err
end
end
function TwitchApi:GetStreamByUserName(userName)
local body, err = self:Request("GET", endpoints.GetStreams, {user_login = userName})
if (body and body.data) then
return body.data[1]
else
return nil, err
end
end
function TwitchApi:GetUserById(userId)
local body, err = self:Request("GET", endpoints.GetUsers, {id = userId})
if (body and body.data) then
return body.data[1]
else
return nil, err
end
end
function TwitchApi:GetUserByName(userName)
local body, err = self:Request("GET", endpoints.GetUsers, {login = userName})
if (body and body.data) then
return body.data[1]
else
return nil, err
end
end
function TwitchApi:ListSubscriptions()
return self:Request("GET", endpoints.EventSubSubscriptions)
end
function TwitchApi:SubscribeWebHook(type, userId, callback, secret)
local parameters = {
type = type,
version = "1",
condition = {
broadcaster_user_id = userId
},
transport = {
method = "webhook",
callback = callback,
secret = secret
}
}
return self:Request("POST", endpoints.EventSubSubscriptions, parameters)
end
function TwitchApi:SubscribeToStreamUp(userId, callback, secret)
return self:SubscribeWebHook("stream.online", userId, callback, secret)
end
function TwitchApi:Unsubscribe(subscriptionId)
return self:Request("DELETE", endpoints.EventSubSubscriptions, {id = subscriptionId})
end
function TwitchApi:__tostring()
return "TwitchApi"
end
return setmetatable({}, {
__call = function (self, ...)
local o = {}
setmetatable(o, TwitchApi)
o:__init(...)
return o
end,
__newindex = function (o, key, val)
error("Writing is prohibited")
end,
__tostring = function ()
return "TwitchApi"
end
})