-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
334 lines (288 loc) · 7.62 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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
'use strict'
const
bodyParser = require('body-parser'),
crypto = require('crypto'),
express = require('express'),
https = require('https'),
request = require('request'),
dateFormat = require('dateformat'),
defer = require('./defer')
var app = express()
app.set('port', process.env.PORT || 3000)
app.use(bodyParser.json())
const VALIDATION_TOKEN = process.env.MESSENGER_VALIDATION_TOKEN || ''
const PAGE_ACCESS_TOKEN = process.env.MESSENGER_PAGE_ACCESS_TOKEN || ''
const API_AI_ACCESS_TOKEN = process.env.API_AI_ACCESS_TOKEN || ''
const WEATHER_API_KEY = process.env.WEATHER_API_KEY || ''
app.get('/webhook', (req, res) => {
if (req.query['hub.mode'] === 'subscribe' &&
req.query['hub.verify_token'] === VALIDATION_TOKEN) {
console.log("Validating webhook")
res.status(200).send(req.query['hub.challenge'])
} else {
console.error("Failed validation. Make sure the validation tokens match.")
res.sendStatus(403)
}
})
app.post('/webhook', (req, res) => {
var data = req.body
// Make sure this is a page subscription
if (data.object == 'page') {
// Iterate over each entry
// There may be multiple if batched
data.entry.forEach((pageEntry) => {
var pageID = pageEntry.id
var timeOfEvent = pageEntry.time
// Iterate over each messaging event
pageEntry.messaging.forEach((messagingEvent) => {
if (messagingEvent.message) {
receivedMessage(messagingEvent)
}
else {
console.log(`Webhook received unknown messagingEvent: ${messagingEvent}`)
}
})
})
res.sendStatus(200)
}
})
function receivedMessage(event) {
var senderID = event.sender.id
var recipientID = event.recipient.id
var timeOfMessage = event.timestamp
var message = event.message
console.log(`Received message for user ${senderID} and page ${recipientID} at ${timeOfMessage} with message:`)
console.log(JSON.stringify(message))
sendReadReceipt(senderID)
sendTypingOn(senderID);
((senderID) => {
request(
{
url: 'https://api.api.ai/v1/query',
headers: {
'Authorization': `Bearer ${API_AI_ACCESS_TOKEN}`,
'Content-Type': 'application/json charset=utf-8'
},
method: 'GET',
qs: {
v: '20150910',
query: message.text,
sessionId: '1234567890',
lang: 'en'
}
}, (error, response, body) => {
if (!error && response.statusCode == 200) {
var queryParams = getQueryParams(JSON.parse(body))
sendTextMessage(senderID, formResponseMessage(queryParams))
if (!queryParams.fallback) {
console.log(sendTypingOn)
sendTypingOn(senderID)
getForecast(queryParams).then((forecast) => {
console.log('promise')
sendTextMessage(senderID, forecast)
})
}
}
})
})(senderID)
}
function getQueryParams(body) {
console.log(body.result.metadata.intentName)
if (body.result.metadata.intentName != 'show weather')
return {
fallback: true,
text: body.result.fulfillment.speech
}
var city = body.result.parameters.address.city
var state = body.result.parameters.address.state
var date = body.result.parameters.date
var time = body.result.parameters.time
var hasCity = city != null && city != ""
var hasDate = date != null && date != ""
var hasTime = time != null && time != ""
var hasState = state != null && state != ""
if (!hasCity) {
if (hasState)
city = state
else
city = 'your location'
}
else if (hasState) {
city += ', ' + state
}
if (!hasDate)
date = dateFormat(new Date(body.timestamp), 'isoDate')
if (!hasTime) {
if (hasDate)
time = '00:00:00'
else
time = dateFormat(new Date(body.timestamp), 'isoTime')
}
return {
fallback: false,
time,
hasTime,
date,
hasDate,
city,
hasCity,
state,
hasState
}
}
function formResponseMessage(params) {
if (params.fallback)
return params.text
var result = `You requested a weather forecast in ${params.city} for ${params.date} ${params.time}.`
return result
}
function getForecast(params) {
var result = defer()
if (!params.hasCity) {
result.resolve(`Cannot determine weather forecast in this location. Please specify the correct city name. Also, it may be that you specified the city I just don't know.`)
return result
}
request(
{
url: 'http://api.openweathermap.org/data/2.5/forecast',
qs: {
q: params.city,
APPID: WEATHER_API_KEY,
units: 'metric'
}
}, (err, response, body) => {
var allweather = JSON.parse(body)
if (!allweather.list) {
console.log(allweather)
result.resolve('Cannot determine weather forecast in this location. Please try something else.')
return result
}
// Picking the closest forecast available from the list
// The weather API gives me the forecast for 5 days maximum
var closestForecastInd = 0
var closestForecastDt = 1e20
var timeRequested = new Date(params.date + ' ' + params.time)
for (var curForecastInd in allweather.list) {
var curDt = Math.abs((new Date(allweather.list[curForecastInd].dt_txt)) - timeRequested)
if (curDt < closestForecastDt) {
closestForecastInd = curForecastInd
closestForecastDt = curDt
}
}
var weather = allweather.list[closestForecastInd]
var weatherDate = new Date(allweather.list[closestForecastInd].dt_txt)
var str =
`Showing closest weather available: ${dateFormat(weatherDate, 'isoDate')} ${dateFormat(weatherDate, 'isoTime')}
Weather type: ${weather.weather[0].description}
Temperature: ${weather.main.temp} °C
Humidity: ${weather.main.humidity}%
Wind speed: ${weather.wind.speed} m/s
Cloudiness: ${weather.clouds.all}%`
result.resolve(str)
})
return result
}
/*
* Send a text message using the Send API.
*
*/
function sendTextMessage(recipientId, messageText) {
var messageData = {
recipient: {
id: recipientId
},
message: {
text: messageText,
metadata: "DEVELOPER_DEFINED_METADATA"
}
}
callSendAPI(messageData)
}
/*
* Send a read receipt to indicate the message has been read
*
*/
function sendReadReceipt(recipientId) {
console.log("Sending a read receipt to mark message as seen")
var messageData = {
recipient: {
id: recipientId
},
sender_action: "mark_seen"
}
callSendAPI(messageData)
}
/*
* Turn typing indicator on
*
*/
function sendTypingOn(recipientId) {
console.log("Turning typing indicator on")
var messageData = {
recipient: {
id: recipientId
},
sender_action: "typing_on"
}
callSendAPI(messageData)
}
/*
* Turn typing indicator off
*
*/
function sendTypingOff(recipientId) {
console.log("Turning typing indicator off")
var messageData = {
recipient: {
id: recipientId
},
sender_action: "typing_off"
}
callSendAPI(messageData)
}
/*
* Send a read receipt to indicate the message has been read
*
*/
function sendReadReceipt(recipientId) {
console.log("Sending a read receipt to mark message as seen")
var messageData = {
recipient: {
id: recipientId
},
sender_action: "mark_seen"
}
callSendAPI(messageData)
}
/*
* Call the Send API. The message data goes in the body. If successful, we'll
* get the message id in a response
*
*/
function callSendAPI(messageData) {
console.log(messageData)
request(
{
uri: 'https://graph.facebook.com/v2.6/me/messages',
qs: { access_token: PAGE_ACCESS_TOKEN },
method: 'POST',
json: messageData
}, (error, response, body) => {
if (!error && response.statusCode == 200) {
var recipientId = body.recipient_id
var messageId = body.message_id
if (messageId) {
console.log(`Successfully sent message with id ${messageId} to recipient ${recipientId}`)
} else {
console.log(`Successfully called Send API for recipient ${recipientId}`)
}
} else {
console.log(error || response.statusCode)
}
})
}
// Start server
app.listen(app.get('port'), () => {
console.log(`Node app is running on port ${app.get('port')}`)
})
module.exports = app