-
Notifications
You must be signed in to change notification settings - Fork 4
/
extension.js
65 lines (56 loc) · 1.89 KB
/
extension.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
'use strict';
function Followers(nodecg) {
this.nodecg = nodecg;
this.request = require('request');
this.latestFollower = nodecg.Replicant('latestFollower', { defaultValue: null, persistent: true });
this.username = nodecg.bundleConfig.username;
this.pollInterval = nodecg.bundleConfig.pollInterval * 1000;
this._scheduleFollowers();
}
Followers.prototype._scheduleFollowers = function() {
var options = {
url: 'https://api.twitch.tv/kraken/channels/' + this.username + '/follows?limit=50',
headers: {
'Client-ID': this.nodecg.config.login.twitch.clientID
}
};
this.nodecg.log.debug('Polling for TwitchTV Followers.');
this.request(options,
(err, response, body) => {
if (err) {
this.nodecg.log.error(err);
setTimeout(() => { this._scheduleFollowers(); }, this.pollInterval);
return;
}
if (response.statusCode != 200) {
this.nodecg.log.error('Unknown response code: ' + response.statusCode);
setTimeout(() => { this._scheduleFollowers(); }, this.pollInterval);
return;
}
var lastFollowerTs = 0;
if (this.latestFollower.value) {
lastFollowerTs = Date.parse(this.latestFollower.value.created_at);
}
try {
body = JSON.parse(body);
} catch (error) {
this.nodecg.log.error(error);
return;
}
if (body.follows.length > 0) {
this.nodecg.log.debug('Discovered ' + body.follows.length + ' followers.');
this.latestFollower.value = body.follows[0];
body.follows.reverse().map((follower) => {
var parsedTs = Date.parse(follower.created_at);
if (parsedTs > lastFollowerTs) {
this.nodecg.sendMessage('follower', follower);
}
});
}
setTimeout(() => { this._scheduleFollowers(); }, this.pollInterval);
}
);
};
module.exports = function(api) {
return new Followers(api);
};