-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathutils.js
78 lines (73 loc) · 2.49 KB
/
utils.js
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
// Copyright (c) 2020-2022 Mitchell Adair
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
const fetch = require("node-fetch");
const USER_TYPES = {
user: 0,
vip: 1,
subscriber: 2,
moderator: 3,
global_mod: 3,
broadcaster: 3,
};
const timedLog = (message) => {
console.log(`${new Date().toUTCString()} ** BOT: ${message}`);
};
module.exports = {
request: async (url, options, onAuthFailure) => {
const r = async () => {
const res = await fetch(url, options);
if (res.ok) {
try {
// can only read res once, so clone so we can fallback to text
const json = await res.clone().json();
return json;
} catch {
return res.text();
}
} else if (res.status === 401) {
if (!onAuthFailure) {
throw new Error("received 401 error without a way to refresh");
}
timedLog("received 401 when attempting request, retrying with new token...");
const newToken = await onAuthFailure();
options.header.authorization = `Bearer ${newToken}`;
return r();
} else {
// if response not OK and not 401, throw the response body as error
const err = await res.json();
timedLog(`received non-401 error when attempting request: ${err.message}`);
throw err;
}
};
return r();
},
getLengthDataFromMillis: (ms) => {
const date = new Date(ms);
return {
years: date.getUTCFullYear() - 1970,
months: date.getUTCMonth(),
days: date.getUTCDate() - 1,
hours: date.getUTCHours(),
minutes: date.getUTCMinutes(),
seconds: date.getUTCSeconds(),
};
},
getUserLevel: (userstate) => {
return userstate["badges-raw"]
? userstate["badges-raw"]
.split(",")
.map((badge) => {
return badge.split("/")[0];
})
.reduce((total, badge) => {
if (USER_TYPES[badge] && USER_TYPES[badge] > total) {
return USER_TYPES[badge];
}
return total;
}, USER_TYPES.user)
: 0;
},
timedLog,
};