app.js
8.96 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
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
'use strict'
const express = require('express');
const bodyParser = require('body-parser');
const request = require('request');
const app = express();
var fs = require("fs");
app.use(express.static('images'));
app.use(bodyParser.json());
app.use(bodyParser.text());
app.use(bodyParser.urlencoded({
extended: false
})); //post에서bodyparser로 받기 위함
var price;
var shape = [];
var kinds = [];
// 3번 단계에서 얻은 토큰을 넣어줍니다 . 개인 깃에 올릴 경우 이 부분은 절대 커밋하지 마세요.
var PAGE_ACCESS_TOKEN = 'EAATExQZAyiJ0BAAcfdgDOytqZCz6XZCCW05NRT7S2dpHbyxRw71m3RBm66Alu3BJLLU6hvLCMK5VYXSppy9BzDlpZB3BwNHgKJQrZAKfyKX5x2VYlYQApR3cGMl0Q27m8EJ7vZAIxEtKZAmSrNImbUmyyx5ZCiyqoTc9W63IYUg1dgZDZD';
//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') {
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) {
var quest = messagingEvent.message.text;
var price = quest;
if (((quest.search('음식') != -1) || (quest.search('추천') != -1)) || ((quest.search('뭐') != -1) && (quest.search('먹') != -1))) {
receivedMessage_price(messagingEvent);
} else if (price == Number(price)) {
price = Number(price);
sendTextMessage(messagingEvent.sender.id, '원하시는 음식 카테고리가 있나요?');
} else if ((quest.search('한식') != -1) || (quest.search('중식') != -1) || (quest.search('일식') != -1) || (quest.search('양식') != -1)) {
if ((quest.search('한식') != -1))
kinds.push('한식');
if ((quest.search('중식') != -1))
kinds.push('중식');
if (quest.search('일식') != -1)
kinds.push('일식');
if ((quest.search('양식') != -1))
kinds.push('양식');
sendTextMessage(messagingEvent.sender.id, '원하시는 음식 형태가 있나요?');
} else if ((quest.search('밥') != -1) || (quest.search('면') != -1) || (quest.search('고기') != -1) || (quest.search('기타') != -1)) {
if ((quest.search('밥') != -1))
shape.push('밥');
if ((quest.search('면') != -1))
shape.push('면');
if (quest.search('고기') != -1)
shape.push('고기');
if ((quest.search('기타') != -1))
shape.push('기타');
receivedMessage_recommend(messagingEvent);
} else if ((quest.search('먹을까') != -1) || (quest.search('말까') != -1)) {
receivedMessage_select(messagingEvent);
} else {
receivedMessage(messagingEvent);
}
} else if (messagingEvent.postback) {
receivedPostback(messagingEvent);
} else {
console.log("Webhook received unknown messagingEvent: ", messagingEvent);
}
});
});
res.sendStatus(200);
}
});
// 메세지 받고 내보내기
function receivedMessage_recommend(event) {
var senderId = event.sender.id;
var content = event.message.text;
var bot_message = content;
fs.readFile('data/food.json', 'utf8', function(err, food_data) {
if (err) {
console.log((err));
res.status(500).send('Internal Server Error');
} else {
var users = JSON.parse(food_data);
var set1 = new Set();
var set2 = new Set();
var set3 = new Set();
function add(users, price, shape, kinds, callback) {
for (var foods in users) {
if (shape.length != 0) {
for (var i = 0; i < shape.length; i++) {
if (users[foods]['shape'] == shape[i]) {
set1.add(foods);
}
}
} else {
set1.add(foods);
}
if (kinds.length != 0) {
for (var j = 0; j < kinds.length; j++) {
if (users[foods]['kinds'] == kinds[j]) {
set2.add(foods);
}
}
} else {
set2.add(foods);
}
if (!price || (price && users[foods]['price'] <= Number(price) + 3000 && users[foods]['price'] >= Number(price) - 3000)) {
set3.add(foods);
}
}
callback(set1, set2, set3);
}
add(users, price, shape, kinds, function(set1, set2, set3) {
let difference1 = new Set([...set1].filter(i => set2.has(i)));
let difference2 = new Set([...difference1].filter(i => set3.has(i)));
var food = [...difference2];
var length = food.length;
console.log('food 목록: ' + food);
console.log('food 갯수: ' + length);
var rand = Math.floor(Math.random() * length);
var food_value = food[rand];
console.log('랜덤 food 번호: ' + rand);
price = '';
shape = [];
kinds = [];
var food_address = 'https://map.naver.com/v5/search/'+food_value+'?c=14145162.8039144,4473559.4748438,14,0,0,0,dh';
sendTextMessage(senderId, '제가 추천해드리는 음식이에욤:>');
sendTextMessage(senderId, food_value);
sendTextMessage(senderId, food_address);
// sendTextMessage(senderId, /data/images/food_value.png);
}); //add closed
}
}); //readFile closed
}
function receivedMessage(event) {
var senderId = event.sender.id;
var content = event.message.text;
var bot_message = content;
var happpy = ['오늘은 무엇을 드실건가요?:)', '뿌에에ㅔ엥', '헣', '저한테 왜그러시는거죠?', '뭐지', '그러쿤요!', '훌쩍', '쒸익쒸익', '뭐하시는거죠?', '눈물', '세상에', '이게무슨일이람', 'ㅋㅋㅋㅋㅋㅋㅋㅋ', '무야', '아니이ㅣㅣ', '네에ㅔㅔ', '찡긋', '(당근 흔드는 중)', '도와주세요', '살려줘'];
var rand = Math.floor(Math.random() * happpy.length);
sendTextMessage(senderId, happpy[rand]);
}
function receivedMessage_select(event) {
var senderId = event.sender.id;
var content = event.message.text;
var answer = ['먹어', '먹지마'];
var rand = Math.floor(Math.random() * answer.length);
sendTextMessage(senderId, answer[rand]);
}
function receivedMessage_price(event) {
var senderId = event.sender.id;
var content = event.message.text;
var bot_message = content;
var recom = ['제가 추천해드릴까욤??', '에휴 결정장애시구먼요. 제가 추천해드릴게요', '밥먹어요!! 추천해줄게요', '뭐드시고 싶어요?? 추천해줄게욤'];
var rand = Math.floor(Math.random() * recom.length);
sendTextMessage(senderId, recom[rand]);
sendTextMessage(senderId, "가격대를 입력하시겠어요? :)");
}
function receivedMessage_map(event) {
var senderId = event.sender.id;
var content = event.message.text;
var bot_message = content;
var recom = ['제가 추천해드릴까욤??', '에휴 결정장애시구먼요. 제가 추천해드릴게요', '밥먹어요!! 추천해줄게요', '뭐드시고 싶어요?? 추천해줄게욤'];
var rand = Math.floor(Math.random() * recom.length);
sendTextMessage(senderId, recom[rand]);
sendTextMessage(senderId, "가격대를 입력하시겠어요? :)");
}
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'));
})