-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
495 lines (432 loc) · 13.6 KB
/
index.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
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
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
// .env
require('dotenv').config();
// Crawling
const axios = require('axios');
const cheerio = require('cheerio');
const fs = require('fs');
// Schedule
const schedule = require('node-schedule')
// Slack Bot Token
const token = process.env.SLACK_BOT_TOKEN;
// Slack API
const { RTMClient } = require('@slack/rtm-api');
const { WebClient } = require('@slack/web-api');
const web = new WebClient(token);
const rtm = new RTMClient(token);
/**
* 날짜 형식 변경
*/
const setFormatDate = (stringDate) => {
const year = stringDate.substr(0, 4);
const month = stringDate.substr(4, 2);
const day = stringDate.substr(6, 2);
return `${year}년 ${month}월 ${day}일`;
}
/**
* 해당 상영관 관련 영화정보 가져오기
* -----------------------------------
*
* @param areacode 지역
* @param theaterData 상영관 정보
* @param date 날짜
*/
const getParsingData = async (areaCode, theaterCode, date) => {
const getTheaterData = async () => {
try {
return await axios.get(
`http://www.cgv.co.kr/common/showtimes/iframeTheater.aspx?areacode=${areaCode}&theatercode=${theaterCode}&date=${date}`
);
} catch (error) {
console.error(error);
}
};
return getTheaterData()
.then(html => {
const ulList = {
areaCode,
theaterCode,
date,
dataList: []
};
const $ = cheerio.load(html.data);
const $bodyList = $('div.sect-showtimes').find('div.col-times');
$bodyList.each(function (i, elem) {
ulList.dataList[i] = {
title: $(this)
.find('div.info-movie a strong')
.text()
.trim(),
hallType: $(this)
.find('div.info-hall li')
.first()
.text()
.trim(),
timeTable: $(this)
.find('div.info-timetable li')
.map(function (i, el) {
return $(this)
.find('em')
.text();
})
.get()
};
});
return ulList;
})
};
/**
* CGV 무비차트 가져오기
* -----------------------------------
*/
const getCGVChartData = async () => {
try {
return await axios.get(
`http://www.cgv.co.kr/movies/`
);
} catch (error) {
console.error(error);
}
};
const getMovieChart = () => {
return getCGVChartData()
.then(html => {
const ulList = []
const $ = cheerio.load(html.data);
const $chartList = $('div.sect-movie-chart').find('li')
$chartList.length = $chartList.length - 1
$chartList.each(function (i, elem) {
ulList[i] = {
title: $(this).find('.title').text().trim(),
openDate: $(this).find('.txt-info').children('strong').text().trim().slice(0, 10),
thumNail: $(this).find('.thumb-image').children('img').attr('src')
};
});
return ulList;
})
}
// Create Movie Chart Blocks
const createMovieChartBlock = (movieList) => {
return movieList.map((item) => {
const timeList = item.timeTable.sort().reduce((acc, time) => acc + ', ' + time)
return {
'type': 'context',
'elements': [
{
'type': 'mrkdwn',
'text': `*${item.title}* / ${item.hallType} / ${timeList}`
}
]
}
})
}
/**
* ------------------------------------
* Bot Setting
* ------------------------------------
* Slack 자체 API가 존재하여 그냥 사용해서 올리면 될 듯
*/
// Common send Message for text
const sendMessage = async (messageText, channel) => {
return await rtm.sendMessage(messageText, channel);
};
const createHelpMessage = async () => {
return [
{
'type': 'context',
'elements': [
{
'type': 'mrkdwn',
'text': ' - 지역코드 리스트 : *지역코드* \n - 지역코드 검색 : *지역코드 / {지역명}* \n - 상영관코드 검색 : *상영관코드 / {지역코드}* \n - 상영관검색 : *상영관검색 / {검색할 단어}* \n - 날짜검색 : *날짜검색 / {상영관코드} / {날짜}* \n - 무비차트 : *{상영작 | 영화차트 | 영화리스트 | 무비차트 | 현재 상영작}* \n - 알람설정 : *알람 / 설정 / {상영관코드} / {날짜} / {영화이름}* \n - 알람조회 : *알람 / 조회* \n - 알람삭제 : *알람 / 삭제 / {인덱스}*'
}
]
}
]
}
const getMovieContent = (movieList) => {
return movieList.map((item) => {
const timeList = item.timeTable.sort().reduce((acc, time) => acc + ', ' + time)
return {
'type': 'context',
'elements': [
{
'type': 'mrkdwn',
'text': `*${item.title}* / ${item.hallType} / ${timeList}`
}
]
}
})
}
// Get Region Code
const getRegionCode = async () => {
const regionData = fs.readFileSync(`./regionCode.json`, 'utf8');
const regionCodeList = JSON.parse(regionData).RegionCodeList;
return regionCodeList
}
// Create Code Info Block
const createCodeInfoBlock = async (codeInfoList) => {
return codeInfoList.map((item) => {
return {
'type': 'context',
'elements': [
{
'type': 'mrkdwn',
'text': `*${item.name}:* ${item.code}`
}
]
}
})
}
// Search Theater Code
const searchTheaterCode = async (regionCode = 00, channel) => {
if (regionCode === 00) {
sendMessage('형식에 맞게 작성해주세요. => 상영관코드 / {지역코드}', channel)
}
const theaterData = fs.readFileSync(`theaterJsonData_${regionCode}.json`, 'utf-8');
const theaterCodeList = JSON.parse(theaterData).AreaTheaterDetailList;
const blocks = createCodeInfoBlock(theaterCodeList)
return blocks
}
// Search Theater Code to Name
const searchTheaterToName = (searchText = '') => {
const allTheater = fs.readFileSync(`allTheater.json`, 'utf-8')
const allTheaterList = JSON.parse(allTheater).AllTheaterDetailList.map(item => {
return {
'theaterName': item.TheaterName,
'theaterCode': item.TheaterCode
}
});
const theaterListString = allTheaterList
.filter(({ theaterName }) => theaterName.includes(searchText))
.reduce((acc, item) => `${acc === '' ? '' : acc + ' / '}${item.theaterName}(${item.theaterCode})`, '')
return [{
'type': 'context',
'elements': [
{
'type': 'mrkdwn',
'text': `${theaterListString}`
}
]
}]
}
// Search Movie List to Date in Specify Theater
const searchMovieToDate = async (theaterCode = '0055', date = (new Date()).toISOString().slice(0, 10).replace(/-/g, '')) => {
const theaterData = await getParsingData('', theaterCode, date);
const blocks = [
{
'type': 'context',
'elements': [
{
'type': 'mrkdwn',
'text': `*상영관 코드 :* ${theaterData.theaterCode}`
},
{
'type': 'mrkdwn',
'text': `*날짜 :* ${theaterData.date}`
}
]
}
]
return [...blocks, ...createMovieChartBlock(theaterData.dataList)]
}
// Get Movie Chart
const getMovieList = async () => {
const movieChartList = await getMovieChart()
return movieChartList.map((item, index) => {
return {
"type": "section",
"text": {
"type": "mrkdwn",
"text": `${index + 1}. ${item.title} / ${item.openDate} 개봉`
},
"accessory": {
"type": "image",
"image_url": `${item.thumNail}`,
"alt_text": `image_${index}`
}
}
})
}
/**
* All alarmList
* -------------
*
* Form Example
* [{
* theaterCode : '0055',
* date : '20190731',
* movieTitle : '알라딘'
* }]
*
*/
let alarmList = []
// create All Alarm List Blocks
const createAlarmListBlocks = (alarmList) => {
return alarmList.map((alram, index) => {
return {
'type': 'context',
'elements': [
{
'type': 'mrkdwn',
'text': `*알람 ${index + 1} :* ${alram.theaterCode} / ${alram.date} / ${alram.movieTitle}`
},
]
}
})
}
const createNoneAlarmListBlock = () => {
return [{
'type': 'context',
'elements': [
{
'type': 'mrkdwn',
'text': `*설정된 알람내역이 없습니다.*`
},
]
}]
}
// deleteAlarmList
const deleteAlarmList = (targetIndex) => {
alarmList = alarmList.filter((alram, index) => {
return index !== targetIndex
})
return createAlarmListBlocks(alarmList)
}
// create Ring Ding Dong Block
const createRingRingBlocks = (alarmInfo, movieInfo) => {
return [{
'type': 'context',
'elements': [
{
'type': 'mrkdwn',
'text': `*!!알람!!* *${setFormatDate(alarmInfo.date)}* *${movieInfo.title}* 예매를 시작했습니다. / ${movieInfo.hallType}`
},
]
}]
}
// Check Alarm List
const checkAlarmList = () => {
const successList = alarmList.map(async (alarm, index) => {
const searchList = await getParsingData('', alarm.theaterCode, alarm.date);
const checkedMovieList = searchList.dataList.filter((movie) => movie.title === alarm.movieTitle)
return { alarm, index, movie: checkedMovieList[0] }
})
successList.map((promise) => {
promise.then((alarmDatas) => {
if (alarmDatas.movie) {
const blocks = createRingRingBlocks(alarmDatas.alarm, alarmDatas.movie)
web.chat.postMessage({ blocks, channel: topChannel })
return alarmDatas.index
}
return -1
}).then((index) => {
if (index >= 0) {
const blocks = deleteAlarmList(parseInt(index))
web.chat.postMessage({ blocks, channel: topChannel })
}
})
})
}
// Create Message
let topChannel = ''
rtm.on('message', async event => {
const eventCodeList = event.text.split('/').map((text) => text.replace(/\s/gi, ""))
topChannel = event.channel
console.log('event===>', event)
console.log(eventCodeList);
try {
let result;
const movieChartKorlist = ['상영작', '영화차트', '영화리스트', '무비차트', '현재 상영작']
if (eventCodeList[0] === 'help') {
const helpMessageBlocks = await createHelpMessage()
result = await web.chat.postMessage({ blocks: helpMessageBlocks, channel: event.channel })
}
if (eventCodeList[0] === '지역코드') {
const regionCodeList = await getRegionCode()
let blocks
if (eventCodeList[1]) {
const searchRegion = regionCodeList.filter((item) => item.name.includes(eventCodeList[1]))
blocks = await createCodeInfoBlock(searchRegion)
} else {
blocks = await createCodeInfoBlock(regionCodeList)
}
result = await web.chat.postMessage({ blocks, channel: event.channel })
}
if (eventCodeList[0] === '상영관코드') {
blocks = await searchTheaterCode(eventCodeList[1], event.channel)
result = await web.chat.postMessage({ blocks, channel: event.channel })
}
if (eventCodeList[0] === '상영관검색') {
blocks = await searchTheaterToName(eventCodeList[1])
result = await web.chat.postMessage({ blocks, channel: event.channel })
}
if (eventCodeList[0] === '날짜검색') {
blocks = await searchMovieToDate(eventCodeList[1], eventCodeList[2])
result = await web.chat.postMessage({ blocks, channel: event.channel })
}
if (movieChartKorlist.includes(eventCodeList[0])) {
blocks = await getMovieList()
result = await web.chat.postMessage({ blocks, channel: event.channel })
}
/**
* -------------------------------------------------------
* 제일 중요한 부분으로 알림에 대한 전반적인 CRUD를 만들기
* -------------------------------------------------------
*
* Message 형식
* - Create : 알람 / 설정 / 상영관코드 / 날짜 / 영화이름
* - Read : 알람 / 조회
* - Delete : 알람 / 삭제 / 인덱스
*
* 1. 모든 알람에 대한 정보는 List로 관리한다.
* 2. 일정 시간마다 Loop를 돌면서 해당 설정한 알람에 대한 확인을 한다.
* 3. 설정한 알람이 실행된 후 알람내역에서 삭제한다.
* 4. !! 된다면 예매 사이트를 보내주도록 구현 !!
*
*/
if (eventCodeList[0] === '알람') {
switch (eventCodeList[1]) {
case '조회':
blocks = await alarmList.length === 0 ? createNoneAlarmListBlock() : createAlarmListBlocks(alarmList)
result = await web.chat.postMessage({ blocks, channel: event.channel })
break;
case '삭제':
blocks = await deleteAlarmList(parseInt(eventCodeList[2]) - 1)
sendMessage(`알람이 삭제되었습니다.`, event.channel)
result = await web.chat.postMessage({ blocks, channel: event.channel })
break;
case '설정':
if (!eventCodeList[4]) {
sendMessage(`알람설정이 실패했습니다.`, event.channel)
} else {
alarmList = [...alarmList, {
theaterCode: `${eventCodeList[2]}` || '0055',
date: `${eventCodeList[3]}` || (new Date()).toISOString().slice(0, 10).replace(/-/g, ''),
movieTitle: `${eventCodeList[4]}` || ''
}]
sendMessage(`알람이 추가되었습니다.`, event.channel)
blocks = await createAlarmListBlocks(alarmList)
result = await web.chat.postMessage({ blocks, channel: event.channel })
}
break;
default:
break;
}
}
console.log('result : ', result)
} catch (error) {
console.log('An error occurred', error);
}
});
/**
* Connect to Slack
*/
(async () => {
const { self, team } = await rtm.start();
console.log(`Listening RTM`, self, team);
// Start Schedule
schedule.scheduleJob('*/4 * * * *', function () {
if (alarmList.length > 0 && topChannel != '') {
checkAlarmList()
}
})
})();