forked from wcko87/simple-twitch-streams-bot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
twitch-helix.js
98 lines (93 loc) · 2.52 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
const twitch = require('./twitch-helix-api');
const EventEmitter = require('events');
const streamEmitter = new EventEmitter();
let startup = false;
let streams = { };
function streamLoop () {
// Uncomment for logging.
//console.log("Get streams...");
//console.log(".--current streams--.");
//console.log(streams)
//console.log("'-------------------'");
twitch.streams.getStreams({
"game_id": [
process.env.GAME_ID
],
"type": 'live'
}).then((data) => {
let res = data.data.data;
if (res === undefined) {
console.log('ERROR: ' + data.data.error);
return null;
}
let user_ids = [];
for (let stream of res) {
user_ids.push(stream["user_id"]);
if (!streams[stream["user_id"]]) {
streams[stream["user_id"]] = {};
}
streams[stream["user_id"]] = {
...streams[stream["user_id"]],
...stream,
};
streams[stream["user_id"]]["timer"] = 15;
streams[stream["user_id"]]["url"] = 'https://www.twitch.tv/' + stream["user_login"];
streams[stream["user_id"]]["login"] = stream["user_login"];
}
if (user_ids.length > 0) {
return twitch.users.getUsers({
"id": user_ids
});
}
return null;
}).then((data) => {
if (data === null) {
return;
}
const res = data.data.data;
if (res === undefined) {
console.log('ERROR: ' + data.data.error);
return null;
} else {
// console.log('request successful');
}
for (const user of res) {
streams[user["id"]].user= user;
if (!streams[user["id"]].send ) {
streams[user["id"]].send = true
if (startup) {
streamEmitter.emit('messageStreamStarted', streams[user["id"]]);
}
}
}
return;
})
.catch((e) => {
console.error(e);
}).finally(() => {
if (!startup) {
startup = true;
}
setTimeout(streamLoop, 30000);
});
}
setTimeout(streamLoop, 5000);
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];
}
}
}, 20000);
streamEmitter.getStreams = () => {
return streams;
}
module.exports = streamEmitter;