백승욱

Add exception handling function

//=============================================================
var express = require('express');
const request = require('request');
const config = require('./config.json');
//=============================================================
const LINE_URL = 'https://api.line.me/v2/bot/message/reply';
const TOKEN = config.TOKEN;
const KOFIC_URL = 'http://www.kobis.or.kr/kobisopenapi/webservice/rest';
const KOFIC_KEY = config.KOFIC_KEY;
//=============================================================
// 어제 기준 영화 순위(1위 ~ 5위) 출력
exports.ShowYesterdayRank = function(replyToken) {
var yesterday = exports.GetYesterday();
request.get(
{
url: KOFIC_URL+`/boxoffice/searchDailyBoxOfficeList.json?key=${KOFIC_KEY}&targetDt=${yesterday}`,
json:true
},(error, response, body) => {
if(!error && response.statusCode == 200) {
console.log(body.boxOfficeResult);
var movieName = [];
movieName[0] = body.boxOfficeResult.dailyBoxOfficeList[0].movieNm;
movieName[1] = body.boxOfficeResult.dailyBoxOfficeList[1].movieNm;
movieName[2] = body.boxOfficeResult.dailyBoxOfficeList[2].movieNm;
movieName[3] = body.boxOfficeResult.dailyBoxOfficeList[3].movieNm;
movieName[4] = body.boxOfficeResult.dailyBoxOfficeList[4].movieNm;
var movieOpenDt = [];
movieOpenDt[0] = body.boxOfficeResult.dailyBoxOfficeList[0].openDt;
movieOpenDt[1] = body.boxOfficeResult.dailyBoxOfficeList[1].openDt;
movieOpenDt[2] = body.boxOfficeResult.dailyBoxOfficeList[2].openDt;
movieOpenDt[3] = body.boxOfficeResult.dailyBoxOfficeList[3].openDt;
movieOpenDt[4] = body.boxOfficeResult.dailyBoxOfficeList[4].openDt;
var movieAudiAcc = [];
movieAudiAcc[0] = exports.numberWithCommas(body.boxOfficeResult.dailyBoxOfficeList[0].audiAcc);
movieAudiAcc[1] = exports.numberWithCommas(body.boxOfficeResult.dailyBoxOfficeList[1].audiAcc);
movieAudiAcc[2] = exports.numberWithCommas(body.boxOfficeResult.dailyBoxOfficeList[2].audiAcc);
movieAudiAcc[3] = exports.numberWithCommas(body.boxOfficeResult.dailyBoxOfficeList[3].audiAcc);
movieAudiAcc[4] = exports.numberWithCommas(body.boxOfficeResult.dailyBoxOfficeList[4].audiAcc);
request.post(
{
url: LINE_URL,
headers: {
'Authorization': `Bearer ${TOKEN}`
},
json: {
"replyToken":replyToken,
"messages":[
{
"type":"text",
"text":
`[1위]\n영화제목 : ${movieName[0]}\n개봉일 : ${movieOpenDt[0]}\n누적 관객 수 : ${movieAudiAcc[0]}명\n\n`+
`[2위]\n영화제목 : ${movieName[1]}\n개봉일 : ${movieOpenDt[1]}\n누적 관객 수 : ${movieAudiAcc[1]}명\n\n`+
`[3위]\n영화제목 : ${movieName[2]}\n개봉일 : ${movieOpenDt[2]}\n누적 관객 수 : ${movieAudiAcc[2]}명\n\n`+
`[4위]\n영화제목 : ${movieName[3]}\n개봉일 : ${movieOpenDt[3]}\n누적 관객 수 : ${movieAudiAcc[3]}명\n\n`+
`[5위]\n영화제목 : ${movieName[4]}\n개봉일 : ${movieOpenDt[4]}\n누적 관객 수 : ${movieAudiAcc[4]}명\n\n`
}
]
}
},(error, response, body) => {
console.log(body)
});
}
});
}
// 어제 날짜를 YYYYMMDD 형식(type: string)으로 반환하는 함수
exports.GetYesterday = function() {
var today = new Date();
var yesterday = new Date(today.setDate(today.getDate() - 1));
var year = yesterday.getFullYear();
var month = ('0' + (yesterday.getMonth() + 1)).slice(-2);
var day = ('0' + yesterday.getDate()).slice(-2);
return (year + month + day);
}
// 숫자 사이에 콤마(,) 찍고 반환하는 함수(입력, 출력 모두 문자열)
exports.numberWithCommas = function(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
File mode changed
//=============================================================
var express = require('express');
const request = require('request');
const config = require('./config.json');
//=============================================================
const LINE_URL = 'https://api.line.me/v2/bot/message/reply'
const TOKEN = config.TOKEN;
const KOFIC_URL = 'http://www.kobis.or.kr/kobisopenapi/webservice/rest'
const KOFIC_KEY = config.KOFIC_KEY;
//=============================================================
exports.MovieInfo = function(replyToken, message) {
request.get(
{
url: KOFIC_URL+`/movie/searchMovieInfo.json?key=${KOFIC_KEY}&movieCd=${message}`,
json:true
},(error, response, body) => {
if(!error && response.statusCode == 200) {
console.log(body.movieInfoResult);
var MovieInfo = body.movieInfoResult.movieInfo;
var MovieName = MovieInfo.movieNm;
var MovieDate = `${MovieInfo.openDt.slice(0,4)}${MovieInfo.openDt.slice(4,6)}${MovieInfo.openDt.slice(6,8)}일`;
var MovieTime = MovieInfo.showTm;
var MovieGenres = [];
for(var i in MovieInfo.genres)
{
MovieGenres.push(MovieInfo.genres[i].genreNm);
}
var MovieDirec = MovieInfo.directors[0].peopleNm;
var MovieActors = [];
for(var i=0; i<MovieInfo.actors.length && i<5; i++)
{
MovieActors[i] = MovieInfo.actors[i].peopleNm;
}
request.post(
{
url: LINE_URL,
headers: {
'Authorization': `Bearer ${TOKEN}`
},
json: {
"replyToken":replyToken,
"messages":[
{
"type":"text",
"text":`영화명: ${MovieName}\n개봉날짜: ${MovieDate}\n상영시간: ${MovieTime}분\n장르: ${MovieGenres}\n감독: ${MovieDirec}\n출연배우: ${MovieActors}`
}
]
}
},(error, response, body) => {
console.log(body)
});
}
});
}
var express = require('express');
const request = require('request');
var config = require('./config.json');
const TARGET_URL = 'https://api.line.me/v2/bot/message/reply'
const TOKEN = config.TOKEN;
const KOFIC_URL = 'http://www.kobis.or.kr/kobisopenapi/webservice/rest'
//Enter a movie title in the message variable.
//It will then return the movie title, director, and actor information to Line Messenger.
exports.movielist = function (replyToken, message) {
var encodedMessage = encodeURI(message);
request.get(
{
url: KOFIC_URL+`/movie/searchMovieList.json?key=${config.KOFIC_KEY}&movieNm=${encodedMessage}`,
json:true
},(error, response, body) => {
if(!error && response.statusCode == 200) {
console.log(body.message);
var result = '', movieNm, prdtYear, directors;
for (let i = 0; i < body.movieListResult.movieList.length; i ++){
movieNm = body.movieListResult.movieList[i].movieNm;
prdtYear = body.movieListResult.movieList[i].prdtYear;
movieCd = body.movieListResult.movieList[i].movieCd;
if(body.movieListResult.movieList[i].directors.length === 0){
directors = "감독정보없음"
}
else{
directors = body.movieListResult.movieList[i].directors[0].peopleNm;
}
result += '제목: ' + movieNm + `(${prdtYear})` + '\n' + '감독: ' + directors + '\n' + '영화코드: ' + movieCd + '\n';
}
request.post(
{
url: TARGET_URL,
headers: {
'Authorization': `Bearer ${TOKEN}`
},
json: {
"replyToken":replyToken,
"messages":[
{
"type":"text",
"text":result
}
]
}
},(error, response, body) => {
console.log(body)
});
}
});
}
const request = require('request');
var config = require('./config.json');
const TARGET_URL = 'https://api.line.me/v2/bot/message/reply'
const TOKEN = config.TOKEN;
const KOFIC_URL = 'http://www.kobis.or.kr/kobisopenapi/webservice/rest'
//Return random integer.
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min; //Exclude maximum value, include minimum value
}
//Get weekend boxoffice movie code.
//Then return list fill with movie code.
function weekendBoxOfficeMovie() {
var year = String(getRandomInt(2010,2023));
var date = String(getRandomInt(1,13));
if(year == 2022){
date = String(getRandomInt(1,6));
}
if(date < 10){
date = '0'+date;
}
date += '15';
return new Promise((resolve) => {
var moviecode = [];
request.get(
{
url: KOFIC_URL+`/boxoffice/searchWeeklyBoxOfficeList.json?key=${config.KOFIC_KEY}&targetDt=${year + date}&itemPerPage=7`,
json:true
},(error, response, body) => {
if(!error && response.statusCode == 200) {
for(let i = 0; i < body.boxOfficeResult.weeklyBoxOfficeList.length; i++){
moviecode.push(body.boxOfficeResult.weeklyBoxOfficeList[i].movieCd)
}
resolve(moviecode)
}
});
});
}
//Returns the title, year of release, names of directors and actors.
//The return format is array and index is as follows:
//[title, year of release, director, actor1, actor2]
async function movieinfo(message){
moviecdlist = await weekendBoxOfficeMovie();
return new Promise((resolve) => {
movieresult = [];
for(let i = 0; i < moviecdlist.length; i++){
request.get(
{
url: KOFIC_URL + `/movie/searchMovieInfo.json?key=${config.KOFIC_KEY}&movieCd=${moviecdlist[i]}`,
json:true
}
,(error,response, body) => {
if(!error && response.statusCode == 200) {
for(let j = 0; j < body.movieInfoResult.movieInfo.genres.length; j++){
if(body.movieInfoResult.movieInfo.genres[j].genreNm == message){
var title = body.movieInfoResult.movieInfo.movieNm;
var openyear = body.movieInfoResult.movieInfo.prdtYear;
if(body.movieInfoResult.movieInfo.directors.length == 0){
var director = "감독정보없음"
}
else{
var director = body.movieInfoResult.movieInfo.directors[0].peopleNm
}
if(body.movieInfoResult.movieInfo.actors.length == 0){
var actor_1 = "배우정보없음"
var actor_2 = "배우정보없음"
}
else if(body.movieInfoResult.movieInfo.actors.length == 1){
var actor_1 = body.movieInfoResult.movieInfo.actors[0].peopleNm
var actor_2 = "배우정보없음"
}
else{
var actor_1 = body.movieInfoResult.movieInfo.actors[0].peopleNm
var actor_2 = body.movieInfoResult.movieInfo.actors[1].peopleNm
}
movieresult.push([title, openyear, director, actor_1, actor_2])
} //제목, 개봉년도, 감독, 배우1, 배우2
}
resolve(movieresult);
}
});
}
});
}
//Enter a movie genre in the message variable.
//It will then return movie title, year of release, director and actor information to Line Messenger.
exports.movieRecommend = async function(replyToken, message){
var movieresult = [];
while(1){
movielist = await movieinfo(message);
for(let i = 0; i < movielist.length; i ++){
movieresult.push(movielist[i]);
}
if(movieresult.length > 1){
break;
}
}
var movierecommend_output = '';
for(let i = 0; i < movieresult.length; i++){
movierecommend_output += `제목: ${movieresult[i][0]}(${movieresult[i][1]})\n감독: ${movieresult[i][2]}\n배우: ${movieresult[i][3]}, ${movieresult[i][4]}\n`
}
request.post(
{
url: TARGET_URL,
headers: {
'Authorization': `Bearer ${TOKEN}`
},
json: {
"replyToken":replyToken,
"messages":[
{
"type":"text",
"text":movierecommend_output
}
]
}
},(error, response, body) => {
console.log(body)
});
}
\ No newline at end of file
{
"TOKEN" : "Insert user token value",
"KOFIC_KEY" : "Insert user key value",
"domain" : "Insert user domain"
}
\ No newline at end of file
//=============================================================
var express = require('express');
const request = require('request');
const config = require('./config.json');
const dailyBoxOfficeList = require('./DailyBoxOfficeList.js');
//=============================================================
const LINE_URL = 'https://api.line.me/v2/bot/message/reply'
const TOKEN = config.TOKEN;
const KOFIC_URL = 'http://www.kobis.or.kr/kobisopenapi/webservice/rest';
const KOFIC_KEY = config.KOFIC_KEY;
//=============================================================
const fs = require('fs');
const path = require('path');
const HTTPS = require('https');
const domain = config.domain;
const sslport = 23023;
const bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.json());
//=============================================================
var BoxOffice = require('./DailyBoxOfficeList.js');
var MovieList = require('./MovieList.js');
var MovieInfo = require('./MovieInfo.js');
// RECEIVE MESSAGE
app.post('/hook', function (req, res) {
var eventObj = req.body.events[0];
// console.log for debugging
console.log('======================', new Date() ,'======================');
console.log('[request]', req.body);
console.log('[request source] ', eventObj.source);
console.log('[request message]', eventObj.message);
Response(eventObj.replyToken, eventObj.message.text);
res.sendStatus(200);
});
// RESPONSE TO MESSAGE
function Response(replyToken, message){
// 사용자가 보낸 라인 메시지 문자열 안에 특정 문자열이 있으면, 특정 함수 실행
if(message.includes('최신') || message.includes('순위') || message.includes('오늘') || message.includes('추천')) {
BoxOffice.ShowYesterdayRank(replyToken);
} else if (isNaN(message) === false && message.length === 8) {
// (예시) 영화 줄거리 출력
MovieInfo.MovieInfo(replyToken, message);
}
else if (typeof(message) === 'string') {
// (예시) 영화 목록 출력
MovieList.movielist(replyToken, message);
}
}
// ※ WARNING: DO NOT TOUCH THIS CODE SECTION ※
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);
}
\ No newline at end of file
This diff is collapsed. Click to expand it.
{
"name": "trans",
"version": "1.0.0",
"description": "",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.17.1",
"request": "^2.88.2"
}
}