-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathbot.js
96 lines (75 loc) · 2.64 KB
/
bot.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
var request = require('request'),
Particle = require('particle-api-js');
var configPath = (process.argv[2] || './config.json'),
config = require(configPath);
var particle = new Particle(),
particleToken;
var fbToken = config.facebookConfig.client_id + '|' + config.facebookConfig.client_secret,
fbURI = 'https://graph.facebook.com/v2.6/' + config.facebookConfig.video_id + '/comments?access_token=' + fbToken + '&order=reverse_chronological';
var seenComments = {},
totalQueries = 0;
function containsAnyOf(needles, haystack) {
for (var i = 0; i < needles.length; ++i) {
if (haystack.match(needles[i])) {
return needles[i];
}
}
return undefined;
};
function queryComments(cb) {
console.log('querying! attempt: ', ++totalQueries);
request.get(fbURI, function(err, response, body) {
if(err) {
return console.log('error querying facebook:', err);
}
body = JSON.parse(body);
if (!body.data || !body.data.length) {
console.log('no comments: ', body);
return;
}
var comments = body.data;
var numTriggers = 0;
for (var i = 0; i < comments.length; ++i) {
var comment = comments[i];
if (seenComments[comment.id]) {
break;
}
console.log('new comment: ', comment);
// normalize the comment
var message = comment.message.toLowerCase();
// record that we've seen this comment
seenComments[comment.id] = message;
// check the comment for triggers
if (containsAnyOf(config.triggers, message)) {
++numTriggers;
}
}
// if there were triggers, fire an event!
if (numTriggers && config.reallyActuallyTrigger) {
var publishEventPr = particle.publishEvent({
name: config.event.name,
data: config.event.data,
auth: particleToken,
isPrivate: config.event.isPrivate
});
publishEventPr.then(
function(data) {
console.log('published event: ', data);
},
function(err) {
console.log('failed to publish event:', err);
}
);
}
});
}
particle.login(config.particleConfig).then(
function(data) {
console.log('connected to particle');
particleToken = data.body.access_token;
setInterval(queryComments, config.interval);
},
function(err) {
console.log('failed to log in to particle\n', err);
}
);