-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex_without_wit.js
98 lines (88 loc) · 2.78 KB
/
index_without_wit.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
var express = require('express');
var bodyParser = require('body-parser');
var request = require('request');
var app = express();
app.set('port', (process.env.PORT || 5000));
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({extended: false}));
// parse application/json
app.use(bodyParser.json());
// index
app.get('/', function (req, res) {
res.send('hello world i am a secret bot')
});
// for facebook verification
app.get('/webhook/', function (req, res) {
if (req.query['hub.verify_token'] === process.env.VERIFY_TOKEN) {
res.send(req.query['hub.challenge'])
}
res.send('Error, wrong token')
});
// to post data
app.post('/webhook/', function (req, res) {
messaging_events = req.body.entry[0].messaging;
for (i = 0; i < messaging_events.length; i++) {
event = req.body.entry[0].messaging[i];
sender = event.sender.id;
if (event.message && event.message.text) {
text = event.message.text;
if (text === 'Yo') {
sendGenericMessage(sender);
continue;
}
sendTextMessage(sender, "Text received, echo: " + text.substring(0, 200));
}
if (event.postback) {
text = JSON.stringify(event.postback);
sendTextMessage(sender, "Postback received: "+text.substring(0, 200), token);
continue;
}
}
res.sendStatus(200)
});
var token = process.env.FB_PAGE_TOKEN;
var var_appsecret_proof = process.env.APP_SECRET_PROOF;
function sendTextMessage(sender, text) {
messageData = {
text:text
};
request({
url: 'https://graph.facebook.com/v2.6/me/messages',
qs: {access_token:token, appsecret_proof: var_appsecret_proof},
method: 'POST',
json: {
recipient: {id:sender},
message: messageData
}
}, function(error, response, body) {
if (error) {
console.log('Error sending messages: ', error);
} else if (response.body.error) {
console.log('Error: ', response.body.error);
}
})
}
function sendGenericMessage(sender) {
messageData = {
"text":"hello, world!"
};
request({
url: 'https://graph.facebook.com/v2.6/me/messages',
qs: {access_token:token, appsecret_proof: var_appsecret_proof},
method: 'POST',
json: {
recipient: {id:sender},
message: messageData
}
}, function(error, response, body) {
if (error) {
console.log('Error sending messages: ', error)
} else if (response.body.error) {
console.log('Error: ', response.body.error)
}
})
}
// spin spin sugar
app.listen(app.get('port'), function() {
console.log('running on port', app.get('port'));
});