app.js
12.6 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
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
'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('public'));
app.use('/images', express.static(__dirname + '/images'));
app.use(bodyParser.json());
app.use(bodyParser.text());
app.use(bodyParser.urlencoded({
extended: false
})); //post에서bodyparser로 받기 위함
app.set('views', __dirname + '/views');
app.set('views engine', 'ejs');
var price;
var shape = [];
var kinds = [];
var food_value='경희대학교 국제캠퍼스';
// 3번 단계에서 얻은 토큰을 넣어줍니다 . 개인 깃에 올릴 경우 이 부분은 절대 커밋하지 마세요.
var PAGE_ACCESS_TOKEN = 'EAARyuiC0CQ0BADOlzIk6y5bwfVs21Rom3b6Hk85IdGaDVSGblyvyj9IxiZA9hTkVZBFIUqGJxyZAMjkzFVWcwVcUgKxjpp5vuuwymg0oWA5gAbDtZCq4RR5x7n1SibAuNqSsEme4g5UdLa9CdtnHOo83dTmtipvFJMrCcnOhDgZDZD';
//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);
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';
var My_webpage = 'https://36b421e6.ngrok.io/food/search';
sendTextMessage(senderId, '제가 추천해드리는 음식이에욤:>');
sendTextMessage(senderId, food_value);
sendTextMessage(senderId, food_address);
sendTextMessage(senderId,"저희 웹사이트도 방문해보실래요? : " + My_webpage);
// 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);
}
});
}
//main page
app.get(['/food', '/food/:id'], function(req, res) {
var id = req.params.id;
if (id) {
if (id == 'search') {
res.render('map.ejs', {
title: 'Searching',
searching: food_value
});
} else if (id == 'recommendation') {
res.render('recommendation.ejs', {
title: 'Recommendation',
description: 'Enter the conditions you want.'
});
}
} else {
res.render('index.ejs', {
title: 'Welcome',
description: 'Hello, Here is our homepage.'
});
}
})
//사용자가 호출한 search page
app.post('/food/search', function(req, res) {
var title = req.body.title;
res.render('map.ejs', {
title: 'Search',
searching: food_value
});
// res.redirect("https://www.google.com/search?q=" + title + "&oq=" + title + "&aqs=chrome..69i57j0l3j69i60j69i61.3149j0j9&sourceid=chrome&ie=UTF-8")
})
//사용자가 호출한 recommendation page
app.post('/food/recommendation', function(req, res) {
fs.readFile('data/food.json', 'utf8', function(err, data) {
if (err) {
console.log((err));
res.status(500).send('Internal Server Error');
} else {
var users = JSON.parse(data);
var price = req.body.price;
var shape = req.body.shape;
var kinds = req.body.kinds;
if (!Array.isArray(shape) && shape) {
var shape = [];
shape.push(req.body.shape);
}
if (!Array.isArray(kinds) && kinds) {
var kinds = [];
kinds.push(req.body.kinds);
}
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) {
for (var i = 0; i < shape.length; i++) {
if (users[foods]['shape'] == shape[i]) {
set1.add(foods);
}
}
} else {
set1.add(foods);
}
if (kinds) {
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) + 5000 && users[foods]['price'] >= Number(price) - 5000)) {
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); //(Math.random() * (max - min)) + min
var food_value = food[rand];
var food_picture = '/images/' + food_value + ".png";
console.log('랜덤 food 번호: '+rand);
res.render('print.ejs', {
title: 'Recommendation',
description: 'We recommend this...',
randvalue: food_value,
picture : food_picture
}); //rander closed
}); //add closed
}
}); //readFile closed
}); //post closed
app.listen(app.get('port'), () => {
console.log('running on port', app.get('port'));
})