app.js
14.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
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
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
const fs = require('fs');
const express = require('express');
const app = express();
const port = 80;
const axios = require('axios');
const cheerio = require('cheerio');
const url = 'http://lol.inven.co.kr/dataninfo/proteam/progamer.php?code=135';
const request = require('request');
const TARGET_URL = 'https://api.line.me/v2/bot/message/reply';
const TOKEN = 'ihoYpWsdObaqmCnQ7nqwBfSGiLV4v3OZSqccIK9osz9y9pOMiKgEpmJ8fHiiBT0rF5wZoa2bRGTQjZ7al4yseviaYPsROO4nyiygZi8lvW2xcD6yakxXZ91eNmzz8e6fQ32IPZ577Iagx/kEQ/UMgAdB04t89/1O/w1cDnyilFU=';
const path = require('path');
const HTTPS = require('https');
const domain = "www.sekechatbot.tk"
const sslport = 23023;
const bodyParser = require('body-parser');
const version = '0.1';
const dataFileName = 'data.json';
var fakerData = {};
var quizList = [];
var isWaitAns = false;
var users = {};
var sumOfStreak = 0;
var sumOfTry = 0;
async function checkData() {
try {
if (fakerData.version == version) {
console.log("이미 데이터가 존재합니다.");
var today = new Date();
var dateInfo = `${today.getFullYear()}/${today.getMonth() + 1}/${today.getDate()}`;
if (fakerData.date != dateInfo)
{
console.log("오래된 데이터입니다. 데이터를 크롤링합니다.");
await getData();
}
}
else if (fakerData.version == undefined) {
const dataBuffer = fs.readFileSync(dataFileName);
console.log("데이터를 읽습니다.");
fakerData = JSON.parse(dataBuffer.toString());
console.log(fakerData);
}
else {
console.log("버전이 다릅니다. 데이터를 크롤링합니다.");
await getData();
}
}
catch (exception) {
if (exception.code == "ENOENT") {
console.log("데이터 파일이 존재하지 않습니다. 데이터를 크롤링합니다.");
await getData();
}
else {
console.log(exception);
}
}
generateQuiz();
return new Promise(function (resolve, reject) {
resolve();
});
}
async function getHTML() {
try {
return axios.get(url);
} catch (error) {
console.error(error);
return null;
}
};
async function getData() {
const html = await getHTML();
if (html == null) {
return;
}
fakerData['version'] = version;
var today = new Date();
var dateInfo = `${today.getFullYear()}/${today.getMonth() + 1}/${today.getDate()}`;
fakerData['date'] = dateInfo;
const $ = cheerio.load(html.data);
var playerName = $('div#lolMain h2.block.name').text().split(' ');
fakerData['name'] = playerName[playerName.length - 1];
//#region LCK 통산 전적
var tr = $('table.table.log_list.log01 tbody').children();
var td = tr.eq(0).children();
fakerData['lCK'] = {
totalGamePlay: td.eq(1).text(),
totalWin: td.eq(2).text(),
totalLose: td.eq(3).text(),
winRate: td.eq(4).text(),
killPerMatch: td.eq(5).text(),
deathPerMatch: td.eq(6).text(),
assistPerMatch: td.eq(7).text(),
kDA: td.eq(8).text(),
kP: td.eq(9).text()
};
//#endregion
//#region 최근 LCK 기록
var recentLCKInfo = $('div.block.scriptorium_box.scriptorium_player_info').children().eq(2);
var mostInfo = recentLCKInfo.find('div.left ul.block.list').children();
var mostList = [];
var indicatorInfo = recentLCKInfo.find('div.right ul.block.bottom.clearfix').children();
mostInfo.each(function (i, elem) {
mostList[i] = {
champion: $(this).find('div.name_area p.value b').text(),
played: $(this).find('div.play_area p.value').text(),
record: $(this).find('div.log_area p.value').text(),
kDA: $(this).find('div.kda_area p.value').text()
};
});
fakerData['recentLCK'] = {
name: recentLCKInfo.find('h3.block.player_sub_title.clearfix').text(),
most: mostList,
comparison_WinRate: indicatorInfo.eq(0).find('div.progress.left div.text').text()
.concat(" ", indicatorInfo.eq(0).find('div.progress.right div.text').text()),
comparison_KDA: indicatorInfo.eq(1).find('div.progress.left div.text').text()
.concat(" ", indicatorInfo.eq(1).find('div.progress.right div.text').text()),
comparison_KP: indicatorInfo.eq(2).find('div.progress.left div.text').text()
.concat(" ", indicatorInfo.eq(2).find('div.progress.right div.text').text())
};
//#endregion
//#region 통산 전적
var td = $('div.scriptorium').children('div.listTable').eq(1).find('table tbody tr').children();
fakerData['fullCareer'] = {
totalGamePlay: td.eq(0).text(),
totalWin: td.eq(1).text(),
totalLose: td.eq(2).text(),
winRate: td.eq(3).text(),
totalKill: td.eq(4).text(),
totalDeath: td.eq(5).text(),
totalAssist: td.eq(6).text(),
killPerMatch: td.eq(7).text(),
deathPerMatch: td.eq(8).text(),
assistPerMatch: td.eq(9).text(),
kDA: td.eq(10).text(),
kP: td.eq(11).text()
}
//#endregion
//#region 대회 별 전적
var tr = $('div.scriptorium').children('div.listTable').eq(3).find('table tbody').children();
var competitionData = {};
tr.each(function (i, elem) {
var td = $(this).children();
var competitionName = td.eq(0).text().replace(td.eq(0).find('span').text(), '');
competitionData[competitionName] = {
name: competitionName,
totalGamePlay: td.eq(1).text(),
totalWin: td.eq(2).text(),
totalLose: td.eq(3).text(),
winRate: td.eq(4).text(),
totalKill: td.eq(5).text(),
totalDeath: td.eq(6).text(),
totalAssist: td.eq(7).text(),
killPerMatch: td.eq(8).text(),
deathPerMatch: td.eq(9).text(),
assistPerMatch: td.eq(10).text(),
kDA: td.eq(11).text(),
kP: td.eq(12).text()
};
});
fakerData['competitions'] = competitionData;
//#endregion
//#region 챔피언 별 전적
var tr = $('div.scriptorium').children('div.listTable').eq(4).find('table tbody').children();
var championData = {};
tr.each(function (i, elem) {
var td = $(this).children();
var championName = td.eq(0).text();
championData[championName] = {
name: championName,
totalGamePlay: td.eq(1).text(),
totalWin: td.eq(2).text(),
totalLose: td.eq(3).text(),
winRate: td.eq(4).text(),
totalKill: td.eq(5).text(),
totalDeath: td.eq(6).text(),
totalAssist: td.eq(7).text(),
killPerMatch: td.eq(8).text(),
deathPerMatch: td.eq(9).text(),
assistPerMatch: td.eq(10).text(),
kDA: td.eq(11).text(),
kP: td.eq(12).text()
}
});
fakerData['champions'] = championData;
//#endregion
console.log(fakerData);
fs.writeFileSync(dataFileName, JSON.stringify(fakerData));
return new Promise(function (resolve, reject) {
resolve();
});
}
function generateQuiz() {
quizList = [];
//#region 최근 LCK 모스트픽 ox
var mostList = [];
mostList = fakerData.recentLCK.most;
var quizO = `${fakerData.name}의 '${fakerData.recentLCK.name}' 모스트 픽은 '${mostList[0].champion}'이다.`;
var quizX = `${fakerData.name}의 '${fakerData.recentLCK.name}' 모스트 픽은 '${mostList[2].champion}'이다.`;
var info = `${fakerData.name}는 '${fakerData.recentLCK.name}'에서 '${mostList[0].champion}'을 가장 많이 플레이했습니다. (${mostList[0].played}게임)`;
generateOX(quizO,quizX,info);
//#endregion
//#region 최근 LCK 승률 비교 ox
var lckWinRate = fakerData.recentLCK.comparison_WinRate.split(' ')[0];
var recentWinRate = fakerData.recentLCK.comparison_WinRate.split(' ')[1];
if (lckWinRate < recentWinRate) {
quizO = `${fakerData.name}의 '${fakerData.recentLCK.name}' 승률은 LCK 통산 승률보다 높다.`;
quizX = `${fakerData.name}의 '${fakerData.recentLCK.name}' 승률은 LCK 통산 승률보다 낮다.`;
} else {
quizO = `${fakerData.name}의 '${fakerData.recentLCK.name}' 승률은 LCK 통산 승률보다 낮다.`;
quizX = `${fakerData.name}의 '${fakerData.recentLCK.name}' 승률은 LCK 통산 승률보다 높다.`;
}
info = `${fakerData.recentLCK.name}' 승률 : ${recentWinRate}\nLCK 통산 승률 : ${lckWinRate}`;
generateOX(quizO,quizX,info);
//#endregion
//#region 최근 LCK KDA 비교 ox
var lckKDA = fakerData.recentLCK.comparison_KDA.split(' ')[0];
var recentKDA = fakerData.recentLCK.comparison_KDA.split(' ')[1];
if (lckKDA < recentKDA) {
quizO = `${fakerData.name}의 '${fakerData.recentLCK.name}' KDA는 LCK 통산 KDA보다 높다.`;
quizX = `${fakerData.name}의 '${fakerData.recentLCK.name}' KDA는 LCK 통산 KDA보다 낮다.`;
} else {
quizO = `${fakerData.name}의 '${fakerData.recentLCK.name}' KDA는 LCK 통산 KDA보다 낮다.`;
quizX = `${fakerData.name}의 '${fakerData.recentLCK.name}' KDA는 LCK 통산 KDA보다 높다.`;
}
info = `${fakerData.recentLCK.name}' KDA : ${recentKDA}\nLCK 통산 KDA : ${lckKDA}`;
generateOX(quizO,quizX,info);
//#endregion
//#region 최근 LCK 킬관여율 비교 ox
var lckKP = fakerData.recentLCK.comparison_KP.split(' ')[0];
var recentKP = fakerData.recentLCK.comparison_KP.split(' ')[1];
if (lckKP < recentKP) {
quizO = `${fakerData.name}의 '${fakerData.recentLCK.name}' 킬관여율은 LCK 통산 킬관여율보다 높다.`;
quizX = `${fakerData.name}의 '${fakerData.recentLCK.name}' 킬관여율은 LCK 통산 킬관여율보다 낮다.`;
} else {
quizO = `${fakerData.name}의 '${fakerData.recentLCK.name}' 킬관여율은 LCK 통산 킬관여율보다 낮다.`;
quizX = `${fakerData.name}의 '${fakerData.recentLCK.name}' 킬관여율은 LCK 통산 킬관여율보다 높다.`;
}
info = `${fakerData.recentLCK.name}' KDA : ${recentKP}\nLCK 통산 KDA : ${lckKP}`;
generateOX(quizO,quizX,info);
//#endregion
}
function generateOX(quizO, quizX, moreInfo) {
var quiz;
var ans;
var info;
info = moreInfo;
if (Math.random() > 0.5) {
quiz = quizO;
ans = 'o';
} else {
quiz = quizX;
ans = 'x';
}
quiz = '[OX퀴즈] ' + quiz;
quizList.push(
{
quiz: quiz,
ans: ans,
info: info
}
);
}
app.use(bodyParser.json());
app.post('/hook', async 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 (!isWaitAns && eventObj.message.text == '시작') {
await checkData();
users[eventObj.source.userId] = {
streak: 0,
quizAns: null,
quizInfo: null
};
sendQuiz(eventObj.replyToken, eventObj.source.userId, true);
} else if (isWaitAns) {
if (checkAns(eventObj.source.userId, eventObj.message.text)) {
users[eventObj.source.userId].streak++;
sendQuiz(eventObj.replyToken, eventObj.source.userId, false);
} else {
endQuiz(eventObj.replyToken, eventObj.source.userId);
}
}
res.sendStatus(200);
});
function sendQuiz(replyToken, id, isInit) {
var randomQuiz = quizList[Math.floor(Math.random()*quizList.length)];
var quizText = randomQuiz.quiz;
var messages;
users[id].quizAns = randomQuiz.ans;
users[id].quizInfo = randomQuiz.info;
if (isInit) {
messages = [
{
"type":"text",
"text":quizText
}
];
} else {
messages = [
{
"type":"text",
"text":'정답입니다.'
},
{
"type":"text",
"text":quizText
}
];
}
request.post(
{
url: TARGET_URL,
headers: {
'Authorization': `Bearer ${TOKEN}`
},
json: {
"replyToken":replyToken,
"messages": messages
}
},(error, response, body) => {
console.log(body)
}
);
isWaitAns = true;
}
function checkAns(id, ans) {
if (ans.toUpperCase() == users[id].quizAns.toUpperCase()) {
return true;
} else {
return false;
}
}
function endQuiz(replyToken, id) {
isWaitAns = false;
sumOfTry++;
sumOfStreak += users[id].streak;
var averageStreak = sumOfStreak/sumOfTry;
request.post(
{
url: TARGET_URL,
headers: {
'Authorization': `Bearer ${TOKEN}`
},
json: {
"replyToken":replyToken,
"messages":[
{
"type":"text",
"text":"오답입니다."
},
{
"type":"text",
"text":users[id].quizInfo
},
{
"type":"text",
"text":`${users[id].streak}문제 연속 정답!\n(유저 평균 : ${averageStreak.toFixed(1)}문제)`
},
{
"type":"text",
"text":"퀴즈를 다시 시작하려면 '시작'을 입력해주세요."
}
]
}
},(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);
}