ShinSeungMin

Add Chatbot Demo!

require('chromedriver');
const request = require('request');
const cheerio = require('cheerio');
const puppeteer = require('puppeteer');
const async = require('async');
let express = require('express');
let app = express();
let bodyParser = require('body-parser');
const { timeout } = require('async');
const {Builder,until} = require('selenium-webdriver'); //모듈 불러오기
const webdriver = require('selenium-webdriver');
const chrome = require('selenium-webdriver/chrome');
const { delayed } = require('selenium-webdriver/lib/promise');
const By = webdriver.By;
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
const url_movies = "https://www.cgv.co.kr/movies/?lt=1&ft=0"; //끝의 쿼리 0은 개봉 전 영화도 포함하는 것. 예매율 순위 가져오기
const url_theaters = "https://www.cgv.co.kr/theaters/"; //영화관 정보 가져오는 링크.
const url_ticketing = "https://www.cgv.co.kr/ticket/"; //상영중인 영화 정보 가져오는 링크.
let cgv_theaters = []; //영화관과 영화관 고유 코드를 담는 배열
let cgv_movies = []; //예매율 상위 19위까지의 영화 정보(CGVMovieInfo Class의 인스턴스)들을 담는 배열.
let cgv_accessible_movies = []; //선택한 일자, 영화관에서 예매할 수 있는 영화 이름과 영화 고유 코드를 담는 배열.
//예매율 Top19위까지의 영화 정보를 관리하는 Class
class CGVMovieInfo {
constructor(title, rank, score, GoldenEgg, movieCode){
this.title = title;
this.rank = rank;
this.score = score;
this.GoldenEgg = GoldenEgg;
this.movieCode = movieCode;
}
getTitle() { return this.title; }
setTitle(title) { this.title = title; }
getRank() { return this.rank; }
setRank(rank) { this.rank = rank; }
getScore() { return this.score; }
setScore(score) { this.score = score; }
getGoldenEgg() { return this.GoldenEgg; }
setGoldenEgg(GoldenEgg) { this.GoldenEgg = GoldenEgg; }
getMovieCode() { return this.movieCode; }
setMovieCode(movieCode) { this.movieCode = movieCode; }
printMovieInfo(){
return {
'rank': this.rank + " : " + this.title,
'score': "예매율 : " + this.score + "%",
'goldenEgg': "골든에그지수 : " + this.GoldenEgg,
'movieCode': "영화코드 : " + this.movieCode
};
}
}
exports.init = () => {async.waterfall([
async () => {
//크롬 설정을 담은 객체 생성
const driver_theaters = new webdriver.Builder().forBrowser('chrome').setChromeOptions(new chrome.Options().headless()).build();
driver_theaters.get(url_theaters);
//9개 권역별로 영화관 list들을 list의 element로 넣기.
let selector = '#contents > div.sect-common > div > div.sect-city > ul > li:nth-child({}) > div > ul > li > a';
let area = [];
for(let i = 1; i <= 9; i++){
let region = await driver_theaters.wait(until.elementsLocated(By.css(selector.replace("{}", i))));
area.push(region);
}
//영화관 및 영화관에 대응되는 영화관별 고유 코드 가져오기.
for (const theaters_by_area of area) {
let theaters_info_by_area = [];
for (const theater of theaters_by_area){
let theater_info = {
"theater_name" : await theater.getAttribute('title'),
"theater_code" : await theater.getAttribute('href')
};
theater_info.theater_name = theater_info.theater_name.replace("CGV", "")
theater_info.theater_code = theater_info.theater_code.replace(/(.+(?<=theaterCode=))|(.+(?<=theatercode=))/, "").substring(0,4);
theaters_info_by_area.push(theater_info);
}
cgv_theaters.push(theaters_info_by_area);
}
driver_theaters.close();
},
async () => {
const driver_movies = new webdriver.Builder().forBrowser('chrome').setChromeOptions(new chrome.Options().headless()).build();
driver_movies.get(url_movies);
//예매율 Top19까지의 영화의 정보를 가져옴.
const rank = await driver_movies.wait(until.elementsLocated(By.css("strong.rank")));
const title = await driver_movies.wait(until.elementsLocated(By.css("strong.title")));
const score = await driver_movies.wait(until.elementsLocated(By.css("strong.percent")));
const GoldenEgg = await driver_movies.wait(until.elementsLocated(By.css("span.percent")));
const link = await driver_movies.wait(until.elementsLocated(By.css("a.link-reservation")));
//영화 제목, 순위, 예매율, 영화 코드, 골든에그 지수를 가져와 CGVMovieInfo 객체 생성자에 파라미터로 넘겨주고, 인스턴스를 받아옴.
for (let i = 0; i < rank.length; i++) {
const newTitle = await title[i].getText();
const newRank = await rank[i].getText();
const newScore = await score[i].getText();
const newCode = await link[i].getAttribute("href");
const newMovie = new CGVMovieInfo(newTitle, parseInt(newRank.replace("No.", "")), newScore.replace("예매율", "").replace("%", ""), await GoldenEgg[i].getText(), newCode.replace(/[^0-9]/g, "").substring(0,8));
cgv_movies.push(newMovie);
}
driver_movies.close();
}
])}
app.get('/cgv_theaters', (req, res) => {
res.send(cgv_theaters[0]);
});
/*
app.post('/ticketing', async (req, res, next) => {
//영화관 이름과 날짜를 가져옴.
const theaterName = req.body.theaterName;
const date = req.body.date;
const LocateQuery = "?PLAY_YMD={}".replace("{}", date);
//입력된 영화관에 맞는 지역 코드와 영화관 고유코드 찾기
let regionCode = 0, theaterCode = "";
for(let i = 0; i < 9; i++){
for(const elem of cgv_theaters[i]){
if(elem.theater_name == theaterName){
regionCode = i;
theaterCode = elem.theater_code;
break;
}
}
}
//예매 가능한 영화 리스트를 얻기 위해 빠른 예매 사이트로 이동.
const driver_ticketing = new webdriver.Builder().forBrowser('chrome').setChromeOptions(new chrome.Options()).build();
driver_ticketing.get(url_ticketing + LocateQuery);
driver_ticketing.switchTo().frame("ticket_iframe"); //Frame 전환
//setTimeout(() => {}, 1000);
//지역 코드에 맞게 list element click
const selected_areas_list = await driver_ticketing.wait(until.elementsLocated(By.css("#theater_area_list > ul > li > a > span.name")));
await selected_areas_list[regionCode].click();
//setTimeout(() => {}, 5000);
//선택한 지역에 대응되는 영화관 정보 가져오기
const selected_theaters_list = await driver_ticketing.wait(until.elementsLocated(By.css("#theater_area_list > ul > li.selected > div > ul > li")));
//프로그램 내부에서 가지고 있는 영화관코드와 웹에서 받아온 영화관코드가 일치하는 경우, selected_theaters_list element 클릭
for (const theater_element of selected_theaters_list){
if(await theater_element.getAttribute("theater_cd") == theaterCode){
await theater_element.click();
//setTimeout(() => {}, 5000);
break;
}
}
//선택한 영화관에서, 선택한 일자에 상영하는 영화 목록 들고오기
await driver_ticketing.sleep(1000);
const selected_movies_list = await driver_ticketing.wait(until.elementsLocated(By.css("#movie_list > ul > li > a > span.text")));
const codes_of_selected_movies = await driver_ticketing.wait(until.elementsLocated(By.css("#movie_list > ul > li")));
//선택불가를 제외한 영화 제목 및 영화 코드 가져오기.
for(let i = 0; i < selected_movies_list.length; i++){
//setTimeout(() => {}, 1000);
const movie_enabled = await codes_of_selected_movies[i].getAttribute("class");
if(movie_enabled.endsWith("dimmed"))
break;
const accessible_movie = {
"movie_title": await selected_movies_list[i].getText(),
"movie_code" : await codes_of_selected_movies[i].getAttribute("movie_cd_group")
}
cgv_accessible_movies.push(accessible_movie);
}
driver_ticketing.close();
res.send(cgv_accessible_movies);
});
*/
exports.getMovieChart = async(rank) => {
let movie_chart = [];
for(const movie_info of cgv_movies){
if(movie_info.getRank() > rank)
break;
const top19_movie = {
"rank" : movie_info.getRank(),
"title" : movie_info.getTitle(),
"code" : movie_info.getMovieCode()
};
movie_chart.push(top19_movie);
}
return movie_chart;
}
exports.getTheaterCode = async(theaterName) => {
let theaterCode = "";
for(let i = 0; i < 9; i++){
for(const elem of cgv_theaters[i]){
if(elem.theater_name == theaterName){
theaterCode = elem.theater_code;
break;
}
}
}
return theaterCode;
}
exports.getAccessibleMovies = async(theaterName, date) => {
//영화관 이름과 날짜를 가져옴.
//입력된 영화관에 맞는 지역 코드와 영화관 고유코드 찾기
let regionCode = 0, theaterCode = "";
for(let i = 0; i < 9; i++){
for(const elem of cgv_theaters[i]){
if(elem.theater_name == theaterName){
regionCode = i;
theaterCode = elem.theater_code;
break;
}
}
}
const baseMovieCode = cgv_movies[0].getMovieCode();
const LocateQuery = "?MOVIE_CD={0}&MOVIE_CD_GROUP={1}&THEATER_CD={2}&PLAY_YMD={3}".replace("{0}", baseMovieCode).replace("{1}", baseMovieCode).replace("{2}", theaterCode).replace("{3}", date);
//예매 가능한 영화 리스트를 얻기 위해 빠른 예매 사이트로 이동.
const driver_ticketing = new webdriver.Builder().forBrowser('chrome').setChromeOptions(new chrome.Options().addArguments("--headless")).build();
driver_ticketing.get(url_ticketing + LocateQuery);
await driver_ticketing.switchTo().frame("ticket_iframe"); //Frame 전환
/*
//setTimeout(() => {}, 1000);
//지역 코드에 맞게 list element click
const selected_areas_list = await driver_ticketing.wait(until.elementsLocated(By.css("#theater_area_list > ul > li > a > span.name")));
await selected_areas_list[regionCode].click();
//setTimeout(() => {}, 5000);
//선택한 지역에 대응되는 영화관 정보 가져오기
const selected_theaters_list = await driver_ticketing.wait(until.elementsLocated(By.css("#theater_area_list > ul > li.selected > div > ul > li")));
//프로그램 내부에서 가지고 있는 영화관코드와 웹에서 받아온 영화관코드가 일치하는 경우, selected_theaters_list element 클릭
for (const theater_element of selected_theaters_list){
if(await theater_element.getAttribute("theater_cd") == theaterCode){
await theater_element.click();
//setTimeout(() => {}, 5000);
break;
}
}
//선택한 영화관에서, 선택한 일자에 상영하는 영화 목록 들고오기
await driver_ticketing.sleep(1000);
const selected_movies_list = await driver_ticketing.wait(until.elementsLocated(By.css("#movie_list > ul > li > a > span.text")));
const codes_of_selected_movies = await driver_ticketing.wait(until.elementsLocated(By.css("#movie_list > ul > li")));
*/
//선택불가를 제외한 영화 제목 및 영화 코드 가져오기.
//const selected_movies_list = await driver_ticketing.wait(until.elementsLocated(By.css("strong")));
//await driver_ticketing.sleep(1000);
//선택한 영화관에서, 선택한 일자에 상영하는 영화 목록 들고오기
//await driver_ticketing.sleep(1000);
const selected_movies_list = await driver_ticketing.wait(until.elementsLocated(By.css("#movie_list > ul > li > a > span.text")));
const codes_of_selected_movies = await driver_ticketing.wait(until.elementsLocated(By.css("#movie_list > ul > li")));
//선택불가를 제외한 영화 제목 및 영화 코드 가져오기.
for(let i = 0; i < selected_movies_list.length; i++){
//setTimeout(() => {}, 1000);
const movie_enabled = await codes_of_selected_movies[i].getAttribute("class");
if(movie_enabled.endsWith("dimmed"))
break;
const accessible_movie = {
"movie_title": await selected_movies_list[i].getText(),
"movie_code" : await codes_of_selected_movies[i].getAttribute("movie_cd_group")
}
cgv_accessible_movies.push(accessible_movie);
}
return cgv_accessible_movies;
}
app.listen(23017);
\ No newline at end of file
const chatbot = require("./app.js");
const request = require('request');
const cheerio = require('cheerio');
const puppeteer = require('puppeteer');
require('chromedriver');
const {Builder,until} = require('selenium-webdriver'); //모듈 불러오기
var webdriver = require('selenium-webdriver');
var By = webdriver.By;
const chrome = require('selenium-webdriver/chrome');//크롬 사용시
const async = require('async')
let express = require('express');
let app = express();
let bodyParser = require('body-parser');
const { timeout } = require('async');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
const booking_url = "https://megabox.co.kr/booking?";
exports.booking_url = booking_url;
const rate_url = "https://www.megabox.co.kr/movie";
let r =0;
let movie_data = [];
exports.movie_data = movie_data;
let location_data = [];
exports.location_data = location_data;
let index = 0;
exports.init = ()=>{async.waterfall([//for 동기적 처리
async () => {
const driver = new webdriver.Builder().forBrowser('chrome').setChromeOptions(new chrome.Options().headless()).build();//
driver.get(booking_url);
driver.switchTo().frame(0)//frameBokdMBooking 프레임 가져옴
let seoul = await driver.wait(until.elementsLocated(By.css('#mCSB_4_container>ul>li>#btn')));
let Gyeonggi = await driver.wait(until.elementsLocated(By.css('#mCSB_5_container>ul>li>#btn')));
const Incheon = await driver.wait(until.elementsLocated(By.css('#mCSB_6_container>ul>li>#btn')));
const DCS = await driver.wait(until.elementsLocated(By.css('#mCSB_7_container>ul>li>#btn')));//Daejeon Chungcheong Sejong
const BDG = await driver.wait(until.elementsLocated(By.css('#mCSB_8_container>ul>li>#btn')));//Busan Daegu Gyeongsang
const GJ= await driver.wait(until.elementsLocated(By.css('#mCSB_9_container>ul>li>#btn')));//gwangju_jeonla
const Gangwon = await driver.wait(until.elementsLocated(By.css('#mCSB_10_container>ul>li>#btn')));
const location_list = [seoul, Gyeonggi, Incheon, DCS, BDG, GJ, Gangwon]//
for(let i = 0; i < location_list.length; i++){
for (item of location_list[i]) {
location_data[index++] = {
'LocationName':await item.getAttribute("brch-nm"),
'LocationNum' : await item.getAttribute("brch-no")
}
// let location_name = await item.getAttribute("brch-nm");
// let location_num = await item.getAttribute("brch-no");
// let obj = {};
// obj[location_name]= location_num
// location_data[index++] = obj;
}
}
let movie_list = await driver.wait(until.elementsLocated(By.css('#mCSB_1_container>ul>li>.btn')));
r = 0;
for (item of movie_list) {
//Using getAttribute to get the data
movie_data[r++] = {
'rank' : r,
'title' : await item.getAttribute("movie-nm"),
'movie_num':await item.getAttribute("movie-no"),
}
}
driver.close();
},
async () => {
r = 0;
const browser = await puppeteer.launch({
headless: true
});
const page = await browser.newPage();
await page.goto(rate_url);
const content = await page.content();
const $ = cheerio.load(content);
const $rate_lists = $("ol.list>li");
$rate_lists.each((index, list) => {
const name = $(list).find('div.tit-area > p.tit').attr('title');
const rate = $(list).find('div.rate-date > span.rate').text();
if(movie_data[r].title === name){
movie_data[r++]['rate'] = rate;
}
});
for(i of movie_data){
if(Object.keys(i).length==3){
movie_data[r++]['rate'] = '예매율 0%';
}
}
browser.close();
console.log("Comepleted!");
},
])}
let appdriver;
exports.using_PlayingMovieURL = async(PlayingMovieURL) => {
appdriver = new webdriver.Builder().forBrowser('chrome').setChromeOptions(new chrome.Options().headless()).build();
appdriver.get(PlayingMovieURL);
//appdriver.switchTo().frame(0)
//frameBokdMBooking 프레임 가져옴
}
exports.geting_PlayingMovie= async() => {
let movie_list = await appdriver.wait(until.elementsLocated(By.css('#mCSB_1_container>ul>li>.btn')));
let n = 0;
console.log(movie_list);
for (item of movie_list) {
movie_data[n++]['running'] = await item.getAttribute('form-at');
}
console.log("Completed get Running");
}
app.listen(5000);
\ No newline at end of file
const MEGABOX = require('./Megabox.js');
const CGV = require('./CGVTicketing.js');
//const SearchingTheaterAPI = require('./SearchingTheaterAPI');
const async = require('async');
MEGABOX.init(); //메가박스 코드 시작(영화관 리스트 가져오기)
CGV.init(); //CGV 코드 시작
const PUSH_TARGET_URL = 'https://api.line.me/v2/bot/message/push'
const REPLY_TARGET_URL = 'https://api.line.me/v2/bot/message/reply'
const asyncHandler = require('express-async-handler')
const bodyParser = require('body-parser');
const request = require('request');
const moment = require("moment");
const HTTPS = require('https');
const path = require('path');
const fs = require('fs');
const sslport = 23023;
var express = require('express');
var app = express();
app.use(bodyParser.json());
/////////////////////////////////////////////////
// commit 할때 지워야 할것들
// const USER_ID = '';
// const TOKEN = '';
// const domain = '';
// const KAKAO_KEY = '';
const USER_ID = 'Uc2471a2b23fdd1ba92cfaefc5109ae66';
const TOKEN = 'dnQaNDicvCKG/BJdsuI0/48ep9UTKuHFjW3L4+uCketz+HhXJI4RhfBMFwuKljG4pKyVahGIxhU0mby+wUvmOlgqHwCs5Hs8wM+ztYvcxo5PDOldHjikU4spRsgLy35Hok2QdqbARcZuupInqeWt3AdB04t89/1O/w1cDnyilFU=';
const domain = '2021105612.osschatbot2022.ml';
const KAKAO_KEY = 'e5051f82023ae6c9893a9755339971ac';
/////////////////////////////////////////////////
let initFlag = false; //브랜드 선택 flag
/////////////////////////////////////////////////
// CGV 변수 초기화 부분
let CGV_flag = -1; //진행 단계
let CGV_date = ""; //날짜
let CGV_RequestedLocation = ""; //사용자가 입력한 장소
let CGV_RespondedTheaters = []; //API를 통해 받아온 영화관들 및 카카오맵 연결 링크
let CGV_SelectedTheater = ""; //사용자가 설정한 영화관 이름
let CGV_SelectedTheaterCode = ""; //영화관 고유코드
let CGV_accessible_movies = []; //상영 날짜와 상영관에 따라 예매할 수 있는 영화 목록
let CGV_movie_chart = [];
let CGV_url_web = "https://www.cgv.co.kr/ticket/";
let CGV_url_mobile = "https://m.cgv.co.kr/WebApp/Reservation/quickResult.aspx";
/////////////////////////////////////////////////
// LotteCinema 변수 초기화 부분
let LOTTE_flag = -1;
////////////////////////////////////////////////
// Megabox 변수 초기화 부분
let MEGA_date;
let MEGA_TheaterLocation;
let MEGA_TheaterLocationCode;
let MEGA_PlayingMovieList = [];
let MEGA_title;
let MEGA_PlayingMovieURL;
let MEGA_flag = -1; //메가박스 인지 확인하는 flag
let MEGA_count; //메가박스에서 영화관 판단하는 count
let MEGA_AbleLocationList = []; //메가박스에서 영화관 이름 매치하는 것 저장하는 list
let MegaboxKakaoResultTheater = [];
exports.MEGA_PlayingMovieURL = MEGA_PlayingMovieURL;
////////////////////////////////////////////////
//처음 영화관을 가져오는 것까지 대략 30초가 걸림 => 30초 기다리고 메세지 전송
setTimeout(function () {
PushSingleMessage("원하시는 브랜드의 번호를 입력해주세요.\n1: CGV\n2: LotteCinema\n3: Megabox\n언제든 브랜드를 바꾸고 싶으시다면 '브랜드'를 입력해주세요.");
}, 30000);
//app.post('/hook', function (req, res) {
app.post('/hook', asyncHandler(async (req, res, next) => {
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);
//어느 순간에서든 "브랜드"를 입력해 원하는 브랜드 선택
//initFlag : false ==> 브랜드 선택 전
//initFlag : true ==> 브랜드 선택 됨
if (eventObj.message.text == "브랜드") {
initFlag = false;
MEGA_flag = -1;
PushSingleMessage("원하시는 브랜드의 번호를 입력해주세요.\n1: CGV\n2: LotteCinema\n3: Megabox\n언제든 브랜드를 바꾸고 싶으시다면 '브랜드'를 입력해주세요.");
}
if (initFlag == false && eventObj.message.text == "1") { //브랜드 선택- CGV 인 경우: CGV_flag를 0으로 두어 메가박스 임을 확인
initFlag = true;
CGV_flag = 0;
} else if (initFlag == false && eventObj.message.text == "2") { //브랜드 선택- 롯데시네마 인 경우: LOTTE_flag를 0으로 두어 메가박스 임을 확인
initFlag = true;
LOTTE_flag = 0;
} else if (initFlag == false && eventObj.message.text == "3") { //브랜드 선택- 메가박스 인 경우: MEGA_flag를 0으로 두어 메가박스 임을 확인
initFlag = true;
MEGA_flag = 0;
}
if (initFlag == true && CGV_flag != -1) { //씨지브이로 브랜드 선택된 경우
if (CGV_flag === 0) {
const text1 = "영화관 위치를 입력해주세요";
const text2 = "ex) 강남"
SendMessage(eventObj, text1, text2);
CGV_flag++;
}
else if (CGV_flag === 1) {
CGV_RespondedTheaters = [];
CGV_RequestedLocation = message.text;
GetCGVKakaoLocalAPI(CGV_RequestedLocation);
setTimeout(function () {
if (CGV_RespondedTheaters.length == 0)
PushSingleMessage("검색 결과가 없습니다. 다시 입력해주세요.");
else {
if (CGV_RespondedTheaters.length == 1) {
CGV_SelectedTheater = CGV_RespondedTheaters[0].theater_name;
CGV_SelectedTheaterCode = CGV.getTheaterCode(CGV_SelectedTheater);
setTimeout(function () {
CGV_flag = 2;
}, 2000);
}
else {
let CGV_OutputString = "원하시는 상영관의 번호를 정확히 입력해주세요\n";
for (let i = 0; i < CGV_RespondedTheaters.length; i++) {
CGV_OutputString += String(i + 1) + ": " + CGV_RespondedTheaters[i].theater_name + "\n";
}
CGV_OutputString += String(CGV_RespondedTheaters.length + 1) + ": 다시 검색하기";
PushSingleMessage(CGV_OutputString);
CGV_flag = 101;
}
}
}, 2000);
}
else if (CGV_flag == 101 && CGV_RespondedTheaters.length != 0) {
let selection = parseInt(message.text);
if (selection > 0 && selection < CGV_RespondedTheaters.length + 1) {
CGV_SelectedTheater = CGV_RespondedTheaters[selection - 1].theater_name;
CGV_SelectedTheaterCode = await CGV.getTheaterCode(CGV_SelectedTheater);
CGV_flag = 2;
}
else {
const text1 = "영화관 위치를 입력해주세요";
const text2 = "ex) 강남"
SendMessage(eventObj, text1, text2);
CGV_flag = 1;
}
}
////날짜 입력 받기
if (CGV_flag === 2) {
const text1 = "선택한 영화관은 CGV" + CGV_SelectedTheater + "입니다.\n 영화를 관람할 날짜를 선택해 주세요.";
const text2 = "ex)20020409, YYYYMMDD";
SendMessage(eventObj, text1, text2);
CGV_flag = 3;
}
//날짜 확인 및 날짜, 장소에 대해 상영중인 영화 리스트 가져오기
if (moment(message.text, "YYYYMMDD", true).isValid() && CGV_flag == 3) {
CGV_date = message.text;
//console.log(MEGA_date, MEGA_TheaterLocation);
if (CGV_date && CGV_SelectedTheater) {
CGV_accessible_movies = await CGV.getMovieChart(5);
const text1 = "현재상영작을 가져오는 중입니다.";
const text2 = "잠시만 기다려주세요.";
PushMessage(text1, text2);
console.log(CGV_accessible_movies);
CGV_flag++;
}
//원본 코드
// MEGA_date = parseInt(eventObj.message.text);
// if (MEGA_date && MEGA_TheaterLocationCode) {
// MEGA_PlayingMovieURL = "https://megabox.co.kr/on/oh/ohb/SimpleBooking/simpleBookingPage.do" + '?brchNo1=' + MEGA_TheaterLocationCode + '&playDe=' + MEGA_date;
// console.log(MEGA_PlayingMovieURL)
// async.waterfall[
// megabox.using_PlayingMovieURL(MEGA_PlayingMovieURL),
// megabox.geting_PlayingMovie()
// ]
// MEGA_flag++
// console.log(MEGA_flag);
// }
}
if (CGV_flag === 4) {
let AccessibleMovieText = "-- 예매 가능한 상영작 --\n\n";
if (CGV_accessible_movies.length == 0) {
PushMessage("현재상영작이 없습니다.", "영화관 선택 단계로 이동합니다.");
setTimeout(function () {
PushMessage("영화관 위치를 입력해주세요", "ex1) 강남");
}, 1000);
CGV_flag = 1;
}
else if (CGV_accessible_movies.length == 1) {
AccessibleMovieText += ("1. " + CGV_accessible_movies[0].title);
const SelectedMovieCode = CGV_accessible_movies[0].code;
PushMessage(AccessibleMovieText, "바로 링크가 전송됩니다.");
setTimeout(function () {
const finalURL_web = CGV_url_web + "?MOVIE_CD=" + SelectedMovieCode + "&MOVIE_CD_GROUP=" + SelectedMovieCode + "&THEATER_CD=" + CGV_SelectedTheaterCode + "&PLAY_YMD=" + CGV_date;
const finalURL_mobile = CGV_url_mobile + "?mgc=" + SelectedMovieCode + "&tc=" + CGV_SelectedTheaterCode + "&ymd=" + CGV_date;
//console.log(finalURL_web);
//PushMessage(finalURL_web, "링크를 누르면 예매 창으로 바로 이동합니다.");
PushURLMessage(finalURL_web, finalURL_mobile);
}, 1000);
}
else {
setTimeout(function () {
let rank = 1;
for (const elem of CGV_accessible_movies) {
AccessibleMovieText += (rank.toString() + ". " + elem.title);
AccessibleMovieText += "\n";
rank++;
}
console.log(AccessibleMovieText);
PushMessage(AccessibleMovieText, "예매할 영화 번호를 입력해주세요.\n ex)1 (영화 앞 숫자만 입력)");
CGV_flag = 5;
}, 1000);
}
}
if (CGV_flag === 5) {
const index = parseInt(message.text) - 1;
if (index < 0 || index > 4) {
PushSingleMessage("다시 입력해주세요!");
} else {
const SelectedMovieCode = CGV_accessible_movies[index].code;
const finalURL_web = CGV_url_web + "?MOVIE_CD=" + SelectedMovieCode + "&MOVIE_CD_GROUP=" + SelectedMovieCode + "&THEATER_CD=" + CGV_SelectedTheaterCode + "&PLAY_YMD=" + CGV_date;
const finalURL_mobile = CGV_url_mobile + "?mgc=" + SelectedMovieCode + "&tc=" + CGV_SelectedTheaterCode + "&ymd=" + CGV_date;
//console.log(finalURL_web);
//PushMessage(finalURL_web, "링크를 누르면 예매 창으로 바로 이동합니다.");
PushURLMessage(finalURL_web, finalURL_mobile);
setTimeout(function () {
initFlag = false;
CGV_flag = -1;
PushSingleMessage("원하시는 브랜드의 번호를 입력해주세요.\n1: CGV\n2: LotteCinema\n3: Megabox\n언제든 브랜드를 바꾸고 싶으시다면 '브랜드'를 입력해주세요.");
}, 1000);
}
}
} else if (initFlag == true && LOTTE_flag != -1) { //롯데시네마로 브랜드 선택된 경우
PushMessage("현재 롯데시네마는 AWS 서버 문제로 지원되지 않습니다!\n다른 브랜드를 선택해주세요.\n롯데시네마의 예매 링크 사이트는 https://www.lottecinema.co.kr/NLCHS/Ticketing 입니다.", "원하시는 브랜드의 번호를 입력해주세요.\n1: CGV\n2: LotteCinema\n3: Megabox\n언제든 브랜드를 바꾸고 싶으시다면 '브랜드'를 입력해주세요.");
initFlag = false;
LOTTE_flag = -1;
}
else if (initFlag == true && MEGA_flag != -1) { //메가박스로 브랜드 선택된 경우
if (MEGA_flag == 0) {
const text1 = "영화관 위치를 입력해주세요";
const text2 = "ex1)강남";
SendMessage(eventObj, text1, text2);
MEGA_flag++;
//PusbuttonhMessage("https://developers.line.biz/en/reference/messaging-api/#message-common-properties");
//console.log(MEGA_flag)
} else if (MEGA_flag === 1) {
MEGA_count = 0; //MEGA_count 초기화
MEGA_AbleLocationList.length = 0; //MEGA_AbleLocationList 초기화
for (i of MEGABOX.location_data) {
if (i['LocationName'].includes(message.text)) {
MEGA_AbleLocationList[MEGA_count++] = i;
}
}
if (MEGA_count == 1) { //결과 1개 => 바로 다음 단계 넘어가기
MEGA_TheaterLocation = MEGA_AbleLocationList[0].LocationName;
MEGA_TheaterLocationCode = MEGA_AbleLocationList[0].LocationNum;
console.log(MEGA_TheaterLocation, MEGA_TheaterLocationCode);
MEGA_flag++;
} else if (MEGA_count > 1) { //결과 2개 이상 => 리스트 출력해주고 번호로 입력받아 넘어가기
console.log(MEGA_AbleLocationList[0], MEGA_AbleLocationList[1]);
let MEGA_OutputString = "원하시는 상영관의 번호를 정확히 입력해주세요\n"; //메가박스 영화관 가능 정보 string
//PushSingleMessage("원하시는 상영관의 번호를 정확히 입력해주세요");
for (let x = 0; x < MEGA_count; x++) {
//PushSingleMessage(String(x + 1) + ": " + MEGA_AbleLocationList[x].LocationName);
MEGA_OutputString += String(x + 1) + ": " + MEGA_AbleLocationList[x].LocationName + "\n";
console.log(String(x + 1), MEGA_AbleLocationList[x].LocationName);
}
MEGA_OutputString += String(MEGA_count + 1) + ": 다시 검색하기";
PushSingleMessage(MEGA_OutputString);
MEGA_flag = 101;
} else {
PushSingleMessage("다시 입력해주세요.");
}
//원본 코드
//console.log(MEGA_flag);
// for (i of MEGABOX.location_data) {
// if (i['LocationName'] === message.text) {
// MEGA_TheaterLocationCode = i['LocationNUm'];
// console.log(MEGA_TheaterLocationCode);
// MEGA_flag++;
// console.log(MEGA_flag)
// break;
// }
// }
} else if (MEGA_flag == 101) {
// 0< input || input > MEGA_count+1 : 다시 검색
let tempNum = parseInt(message.text);
if (tempNum > 0 && tempNum < MEGA_count + 1) {
//번호에 맞는 LocationCode 전달
MEGA_TheaterLocation = MEGA_AbleLocationList[tempNum - 1].LocationName;
MEGA_TheaterLocationCode = MEGA_AbleLocationList[tempNum - 1].LocationNum;
console.log(MEGA_TheaterLocation, MEGA_TheaterLocationCode);
MEGA_flag = 2;
} else {
//다시 장소 입력받기
const text1 = "영화관 위치를 입력해주세요";
const text2 = "ex1)강남";
SendMessage(eventObj, text1, text2);
MEGA_flag = 1;
}
}
//날짜 입력 받기
if (MEGA_flag == 2) {
const text1 = "현재 영화관은 " + MEGA_TheaterLocation + " 입니다.\n영화를 보실 날짜를 입력해주세요.";
const text2 = "ex)20020409";
SendMessage(eventObj, text1, text2);
MEGA_flag = 3;
}
//날짜 확인 및 날짜, 장소에 대해 상영중인 영화 리스트 가져오기
if (moment(message.text, "YYYYMMDD", true).isValid() && MEGA_flag == 3) {
MEGA_date = parseInt(message.text);
let today = GettingToday();//오늘 이후인지 확인하기 위해 날짜 가져옴
//console.log(MEGA_date, MEGA_TheaterLocation);
if (today <= MEGA_date && MEGA_date && MEGA_TheaterLocationCode) {
const text1 = "현재상영작을 가져오는 중입니다.";
const text2 = "잠시만 기다려주세요.";
PushMessage(text1, text2);
MEGA_PlayingMovieURL = "https://megabox.co.kr/on/oh/ohb/SimpleBooking/simpleBookingPage.do" + '?brchNo1=' + MEGA_TheaterLocationCode + '&playDe=' + MEGA_date;
MEGABOX.using_PlayingMovieURL(MEGA_PlayingMovieURL);
await MEGABOX.geting_PlayingMovie();
console.log(MEGA_PlayingMovieURL, MEGABOX.movie_data);
MEGA_flag = 4;
}
else {
const text1 = "영화를 보실 날짜를 다시 입력해주세요.";
const text2 = "ex)20020409";
SendMessage(eventObj, text1, text2);
}
//원본 코드
// MEGA_date = parseInt(eventObj.message.text);
// if (MEGA_date && MEGA_TheaterLocationCode) {
// MEGA_PlayingMovieURL = "https://megabox.co.kr/on/oh/ohb/SimpleBooking/simpleBookingPage.do" + '?brchNo1=' + MEGA_TheaterLocationCode + '&playDe=' + MEGA_date;
// console.log(MEGA_PlayingMovieURL)
// async.waterfall[
// MEGABOX.using_PlayingMovieURL(MEGA_PlayingMovieURL),
// MEGABOX.geting_PlayingMovie()
// ]
// MEGA_flag++
// console.log(MEGA_flag);
// }
}
if (MEGA_flag == 4) {
let obj = {};
let n;
let PlayingMovie = "-현재 상영작-\n\n";
let movietitle;
console.log(MEGABOX.movie_data);
for (n = 0; n < Object.keys(MEGABOX.movie_data).length; n++) {
if (MEGABOX.movie_data[n].running == 'Y') {
console.log(MEGABOX.movie_data[n]);
movietitle = MEGABOX.movie_data[n].title;
MEGA_PlayingMovieList[movietitle] = MEGABOX.movie_data[n].movie_num;
}
}
console.log(Object.keys(MEGA_PlayingMovieList).length);
if (Object.keys(MEGA_PlayingMovieList).length == 0) {
PushSingleMessage("현재상영작이 없습니다.\n영화관 선택 단계로 이동합니다.");
setTimeout(function () {
PushMessage("영화관 위치를 입력해주세요", "ex1)강남");
}, 1000);
MEGA_flag = 1;
} else if (Object.keys(MEGA_PlayingMovieList).length == 1) {
PlayingMovie += '1: ' + Object.keys(MEGA_PlayingMovieList)[0];
PushMessage(PlayingMovie, "바로 링크가 보내집니다.");
MEGA_title = MEGA_PlayingMovieList[Object.keys(MEGA_PlayingMovieList)[0]];
setTimeout(function () {
const PC_final_URL = "https://www.megabox.co.kr/booking?rpstMovieNo=" + MEGA_title + "&brchNo1=" + MEGA_TheaterLocationCode + '&playDe=' + MEGA_date;
const Smartphone_final_URL = "https://m.megabox.co.kr/booking/movie?movieNo=" + MEGA_title + "&brchNo1=" + MEGA_TheaterLocationCode + '&playDe=' + MEGA_date;
PushURLMessage(PC_final_URL, Smartphone_final_URL);
setTimeout(function () {
initFlag = false;
MEGA_flag = -1;
MEGA_PlayingMovieList = [];
PushSingleMessage("원하시는 브랜드의 번호를 입력해주세요.\n1: CGV\n2: LotteCinema\n3: Megabox\n언제든 브랜드를 바꾸고 싶으시다면 '브랜드'를 입력해주세요.");
}, 1000);
}, 1000);
} else {
let index = 0;
for (let playingmovie = 0; playingmovie < Object.keys(MEGA_PlayingMovieList).length; playingmovie++) {
PlayingMovie += (playingmovie + 1).toString() + '. ' + Object.keys(MEGA_PlayingMovieList)[index++];
PlayingMovie += "\n";
}
console.log(PlayingMovie);
await PushMessage(PlayingMovie, "예매할 영화 번호를 입력해주세요.\n ex)1 (영화 앞 숫자만 입력)");
MEGA_flag = 5;
}
} else if (MEGA_flag == 5) {
const index = parseInt(message.text) - 1;
console.log(Object.keys(MEGA_PlayingMovieList).length);
if (index < 0 || index > Object.keys(MEGA_PlayingMovieList).length - 1) {
PushSingleMessage("다시 입력해주세요!");
} else {
MEGA_title = MEGA_PlayingMovieList[Object.keys(MEGA_PlayingMovieList)[index]];
const PC_final_URL = "https://www.megabox.co.kr/booking?rpstMovieNo=" + MEGA_title + "&brchNo1=" + MEGA_TheaterLocationCode + '&playDe=' + MEGA_date;
const Smartphone_final_URL = "https://m.megabox.co.kr/booking/movie?movieNo=" + MEGA_title + "&brchNo1=" + MEGA_TheaterLocationCode + '&playDe=' + MEGA_date;
console.log(PC_final_URL, Smartphone_final_URL);
PushURLMessage(PC_final_URL, Smartphone_final_URL);
MEGA_PlayingMovieList = []; //영화 리스트 초기화
MegaboxKakaoResultTheater = [];
GetMegaboxKakaoMapURL(MEGA_TheaterLocation);
setTimeout(function () {
console.log(MegaboxKakaoResultTheater[0]);
let MegaboxKakaoResultTheaterNAME = MegaboxKakaoResultTheater[0]['theater_name'];
let MegaboxKakaoResultTheaterURL = MegaboxKakaoResultTheater[0]['theater_url'];
console.log(MegaboxKakaoResultTheaterNAME, MegaboxKakaoResultTheaterURL);
PushMessage(MegaboxKakaoResultTheaterURL, "카카오맵으로 검색한 " + MegaboxKakaoResultTheaterNAME + "의 위치입니다.");
setTimeout(function () {
//EGA_PlayingMovieList = [];
initFlag = false;
MEGA_flag = -1;
PushSingleMessage("원하시는 브랜드의 번호를 입력해주세요.\n1: CGV\n2: LotteCinema\n3: Megabox\n언제든 브랜드를 바꾸고 싶으시다면 '브랜드'를 입력해주세요.");
}, 1000);
}, 2000);
}
}
}
res.sendStatus(200);
}))
//});
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);
}
//오늘 날짜 구하기
function GettingToday() {
var today = new Date();
var year = today.getFullYear();
var month = ('0' + (today.getMonth() + 1)).slice(-2);
var day = ('0' + today.getDate()).slice(-2);
var dateString = year + month + day;
var dateInt = parseInt(dateString);
console.log(dateInt);
return dateInt;
}
//24시간마다 데이터 초기화
var dayInMilliseconds = 1000 * 60 * 60 * 24;
setInterval(function () { MEGABOX.init(); console.log("success") }, dayInMilliseconds);
//CGV - Kakao API로 영화관 위치 찾기
function GetCGVKakaoLocalAPI(location) {
let kakaoOptions = {
url: "https://dapi.kakao.com/v2/local/search/keyword",
method: "GET",
headers: {
'Authorization': `KakaoAK ${KAKAO_KEY}`
},
qs: {
'query': `CGV ${location}`,
//'category_group_code' : 'CT1',
'size': 5
},
encoding: 'UTF-8'
};
request(kakaoOptions, function (err, res, body) {
info_list = JSON.parse(body).documents;
if (!err && res.statusCode == 200) {
info_list.forEach(info => {
if (info.category_name.endsWith("CGV")) {
const theater_info = {
"theater_name": info.place_name.replace("CGV ", ""),
"theater_url": info.place_url
};
CGV_RespondedTheaters.push(theater_info);
console.log(theater_info);
}
});
}
});
}
//Megabox - Kakao API로 영화관 위치 찾기
GetMegaboxKakaoMapURL = async (LOCATE) => {
let KAKAOOPTION = {
url: "https://dapi.kakao.com/v2/local/search/keyword",
method: "GET",
headers: {
'Authorization': `KakaoAK ${KAKAO_KEY}` // commit 할때 지워야 할것
},
qs: {
'query': '메가박스 ' + LOCATE, // 메가박스 영화관이름
//'category_group_code' : 'CT1',
'size': 5
},
encoding: 'UTF-8'
};
let selectable_theaters = [];
request(KAKAOOPTION, function (err, res, body) {
info_list = JSON.parse(body).documents;
if (!err && res.statusCode == 200) {
info_list.forEach(info => {
//console.log(info.category_name);
if (info.category_name.endsWith("메가박스")) {
const theater_info = {
"theater_name": info.place_name,
"theater_url": info.place_url
};
//console.log(theater_info);
//return theater_info;
selectable_theaters.push(theater_info);
}
});
}
console.log(selectable_theaters);
MegaboxKakaoResultTheater = selectable_theaters;
return;
});
}
//메세지 전송하는 function 모음
function SendMessage(eventObj, text1, text2 = "") { //reply message
request.post(
{
url: REPLY_TARGET_URL,
headers: {
'Authorization': `Bearer ${TOKEN}`
},
json: {
"replyToken": eventObj.replyToken,
"messages": [
{
"type": "text",
"text": text1
},
{
"type": "text",
"text": text2
}
]
}
}, (error, response, body) => {
console.log(body);
});
}
function PushMessage(text1, text2 = "") { //push two message
request.post(
{
url: PUSH_TARGET_URL,
headers: {
'Authorization': `Bearer ${TOKEN}`
},
json: {
"to": `${USER_ID}`,
"messages": [
{
"type": "text",
"text": text1
},
{
"type": "text",
"text": text2
}
]
}
}, (error, response, body) => {
console.log(body)
});
}
function PushSingleMessage(text1) {//push single message
request.post(
{
url: PUSH_TARGET_URL,
headers: {
'Authorization': `Bearer ${TOKEN}`
},
json: {
"to": `${USER_ID}`,
"messages": [
{
"type": "text",
"text": text1
}
]
}
}, (error, response, body) => {
console.log(body)
});
}
function PushURLMessage(pcurl, smartphoneurl) {//push single message
request.post(
{
url: PUSH_TARGET_URL,
headers: {
'Authorization': `Bearer ${TOKEN}`
},
json: {
"to": `${USER_ID}`,
"messages": [
{
"type": "text",
"text": "pc버전 url입니다\n\n" + pcurl
},
{
"type": "text",
"text": "mobile버전 url입니다\n\n" + smartphoneurl
}
]
}
}, (error, response, body) => {
console.log(body)
});
}
{
"name": "chatbotdemo",
"version": "1.0.0",
"description": "",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"async": "^3.2.3",
"body-parser": "^1.20.0",
"cheerio": "^1.0.0-rc.11",
"chromedriver": "^101.0.0",
"express": "^4.18.1",
"express-async-handler": "^1.2.0",
"moment": "^2.29.3",
"puppeteer": "^14.1.1",
"request": "^2.88.2",
"selenium-webdriver": "^4.1.2"
}
}