app.js
5.29 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
//웹 프레임 웤
var express = require('express');
// 요청 리소스 표현 모듈
var request = require('request');
// api의 데이터포맷이 xml이므로 json으로 파싱할 필요가 있음
var convert = require('xml-js');
const bodyParser = require('body-parser');
// 라인 메신져
const TARGET_URL = 'https://api.line.me/v2/bot/message/reply'
const TOKEN = 'OPv3udmn1UGx+xWZFm80KeZbeGJm63nyt+sTpvBr1Mbc1Y0FAeK4MohQLcWq5yytJ6vnaNgXZfigAEFdbjzs05b4QAU+9r1jcZ05t6QvhWDTRYT0Z+YDMMePXtrQYCT84kmkH0OpJ4smBFwLxrtwtAdB04t89/1O/w1cDnyilFU='
// 공공보건포털_API
const CORONA_URL = 'http://openapi.data.go.kr/openapi/service/rest/Covid19/getCovid19InfStateJson';
const SERVICE_KEY = 'DMUPOq6b%2B%2F1gqfLEXQ6bnhgoTO73BfPprA6HVNcV%2F6vHMGG%2Bgiw%2BPDkPvX1eQ7b9uvl%2B42fxUPkU0W3Si907Lw%3D%3D'
// express 미들웨어 정의
var app = express();
app.use(bodyParser.json());
// 기타 비동기식 오류처리에 쓰일 모듈들
const fs = require('fs');
const path = require('path');
const HTTPS = require('https');
const { measureMemory } = require('vm');
const domain = "www.oss-chatbot-kwak.tk"
const sslport = 23023;
var date;
// 챗봇으로 입력
app.post('/hook', function (req, res) {
var eventObj = req.body.events[0];
var source = eventObj.source;
var message = eventObj.message;
// request log
console.log('======================', new Date() ,'======================');
console.log('[request]', req.body);
console.log('[request source] ', eventObj.source);
console.log('[request message]', eventObj.message);
//
if(message.text == '/코로나' || message.text == '/corona'){
request.post(
{
url: TARGET_URL,
headers: {
'Authorization': `Bearer ${TOKEN}`
},
json: {
"replyToken":eventObj.replyToken,
"messages":[
{
"type":"text",
"text":"확인하고 싶으신 일자를 적어주세요."
},
{
"type":"text",
"text":"예시) 20201209"
}
]
}
},(error, response, body) => {
console.log(body)
});
return;
}
else
{
date = message.text;
queryParams = '?' + encodeURIComponent('ServiceKey') + '=' + SERVICE_KEY; /* Service Key*/
queryParams += '&' + encodeURIComponent('pageNo') + '=' + encodeURIComponent('1'); /* */
queryParams += '&' + encodeURIComponent('numOfRows') + '=' + encodeURIComponent('4'); /* */
queryParams += '&' + encodeURIComponent('startCreateDt') + '=' + encodeURIComponent(date);
queryParams += '&' + encodeURIComponent('endCreateDt') + '=' + encodeURIComponent(date); /* */
bot_reply(eventObj.replyToken, message);
res.sendStatus(200);
}
});
function bot_reply(replyToken, message) {
request({
url: CORONA_URL + queryParams,
method: 'GET'
},(error, response, body) => {
if(!error && response.statusCode == 200) {
console.log('Status', response.statusCode);
console.log('Headers', JSON.stringify(response.headers));
var xmlToJson = convert.xml2json(response.body, {compact: true, spaces: 4});
const jsonData = JSON.parse(xmlToJson); // json text -> json object
console.log('Reponse received', xmlToJson); // json text
var resultMessage = jsonData.response.body.items.item;
request.post(
{
url: TARGET_URL,
headers: {
'Authorization': `Bearer ${TOKEN}`
},
json: {
"replyToken":replyToken,
"messages":[
{
"type":"text",
"text": '선택하신 날짜의 Corona Virus-19 현황은 다음과 같습니다.'
},
{
"type":"text",
"text": JSON.stringify(resultMessage)
}
]
}
},(error, response, body) => {
console.log(body)
});
}
});
}
// 오류처리
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);
}