-
Notifications
You must be signed in to change notification settings - Fork 51
/
webhook.js
181 lines (159 loc) · 5.05 KB
/
webhook.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
'use strict';
const PAGE_ACCESS_TOKEN = process.env.PAGE_ACCESS_TOKEN;
const APIAI_TOKEN = process.env.APIAI_TOKEN;
const WEATHER_API_KEY = process.env.WEATHER_API_KEY;
const express = require('express');
const bodyParser = require('body-parser');
const request = require('request');
const apiai = require('apiai');
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
const server = app.listen(process.env.PORT || 5000, () => {
console.log('Express server listening on port %d in %s mode', server.address().port, app.settings.env);
});
const apiaiApp = apiai(APIAI_TOKEN);
/* For Facebook Validation */
app.get('/webhook', (req, res) => {
if (req.query['hub.mode'] && req.query['hub.verify_token'] === 'tuxedo_cat') {
res.status(200).send(req.query['hub.challenge']);
} else {
res.status(403).end();
}
});
/* Handling all messenges */
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) {
receivedMessage(event);
}
});
});
res.status(200).end();
}
});
/* GET query from API.ai */
function receivedMessage(event) {
let sender = event.sender.id;
let text = event.message.text;
let apiai = apiaiApp.textRequest(text, {
sessionId: 'tabby_cat'
});
apiai.on('response', (response) => {
let aiText = response.result.fulfillment.speech;
console.log(aiText);
switch (aiText) {
case 'SHOW_BIOGRAPHY':
prepareSendBio(sender);
break;
default:
prepareSendAiMessage(sender, aiText);
}
});
apiai.on('error', (error) => {
console.log(error);
});
apiai.end();
}
function sendMessage(messageData) {
request({
url: 'https://graph.facebook.com/v2.6/me/messages',
qs: {access_token: PAGE_ACCESS_TOKEN},
method: 'POST',
json: messageData
}, (error, response) => {
if (error) {
console.log('Error sending message: ', error);
} else if (response.body.error) {
console.log('Error: ', response.body.error);
}
});
}
function prepareSendAiMessage(sender, aiText) {
let messageData = {
recipient: {id: sender},
message: {text: aiText}
};
sendMessage(messageData);
}
function prepareSendBio(sender) {
let messageData = {
recipient: {
id: sender
},
message: {
attachment: {
type: 'template',
payload: {
template_type: 'generic',
elements: [{
title: 'Twitter',
subtitle: '@girlie_mac',
item_url: 'https://www.twitter.com/girlie_mac',
image_url: 'https://raw.githubusercontent.com/girliemac/fb-apiai-bot-demo/master/public/images/tomomi-twitter.png',
buttons: [{
type: 'web_url',
url: 'https://www.twitter.com/girlie_mac',
title: 'View Twitter Bio'
}],
}, {
title: 'Work History',
subtitle: 'Tomomi\'s LinkedIn',
item_url: 'https://www.linkedin.com/in/tomomi',
image_url: 'https://raw.githubusercontent.com/girliemac/fb-apiai-bot-demo/master/public/images/tomomi-linkedin.png',
buttons: [{
type: 'web_url',
url: 'https://www.linkedin.com/in/tomomi',
title: 'View LinkedIn'
}]
}, {
title: 'GitHub Repo',
subtitle: 'girliemac',
item_url: 'https://github.com/girliemac',
image_url: 'https://raw.githubusercontent.com/girliemac/fb-apiai-bot-demo/master/public/images/tomomi-github.png',
buttons: [{
type: 'web_url',
url: 'https://github.com/girliemac',
title: 'View GitHub Repo'
}]
}]
}
}
}
};
sendMessage(messageData);
}
/* Webhook for API.ai to get response from the 3rd party API */
app.post('/ai', (req, res) => {
console.log('*** Webhook for api.ai query ***');
console.log(req.body.result);
if (req.body.result.action === 'weather') {
console.log('*** weather ***');
let city = req.body.result.parameters['geo-city'];
let restUrl = 'http://api.openweathermap.org/data/2.5/weather?APPID='+WEATHER_API_KEY+'&q='+city;
request.get(restUrl, (err, response, body) => {
if (!err && response.statusCode == 200) {
let json = JSON.parse(body);
console.log(json);
let tempF = ~~(json.main.temp * 9/5 - 459.67);
let tempC = ~~(json.main.temp - 273.15);
let msg = 'The current condition in ' + json.name + ' is ' + json.weather[0].description + ' and the temperature is ' + tempF + ' ℉ (' +tempC+ ' ℃).'
return res.json({
speech: msg,
displayText: msg,
source: 'weather'
});
} else {
let errorMessage = 'I failed to look up the city name.';
return res.status(400).json({
status: {
code: 400,
errorType: errorMessage
}
});
}
})
}
});