-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapp.js
55 lines (50 loc) · 1.54 KB
/
app.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
"use latest"
const axios = require("axios").default;
module.exports = function (ctx, done) {
var secrets = {
apiKey: ctx.secrets.nlpApiKey,
slackWebhookURL: ctx.secrets.slackWebhookURL
};
var tweet = {
main: {
userName: ctx.data.from,
text: ctx.data.text,
url: ctx.data.url
},
nlpConfig: {
document: {
type: "PLAIN_TEXT",
content: ctx.data.text
},
encodingType: "UTF8"
}
};
checkSentiment(secrets, tweet, () => {
console.log(tweet);
done(null, `complete!`);
});
};
function checkSentiment(secrets, tweetData, cb) {
axios.post(`https://language.googleapis.com/v1/documents:analyzeSentiment?key=${secrets.apiKey}`, tweetData.nlpConfig)
.then(res => {
if (res.data.documentSentiment.score < 0) {
console.log("Negative tweet")
return isNegative(secrets, tweetData.main)
} else {
//TODO: some other action.
console.log("Positive tweet")
}
})
.then(() => {
cb();
})
.catch(err => { handleErrors("NLP", err) });
}
function isNegative(secrets, tweetData) {
axios.post(secrets.slackWebhookURL, {
text: `*${tweetData.userName}*\n> _${tweetData.text}_\n ${tweetData.url}`
}).catch(err => { handleErrors("Slack", err) });
}
function handleErrors(caller, reason) {
console.log(`Failed at ${caller}: ${reason}`);
}