forked from JE0112/emergencyRoom-ChatBot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
340 lines (287 loc) · 9.34 KB
/
app.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
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
const address = require('./Address.js');
const express = require('express');
const request = require('request');
const emergency = require('./emergency_api.js')
const sample = require('./Directions_15')
const fetch = () => import('node-fetch').then(({default: fetch}) => fetch());
require("dotenv").config( {path: "/home/ec2-user/emergencyRoom-ChatBot/.env"} );
const KAKAO_KEY = process.env.KAKAO_KEY;
const TOKEN = process.env.CHANNEL_ACCESS_TOKEN;;
const domain = process.env.MY_DOMAIN;
const KAKAO_URL = "https://dapi.kakao.com/v2/local/search/address.json?"
const KAKAO_PLACE_URL = "https://dapi.kakao.com/v2/local/search/keyword.json?"
const TARGET_URL = 'https://api.line.me/v2/bot/message/reply'
const fs = require('fs');
const path = require('path');
const HTTPS = require('https');
const sslport = 23023;
const bodyParser = require('body-parser');
const { stringify } = require('querystring');
const app = express();
var event_time = 1
var add_list = new Array();
var add_index = 0;
var confirmed = new Boolean(false);
var hospital_list = []
const delay = () => {
const randomDelay = Math.floor(Math.random() * 4) * 100
return new Promise(resolve => setTimeout(resolve, randomDelay))
}
// const agent = new HTTPS.Agent({
// keepAlive: true,
// });
function loading(eventObj,res){
request.post(
{
url: 'https://api.line.me/v2/bot/message/push',
headers: {
'Authorization': `Bearer ${TOKEN}`,
},
json: {
"to":eventObj.source.userId, //eventObj.replyToken
"messages":[
{
"type": "text", // ①
"text": "잠시만 기다려주세요."},
],
}
},(error, response, body) => {
});
}
const saveData = async (a,b,current_x,current_y,current_address,eventObj,line_res,req, res) => {
try{
emergency.getspot_xy(a,b).then(async (res)=> {
await loading(eventObj,line_res)
let addrJson ={}
addrJson["current_address"] = {"address" : current_address, "x" : current_x,"y" : current_y}
addrJson["hospital_data"] = res
sample.fetchAPI(addrJson,eventObj,line_res)
})
}
catch(e){
console.log(e);
}
}
function main(eventObj,res){
add_list = [];
add_index = 0;
request.post(
{
url: TARGET_URL,
headers: {
'Authorization': `Bearer ${TOKEN}`,
},
json: {
"replyToken":eventObj.replyToken, //eventObj.replyToken
"messages":[
{
"type": "text", // ①
"text": "응급 상황인가요?"},
{"type": "text",
"text": "현재있는 위치의 주소나 보이는 곳을 입력하세요."},
],
}
},(error, response, body) => {
});
res.sendStatus(200);
}
async function again(eventObj, res) {
await request.post(
{
url: TARGET_URL,
headers: {
'Authorization': `Bearer ${TOKEN}`,
},
json: {
"replyToken":eventObj.replyToken,
"messages":[
{
"type": "text",
"text": "요청하신 주소를 찾을 수 없습니다."},
{"type": "text",
"text": "정확한 주소 또는 장소 이름을 입력해 주세요. "},
],
}
},(error, response, body) => {
event_time=2;
res.sendStatus(200);
});
}
async function findme(eventObj, res) {
await request.get(
{
url: KAKAO_URL + new URLSearchParams(
{query: eventObj.message.text}
),
headers: {
"Authorization": KAKAO_KEY
}
}, (error, response, body) =>{
if(!error && response.statusCode == 200) {
jbody = JSON.parse(body);
add_list = jbody.documents;
console.log(add_list);
if (add_list.length == 0) {
async function findagain(eventObj, res) {
await request.get(
{
url: KAKAO_PLACE_URL + new URLSearchParams(
{query: eventObj.message.text}
),
headers: {
"Authorization": KAKAO_KEY
}
}, (error, response, body) =>{
if(!error && response.statusCode == 200) {
jbody = JSON.parse(body);
add_list = new Array();
add_list = jbody.documents;
// console.log("addlist PLACE !--- ", add_list)
find_current(eventObj, res);
}
}, ()=>{
res.sendStatus(200);
}
)
};
findagain(eventObj, res);
}
else {find_current(eventObj, res); }
}
}, ()=>{
res.sendStatus(200);
}
)
}
async function find_current(eventObj,res){
if (add_list.length <= add_index) {
console.log("no current address");
await again(eventObj, res);
} else {
var x = add_list[add_index].x
var y = add_list[add_index].y
var address_name = add_list[add_index].address_name
var string = "yes&&" + String(x) + "&&"+String(y) +"&&" + String(address_name)
await request.post(
{
url: TARGET_URL,
headers: {
'Authorization': `Bearer ${TOKEN}`,
},
json: {
"replyToken":eventObj.replyToken,
"messages":[
{
"type": "location",
"title": "현재 위치",
"address": add_list[add_index].address_name,
"longitude": parseFloat(add_list[add_index].x),
"latitude": parseFloat(add_list[add_index].y),
},
{
"type": "template",
"altText": "This is a buttons template",
"template": {
"type": "buttons",
"text": "이곳이 맞나요?",
"defaultAction": {
"type": "uri",
"label": "View detail",
"uri": "http://example.com/page/123"
},
"actions": [
{
"type": "postback",
"label": "네",
"data": string
},
{
"type": "postback",
"label": "아니요",
"data": "action=no"
},
{
"type": "postback",
"label": "다시 입력하기",
"data": "action=reset"
},
]
}
}
],
}
},(error, response) => {
// console.log(error);
// console.log(response.statusCode);
// console.log(response.statusMessage);
}
);
res.sendStatus(200);
}
}
app.use(bodyParser.json());
app.post('/hook', async function (req, res) {
var eventObj = req.body.events[0];
var headers = req.headers;
console.log('======================', new Date() ,'======================');
console.log("event_time: ", event_time);
if(event_time==1){
main(eventObj,res)
event_time=2
}
else if (event_time == 2) {
findme(eventObj, res);
event_time=3;
}
else if (event_time == 3){
let arr = eventObj.postback.data;
const string = arr.split("&&");
let action = string[0]
let current_adress_x = string[1]
let current_adress_y = string[2]
let current_address = string[3]
if(action =='yes'){
let a = current_address.split(' ')[0]
let b = current_address.split(' ')[1]
console.log(a,b)
saveData(a,b,current_adress_x,current_adress_y,current_address,eventObj,res);
event_time=1
}
else if (action == 'action=no'){
add_index++;
find_current(eventObj, res);
}
else{
add_list = [];
add_index = 0;
event_time = 2;
main(eventObj,res)
}
}
});
try {
const option = {
ca: fs.readFileSync('/etc/letsencrypt/live/' + domain +'/fullchain.pem'),
key: fs.readFileSync(path.resolve(process.cwd(), '/etc/letsencrypt/live/' + domain +'/privkey.pem'), 'utf8').toString(),
cert: fs.readFileSync(path.resolve(process.cwd(), '/etc/letsencrypt/live/' + domain +'/cert.pem'), 'utf8').toString(),
};
HTTPS.createServer(option, app).listen(sslport, () => {
console.log(`[HTTPS] Server is started on port ${sslport}`);
});
} catch (error) {
console.log('[HTTPS] HTTPS 오류가 발생하였습니다. HTTPS 서버는 실행되지 않습니다.');
console.log(error);
}
// function arr_compare(arr, arr_xy){
// var i;
// var j = 0;
// var hospital_xy_data = []
// var length = arr_xy.length;
// for( i = 0;i<length;i++){
// if(arr[j].병원이름 == arr_xy[i].병원이름){
// hospital_xy_data.push(arr_xy[i]);
// j += 1;
// }
// }
// return hospital_xy_data;
// }