-
Notifications
You must be signed in to change notification settings - Fork 2
/
app.js
209 lines (198 loc) · 6.82 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
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
198
199
200
201
202
203
204
205
206
207
208
209
'use strict'
const express = require('express');
const bodyParser = require('body-parser');
const request = require('request');
const async = require('async');
var question = require('./question.js');
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
const DEBUG = true;
const server = app.listen(process.env.PORT || 3000, () => {
console.log('Express server listening on port %d in %s mode', server.address().port, app.settings.env);
});
function sendMessage(event) {
var GOOGLE_API_KEY = process.env.GOOGLE_API_KEY;
var FACEBOOK_ACCESS_TOKEN = process.env.FACEBOOK_ACCESS_TOKEN;
var FACEBOOK_VERIFICATION_TOKEN = process.env.FACEBOOK_VERIFICATION_TOKEN;
let sender = event.sender.id;
var topic = event.message.text.replace(/\s/g, ""); // Removing whitespace from input to use in request url
function wikiNotFoundError() { // generalized error message when no data for questions is found
request({ // request to facebook page to send error message
url: 'https://graph.facebook.com/v2.10/me/messages',
qs: { access_token: FACEBOOK_ACCESS_TOKEN },
method: 'POST',
json: {
recipient: { id: sender },
message: { text: 'I\'m sorry. I did not receive any data. Please try again!' }
}
});
}
function sendQuestion(articlesData) {
var siteUrl = 'https://language.googleapis.com/v1beta2/documents:analyzeEntities?key=' + GOOGLE_API_KEY; // Google NLP API url
var options =
{
url: siteUrl,
method: 'POST',
body:
{
"document":
{
"type": "PLAIN_TEXT",
"language": "EN",
"content": articlesData[0] // first text paragraph in first article for now
},
"encodingType": "UTF8"
},
json: true
}
request(options, function (error, response, body) {
if (!error && response.statusCode === 200) {
var data = body.entities;
data.sort(function (a, b) { // sorting entities according to their salience
return b.salience - a.salience;
});
if (data.length > 1) {
var blank='_______';
var key = data[0].name;
var index = data[0].mentions[0].text.beginOffset;
if (data[0]) {
for (var j = 0; j < data[0].mentions.length; j++) {
if (data[0].mentions[j]) {
if (data[0].mentions[j].text.content === key && data[0].mentions[j].type === "PROPER") {
key = data[0].name;
index = data[0].mentions[j].text.beginOffset;
break;
}
}
}
}
for (var i = 1; i < data.length; i++) {
if (data[i]) {
for (var j = 0; j < data[i].mentions.length; j++) {
if (data[i].mentions[j]) {
if (data[i].mentions[j].text.content === data[i].name && data[i].mentions[j].type === "PROPER") {
key = data[i].name;
index = data[i].mentions[j].text.beginOffset;
break;
}
}
}
}
if (key != data[0].name && topic.toLowerCase() != key.replace(/\s/g, "").toLowerCase()) {
break;
}
}
//var length = key.length;
var newText = '';
var blank = '_______';
// Insert blanks into all occurrences of answer within question
var arrAns = articlesData[0].split(key);
for(var i in arrAns) {
newText += arrAns[i];
if(i < arrAns.length - 1) {
newText += blank;
}
}
//newText = articlesData[0].substring(0, index) + blank + articlesData[0].substring(index + length);
console.log('ANSWER: ' + key);
request({
url: 'https://graph.facebook.com/v2.10/me/messages',
qs: { access_token: FACEBOOK_ACCESS_TOKEN },
method: 'POST',
json: {
recipient: { id: sender },
message: { text: newText }
}
});
}
else {
wikiNotFoundError();
}
}
});
}
function get50Questions(articles, callback) {
var articlesData = [];
async.forEachOf(articles, function (value, key, callback) {
var siteUrl = 'http://' + topic + '.wikia.com/api/v1/Articles/AsSimpleJson?id=' + value; // wikia API url
request.get(siteUrl, function (error, response, body) {
if (!error && response.statusCode === 200) {
try {
var sections = JSON.parse(body).sections; // get all the sections in the article
}
catch (e) {
wikiNotFoundError();
return;
}
for (var i = 0; i < sections.length; i++) {
if (sections[i]) { //if the section has data
if (sections[i].content[0]) { // if the content has data
if (sections[i].content[0].text) { // if the text exists
articlesData.push(sections[i].content[0].text);
break;
}
}
}
}
callback(); // sendQuestion()
} else {
wikiNotFoundError();
}
});
}, function (err) {
if (err) {
return callback(null);
} else {
return callback(articlesData);
}
});
}
function getFiftyArticles() {
var articles = [];
var siteUrl = 'http://' + topic + '.wikia.com/api/v1/Articles/Top?Limit=250';
var rand;
// Create list of 250 popular articles
request.get(siteUrl, function (error, response, body) {
if (!error && response.statusCode === 200) {
try {
var items = JSON.parse(body).items;
}
catch (e) {
wikiNotFoundError();
return;
}
var itemsCount = items.length;
var noOfQs = (itemsCount < 50) ? itemsCount : 50;
for (var i = 0; i < noOfQs; i++) {
rand = Math.random();
rand *= itemsCount;
articles.push(items[Math.floor(rand)].id);
}
get50Questions(articles, function (articlesData) {
sendQuestion(articlesData);
});
}
});
}
getFiftyArticles();
}
app.get('/webhook', (req, res) => { // For Facebook Webhook Verification
if (req.query['hub.mode'] && req.query['hub.verify_token'] === FACEBOOK_VERIFICATION_TOKEN) {
res.status(200).send(req.query['hub.challenge']);
} else {
res.status(403).end();
}
});
app.post('/webhook', (req, res) => {
if (req.body.object === 'page') {
req.body.entry.forEach((entry) => {
entry.messaging.forEach((event) => {
if (event.message && event.message.text) {
sendMessage(event);
}
});
});
res.status(200).end();
}
});