-
Notifications
You must be signed in to change notification settings - Fork 38
Expand file tree
/
Copy pathindex.js
More file actions
51 lines (42 loc) · 1.44 KB
/
Copy pathindex.js
File metadata and controls
51 lines (42 loc) · 1.44 KB
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
const express = require('express')
const bodyParser = require('body-parser')
const app = express()
app.use(bodyParser.json())
app.set('port', (process.env.PORT || 5000))
const REQUIRE_AUTH = true
const AUTH_TOKEN = 'an-example-token'
app.get('/', function (req, res) {
res.send('Use the /webhook endpoint.')
})
app.get('/webhook', function (req, res) {
res.send('You must POST your request')
})
app.post('/webhook', function (req, res) {
// we expect to receive JSON data from api.ai here.
// the payload is stored on req.body
console.log(req.body)
// we have a simple authentication
if (REQUIRE_AUTH) {
if (req.headers['auth-token'] !== AUTH_TOKEN) {
return res.status(401).send('Unauthorized')
}
}
// and some validation too
if (!req.body || !req.body.result || !req.body.result.parameters) {
return res.status(400).send('Bad Request')
}
// the value of Action from api.ai is stored in req.body.result.action
console.log('* Received action -- %s', req.body.result.action)
// parameters are stored in req.body.result.parameters
var userName = req.body.result.parameters['given-name']
var webhookReply = 'Hello ' + userName + '! Welcome from the webhook.'
// the most basic response
res.status(200).json({
source: 'webhook',
speech: webhookReply,
displayText: webhookReply
})
})
app.listen(app.get('port'), function () {
console.log('* Webhook service is listening on port:' + app.get('port'))
})