app.js
11.4 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
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
var express = require('express');
const request = require('request');
const TARGET_URL = 'https://api.line.me/v2/bot/message/reply'
const TOKEN = '9odQvyPPtDEzqHdfdk8Q8ua6dgrffTQuJnpkYuM6Q0VTREhmU+NJ0BAVCIfo2gEDtD37TYC0TZ7MrijHZeA592eUwzb+quftcHXBa0hye5iZHK0G4HiZCnB9C2bLgQvgQVJ47DwGeBQlwaNVJvze1AdB04t89/1O/w1cDnyilFU='
const PAPAGO_URL = 'https://openapi.naver.com/v1/papago/n2mt'
const PAPAGO_D_URL = 'https://openapi.naver.com/v1/papago/detectLangs'
const PAPAGO_ID = 'tA41WEd_nbzy0nZcUQks'
const PAPAGO_SECRET = '6DHwov9gg2'
const WEATHER_TARGET_URL = 'http://apis.data.go.kr/1360000/VilageFcstInfoService/getVilageFcst';
const weather_key = 'CuIdcpULvcissE3Jk7AyAXok4bR4j6xyNkhfmWxOI9%2BxCs%2FkI%2F4v4j4rz3DDsQZVeuJTrWQhzQ3CV4JkeykMSw%3D%3D';
const fs = require('fs');
const path = require('path');
const HTTPS = require('https');
const domain = "www.theia17.tk"
const sslport = 23023;
const bodyParser = require('body-parser');
var app = express();
var async = require('async');
const { resolve } = require('path');
var Language_Detect_Array = new Array();
var User_Info_Array = new Array();
var Weahter_Detect_Array = new Array();
Weahter_Detect_Array[0] =
{
"Region" : '수원',
"nx" : 61,
"ny" : 120
}
Weahter_Detect_Array[1] =
{
"Region" : '서울',
"nx" : 60,
"ny" : 127
}
Weahter_Detect_Array[2] =
{
"Region" : '밀양',
"nx" : 92,
"ny" : 83
}
Language_Detect_Array[0] =
{
"Message" : '영어',
"PapagoLanguage" : 'en'
}
Language_Detect_Array[1] =
{
"Message" : '일본어',
"PapagoLanguage" : 'ja'
}
Language_Detect_Array[2] =
{
"Message" : '프랑스어',
"PapagoLanguage" : 'fr'
}
Language_Detect_Array[3] =
{
"Message" : '한국어',
"PapagoLanguage" : 'ko'
}
User_Info_Array[0] =
{
UserId : null,
UserPapagoLanguage : '',
UserRegion : '수원',
}
app.use(bodyParser.json());
app.post('/hook', function (req, res) {
var eventObj = req.body.events[0];
var message = eventObj.message.text;
var replyToken = eventObj.replyToken;
var userid = eventObj.source.userId;
AsyncFunction(message, replyToken, userid);
res.sendStatus(200);
});
async function AsyncFunction(message, replyToken, userid)
{
var User_Location = search_user_info(userid);
var DetectLanguage = await detector(message);
if(DetectLanguage != 'ko') var TransToKoreanMessage = await trans(DetectLanguage, message, 'ko'); else var TransToKoreanMessage = message;
console.log(TransToKoreanMessage);
var DetectChange = Detect_Papago_Language_Change(TransToKoreanMessage, User_Location);
if (DetectChange) DetectChange = Detect_Weather_Region_Change(TransToKoreanMessage, User_Location);
if(TransToKoreanMessage != '날씨')
{
if(DetectLanguage != User_Info_Array[User_Location].UserPapagoLanguage) var TransToUserSettingMessage = await trans(DetectLanguage, message, User_Info_Array[User_Location].UserPapagoLanguage);
var Messaging = await messaging(TransToUserSettingMessage, replyToken, DetectChange);
console.log("log-Message: ", Messaging);
}
else
weathercheck(replyToken, userid, DetectLanguage);
}
async function weathercheck(replyToken, userid, DetectLanguage)
{
var User_Location = search_user_info(userid);
var location = user_location(User_Location);
var timevalue = make_time()
var url = make_url(timevalue, location);
var message = await weather_get(url, User_Location);
if(DetectLanguage != 'ko')
message = await trans ('ko', message, DetectLanguage)
var Messaging = await messaging(message, replyToken, 1);
console.log("log-Message: ", Messaging);
}
function detector (message)
//언어 감지
{
return new Promise(function(resolve, reject)
{
request.post
(
{
url: PAPAGO_D_URL,
headers:
{
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
'X-Naver-Client-Id': `${PAPAGO_ID}`,
'X-Naver-Client-Secret': `${PAPAGO_SECRET}`
},
body: 'query='+message,
json:true
},(error, response, body) =>
{
if(!error && response.statusCode == 200)
{
var DetectLanguage = body.langCode;
resolve(DetectLanguage);
}
else
{
reject(new Error('Request is failed'));
}
}
)
})
}
function messaging(message, replyToken, DetectChange)
//메시지 보내기
{
return new Promise(function(resolve, reject)
{
if(DetectChange)
request.post
(
{
url: TARGET_URL,
headers:
{
'Authorization': `Bearer ${TOKEN}`
},
json:
{
"replyToken":replyToken,
"messages":
[
{
"type":"text",
"text":message
}
]
}
}, (error, response, body) =>
{
if(!error && response.statusCode == 200)
resolve('정상적으로 전송 되었습니다.');
}
);
})
}
function trans (DetectLanguage, message, TransLanguage)
//언어 번역
{
return new Promise(function(resolve, reject)
{
request.post(
{
url: PAPAGO_URL,
headers:
{
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
'X-Naver-Client-Id': `${PAPAGO_ID}`,
'X-Naver-Client-Secret': `${PAPAGO_SECRET}`
},
body: 'source='+DetectLanguage+'&target='+TransLanguage+'&text='+message,
json:true
},(error, response, body) =>
{
if(!error && response.statusCode == 200)
{
var transMessage = body.message.result.translatedText;
console.log('transMessage: ', transMessage);
resolve(transMessage);
}
}
);
})
}
function search_user_info (userid)
//유저 생성 또는 위치 찾기
{
for(var i in User_Info_Array)
{
if (User_Info_Array[i].UserId == userid)
{
//기존 유저
return i;
break;
}
else if ( i == User_Info_Array.length-1)
{
//새로운 유저
User_Info_Array[User_Info_Array.length] =
{
UserId : userid,
UserPapagoLanguage : 'en',
UserRegion : '수원'
}
return User_Info_Array.length-1;
}
}
}
function Detect_Papago_Language_Change (TransToKoreanMessage, User_Location)
//번역 언어 변경 감지
{
for(var i in Language_Detect_Array) // Detect Language change
{
if (TransToKoreanMessage == Language_Detect_Array[i].Message)
{
//언어 변경 감지o
User_Info_Array[User_Location].UserPapagoLanguage = Language_Detect_Array[i].PapagoLanguage;
return 0;
break;
}
else if ( i == Language_Detect_Array.length-1)
{
//언어 변경 감지x
return 1;
}
}
}
function Detect_Weather_Region_Change (TransToKoreanMessage, User_Location)
//지역 변경 감지
{
for(var i in Weahter_Detect_Array)
{
if (TransToKoreanMessage == Weahter_Detect_Array[i].Region)
{
//지역 변경 감지o
User_Info_Array[User_Location].UserRegion = Weahter_Detect_Array[i].Region
return 0;
break;
}
else if ( i == Weahter_Detect_Array.length-1)
{
//지역 변경 감지x
return 1;
}
}
}
function make_time()
{
var today = new Date();
var value = new Object();
var dd = today.getDate();
var mm = today.getMonth()+1;
var yyyy = today.getFullYear();
var hours = today.getHours();
var minutes = today.getMinutes();
for (var i = 1; i<8; i++)
{
var temp = i+1;
if(3*i-1 <= hours && 3*temp-1 >= hours)
{
if(3*i-1<10)
value.hours = '0'+3*i-1;
else
value.hours = 3*i-1;
value.hours = 3*i-1+'00';
break;
}
}
if(minutes < 30){
// 30분보다 작으면 한시간 전 값
hours = hours - 1;
if(hours < 0){
// 자정 이전은 전날로 계산
today.setDate(today.getDate() - 1);
dd = today.getDate();
mm = today.getMonth()+1;
yyyy = today.getFullYear();
hours = 23;
}
}
if(hours<10) {
hours='0'+hours
}
if(mm<10) {
mm='0'+mm
}
if(dd<10) {
dd='0'+dd
}
today = yyyy+""+mm+""+dd;
value.today = today;
return value;
}
function make_url(timevalue, location)
{
var serviceKey = weather_key;
var pageNo = '1';
var numOfRows = '5';
var dataType = 'JSON';
var base_date = timevalue.today;
var base_time = timevalue.hours;
var nx = location.nx;
var ny = location.ny;
var url = `${WEATHER_TARGET_URL}`;
url += '?serviceKey='+serviceKey;
url += '&pageNo='+pageNo;
url += '&numOfRows='+numOfRows;
url += '&dataType='+dataType;
url += '&base_date='+base_date;
url += '&base_time='+base_time;
url += '&nx='+nx;
url += '&ny='+ny;
return url;
}
function user_location(User_Location)
{
var location_info = new Object();
for(var i in Weahter_Detect_Array)
{
if (User_Info_Array[User_Location].UserRegion == Weahter_Detect_Array[i].Region)
{
location_info.nx = Weahter_Detect_Array[i].nx;
location_info.ny = Weahter_Detect_Array[i].ny;
return location_info;
break;
}
}
}
function weather_get (url, User_Location)
{
return new Promise(function(resolve, reject)
{
request.get(
{
url: url,
},(error, response, body) =>
{
if(!error && response.statusCode == 200)
{
var weatherObj = JSON.parse(response.body);
resolve(User_Info_Array[User_Location].UserRegion+'에 4시간 안에 비가 올 확률은 '+weatherObj.response.body.items.item[0].fcstValue+'% 입니다.');
}
else{
console.log('Error', error);
}
}
)
});
}
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);
}
app.listen(23023, function () {
console.log('Linebot listening on port 23023!');
});