-
Notifications
You must be signed in to change notification settings - Fork 1
/
twitch-helix.js
197 lines (179 loc) · 5.9 KB
/
twitch-helix.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
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
const EventEmitter = require('events');
const jsonfile = require('jsonfile');
const axios = require('axios');
const qs = require('qs');
const configFile = './config.json';
const config = jsonfile.readFileSync(configFile);
const streamEmitter = new EventEmitter();
let startup = true;
let streams = {};
let tags = config["target-stream-tags"];
let titleWordlist = config["target-stream-title-wordlist"];
let detectionMode = config["target-stream-detection-type"];
let currentTwitchToken;
if (detectionMode == undefined)
detectionMode = "tags";
async function getOauthToken() {
if (Date.now() < config["twitch-access-token-expires-At"] && config["twitch-access-token"] && config["twitch-access-token"].length > 0) {
return config["twitch-access-token"];
}
const res = await axios({
url: "https://id.twitch.tv/oauth2/token",
method: "POST",
headers: {},
data: {
client_id: config["twitch-client-id"],
client_secret: config["twitch-client-secret"],
"grant_type": "refresh_token",
refresh_token: config["twitch-refresh-token"],
}
});
if (!res.data["access_token"]) {
throw new Error("API did not provide an OAuth token!");
}
if (res.data["access_token"]) {
updateConfig("twitch-access-token", res.data["access_token"]);
updateConfig("twitch-access-token-expires-At", Date.now() + 3500 * 1000);
}
return res.data["access_token"];
}
function getStreams(token, cursor=null) {
let apiURL = `https://api.twitch.tv/helix/streams?game_id=${config["target-game-ids"].join("&game_id=")}&first=99&type=live`;
if (cursor)
apiURL = apiURL + `&after=${cursor}`
return axios({
url: apiURL,
method: "GET",
headers: {
"Client-ID": config["twitch-client-id"],
"Authorization": "Bearer " + token,
},
params: {
"game_id": config["target-game-ids"],
"first": 99,
"type": 'live',
}
});
}
function getUsers(ids) {
return axios({
url: "https://api.twitch.tv/helix/users",
method: "GET",
headers: {
"Client-ID": config["twitch-client-id"],
"Authorization": "Bearer " + config["twitch-access-token"],
},
params: {
"id": ids,
}
});
}
async function streamLoop() {
// Uncomment for logging.
//console.log("Get streams...");
//console.log(".--current streams--.");
//console.log(streams)
//console.log("'-------------------'");
let streamList = [];
getOauthToken().then((token) => {
currentTwitchToken = token;
return getStreams(currentTwitchToken);
}).then(async (res) => {
let streamCursor = res.data.pagination.cursor;
streamList = streamList.concat(res.data.data);
while (streamCursor != null) {
let extraRes = await getStreams(currentTwitchToken, streamCursor);
streamList = streamList.concat(extraRes.data.data);
streamCursor = extraRes.data.pagination.cursor;
}
let user_ids = [];
for (let i = 0; i < streamList.length; i++) {
let stream = streamList[i];
let speedrun = false;
if (detectionMode == "tags") { //tags mode
if (stream.tag_ids) {
speedrun = tags.find(tag => {
if (stream.tag_ids.includes(tag))
return true;
return false;
});
}
} else { //title mode
speedrun = titleWordlist.some(val => {
let regex = new RegExp('(^|\\s|!|-|\\.|\\?|,)' + val.toLowerCase() + '($|\\s|!|-|\\.|\\?|,)', 'i')
return regex.test(stream["title"].toLowerCase());
});
}
if (speedrun) {
user_ids.push(stream["user_id"]);
if (typeof streams[stream["user_id"]] === 'undefined') {
streams[stream["user_id"]] = {};
}
streams[stream["user_id"]]["timer"] = 15;
streams[stream["user_id"]]["title"] = stream["title"];
streams[stream["user_id"]]["viewer_count"] = stream["viewer_count"];
streams[stream["user_id"]]["game_id"] = stream["game_id"];
streams[stream["user_id"]]["game_name"] = stream["game_name"];
}
}
if (user_ids.length > 0) {
return getUsers(user_ids);
}
return null;
}).then((response) => {
if (response === null) {
return;
}
let userData = response.data.data;
for (let i = 0; i < userData.length; i++) {
let userElem = userData[i];
if (typeof streams[userElem["id"]]["url"] === 'undefined') {
if (startup === true) {
streamEmitter.emit('messageStreamStarted', {
"id": userElem["id"],
"url": 'https://www.twitch.tv/' + userElem["login"],
"name": userElem["login"],
"title": streams[userElem["id"]]["title"],
"game": streams[userElem["id"]]["game_name"],
"user_profile_image": userElem["profile_image_url"]
});
}
}
streams[userElem["id"]]["url"] = 'https://www.twitch.tv/' + userElem["login"];
streams[userElem["id"]]["display_name"] = userElem["display_name"];
streams[userElem["id"]]["login"] = userElem["login"];
streams[userElem["id"]]["lastUpdate"] = new Date().getTime();
}
return;
}).catch((e) => {
console.error(e);
}).then(() => {
setTimeout(streamLoop, 30000);
});
}
function updateConfig(key, value) {
config[key] = value;
jsonfile.writeFile(configFile, config, { spaces: 2 }, function (err) {
if (err) console.error(err)
});
}
setTimeout(streamLoop, 15000);
setInterval(() => {
for (let stream of Object.keys(streams)) {
streams[stream]["timer"]--;
if (streams[stream]["timer"] < 1) {
if (typeof streams[stream]["url"] !== 'undefined' && typeof streams[stream]["title"] !== 'undefined') {
streamEmitter.emit('messageStreamDeleted', {
"url": streams[stream]["url"],
"title": streams[stream]["title"],
"id": stream
});
}
delete streams[stream];
}
}
}, 10000);
streamEmitter.getStreams = () => {
return streams;
}
module.exports = streamEmitter;