forked from SeonHyungJo/Theater-Noti
-
Notifications
You must be signed in to change notification settings - Fork 0
/
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()
}
})
})();