app.js
3.14 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
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
'use strict'
const express = require('express');
const bodyParser = require('body-parser');
const request = require('request');
const app = express();
// 3번 단계에서 얻은 토큰을 넣어줍니다 . 개인 깃에 올릴 경우 이 부분은 절대 커밋하지 마세요.
var PAGE_ACCESS_TOKEN = 'EAAIZBdEhUzlcBAAy7a21fSEuW76k1ABpld4ncE0XcrRv902dy56lZAZCAZANmKifUVah2H5j94xZBpmWAVGR9bhVlouzYyykVJ0XD447ju4Wco2G08jroUdF9hU1FZCILBSZAJxmgkoTYbCQ2FQ8xZByvsDGZAPVPvtBHL51ZCTfOiEgZDZD';
app.set('port', (process.env.PORT || 5000));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.get('/', (req, res) => {
res.send('Hello world');
})
// 페이스북 연결
app.get('/webhook', (req, res) => {
//if (req.query['hub.verify_token'] === 'VERIFY_TOKEN') {
if (req.query['hub.verify_token'] === PAGE_ACCESS_TOKEN) {
res.send(req.query['hub.challenge']);
}
res.send('Error, wrong token');
})
app.post("/webhook", (req, res) => {
console.log("WEBHOOK GET IT WORKS");
var data = req.body;
console.log(data);
// 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.optin) {
receivedAuthentication(messagingEvent);
} else if (messagingEvent.message) {
receivedMessage(messagingEvent);
} else if (messagingEvent.postback) {
receivedPostback(messagingEvent);
} else {
console.log("Webhook received unknown messagingEvent: ", messagingEvent);
}
});
});
res.sendStatus(200);
}
});
// 메세지 받고 내보내기
function receivedMessage(event) {
var senderId = event.sender.id;
var content = event.message.text;
var bot_message = content;
sendTextMessage(senderId, bot_message);
}
function receivedPostback(event) {
console.log("RECEIVED POSTBACK IT WORKS");
var senderID = event.sender.id;
var recipientID = event.recipient.id;
var timeOfPostback = event.timestamp;
var payload = event.postback.payload;
console.log("Received postback for user %d and page %d with payload '%s' " +
"at %d", senderID, recipientID, payload, timeOfPostback);
sendTextMessage(senderID, "Postback called");
}
function sendTextMessage(recipientId, message) {
request({
url: 'https://graph.facebook.com/v2.6/me/messages',
qs: { access_token: PAGE_ACCESS_TOKEN },
method: 'POST',
json: {
recipient: { id: recipientId },
message: { text: message }
}
}, (error, response, body) => {
if (error) {
console.log('Error sending message: ' + response.error);
}
});
}
app.listen(app.get('port'), () => {
console.log('running on port', app.get('port'));
})