백승욱

Add exception handling function

1 -//=============================================================
2 -var express = require('express');
3 -const request = require('request');
4 -const config = require('./config.json');
5 -//=============================================================
6 -const LINE_URL = 'https://api.line.me/v2/bot/message/reply';
7 -const TOKEN = config.TOKEN;
8 -const KOFIC_URL = 'http://www.kobis.or.kr/kobisopenapi/webservice/rest';
9 -const KOFIC_KEY = config.KOFIC_KEY;
10 -//=============================================================
11 -
12 -// 어제 기준 영화 순위(1위 ~ 5위) 출력
13 -exports.ShowYesterdayRank = function(replyToken) {
14 -
15 - var yesterday = exports.GetYesterday();
16 -
17 - request.get(
18 - {
19 - url: KOFIC_URL+`/boxoffice/searchDailyBoxOfficeList.json?key=${KOFIC_KEY}&targetDt=${yesterday}`,
20 - json:true
21 - },(error, response, body) => {
22 - if(!error && response.statusCode == 200) {
23 - console.log(body.boxOfficeResult);
24 -
25 - var movieName = [];
26 - movieName[0] = body.boxOfficeResult.dailyBoxOfficeList[0].movieNm;
27 - movieName[1] = body.boxOfficeResult.dailyBoxOfficeList[1].movieNm;
28 - movieName[2] = body.boxOfficeResult.dailyBoxOfficeList[2].movieNm;
29 - movieName[3] = body.boxOfficeResult.dailyBoxOfficeList[3].movieNm;
30 - movieName[4] = body.boxOfficeResult.dailyBoxOfficeList[4].movieNm;
31 -
32 - var movieOpenDt = [];
33 - movieOpenDt[0] = body.boxOfficeResult.dailyBoxOfficeList[0].openDt;
34 - movieOpenDt[1] = body.boxOfficeResult.dailyBoxOfficeList[1].openDt;
35 - movieOpenDt[2] = body.boxOfficeResult.dailyBoxOfficeList[2].openDt;
36 - movieOpenDt[3] = body.boxOfficeResult.dailyBoxOfficeList[3].openDt;
37 - movieOpenDt[4] = body.boxOfficeResult.dailyBoxOfficeList[4].openDt;
38 -
39 - var movieAudiAcc = [];
40 - movieAudiAcc[0] = exports.numberWithCommas(body.boxOfficeResult.dailyBoxOfficeList[0].audiAcc);
41 - movieAudiAcc[1] = exports.numberWithCommas(body.boxOfficeResult.dailyBoxOfficeList[1].audiAcc);
42 - movieAudiAcc[2] = exports.numberWithCommas(body.boxOfficeResult.dailyBoxOfficeList[2].audiAcc);
43 - movieAudiAcc[3] = exports.numberWithCommas(body.boxOfficeResult.dailyBoxOfficeList[3].audiAcc);
44 - movieAudiAcc[4] = exports.numberWithCommas(body.boxOfficeResult.dailyBoxOfficeList[4].audiAcc);
45 -
46 - request.post(
47 - {
48 - url: LINE_URL,
49 - headers: {
50 - 'Authorization': `Bearer ${TOKEN}`
51 - },
52 - json: {
53 - "replyToken":replyToken,
54 - "messages":[
55 - {
56 - "type":"text",
57 - "text":
58 - `[1위]\n영화제목 : ${movieName[0]}\n개봉일 : ${movieOpenDt[0]}\n누적 관객 수 : ${movieAudiAcc[0]}명\n\n`+
59 - `[2위]\n영화제목 : ${movieName[1]}\n개봉일 : ${movieOpenDt[1]}\n누적 관객 수 : ${movieAudiAcc[1]}명\n\n`+
60 - `[3위]\n영화제목 : ${movieName[2]}\n개봉일 : ${movieOpenDt[2]}\n누적 관객 수 : ${movieAudiAcc[2]}명\n\n`+
61 - `[4위]\n영화제목 : ${movieName[3]}\n개봉일 : ${movieOpenDt[3]}\n누적 관객 수 : ${movieAudiAcc[3]}명\n\n`+
62 - `[5위]\n영화제목 : ${movieName[4]}\n개봉일 : ${movieOpenDt[4]}\n누적 관객 수 : ${movieAudiAcc[4]}명\n\n`
63 - }
64 - ]
65 - }
66 - },(error, response, body) => {
67 - console.log(body)
68 - });
69 - }
70 - });
71 -}
72 -
73 -
74 -// 어제 날짜를 YYYYMMDD 형식(type: string)으로 반환하는 함수
75 -exports.GetYesterday = function() {
76 -
77 - var today = new Date();
78 - var yesterday = new Date(today.setDate(today.getDate() - 1));
79 -
80 - var year = yesterday.getFullYear();
81 - var month = ('0' + (yesterday.getMonth() + 1)).slice(-2);
82 - var day = ('0' + yesterday.getDate()).slice(-2);
83 -
84 - return (year + month + day);
85 -}
86 -
87 -
88 -// 숫자 사이에 콤마(,) 찍고 반환하는 함수(입력, 출력 모두 문자열)
89 -exports.numberWithCommas = function(x) {
90 - return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
91 -}
File mode changed
1 -//=============================================================
2 -var express = require('express');
3 -const request = require('request');
4 -const config = require('./config.json');
5 -//=============================================================
6 -const LINE_URL = 'https://api.line.me/v2/bot/message/reply'
7 -const TOKEN = config.TOKEN;
8 -const KOFIC_URL = 'http://www.kobis.or.kr/kobisopenapi/webservice/rest'
9 -const KOFIC_KEY = config.KOFIC_KEY;
10 -//=============================================================
11 -
12 -exports.MovieInfo = function(replyToken, message) {
13 - request.get(
14 - {
15 - url: KOFIC_URL+`/movie/searchMovieInfo.json?key=${KOFIC_KEY}&movieCd=${message}`,
16 - json:true
17 - },(error, response, body) => {
18 - if(!error && response.statusCode == 200) {
19 - console.log(body.movieInfoResult);
20 - var MovieInfo = body.movieInfoResult.movieInfo;
21 - var MovieName = MovieInfo.movieNm;
22 - var MovieDate = `${MovieInfo.openDt.slice(0,4)}${MovieInfo.openDt.slice(4,6)}${MovieInfo.openDt.slice(6,8)}일`;
23 - var MovieTime = MovieInfo.showTm;
24 - var MovieGenres = [];
25 - for(var i in MovieInfo.genres)
26 - {
27 - MovieGenres.push(MovieInfo.genres[i].genreNm);
28 - }
29 - var MovieDirec = MovieInfo.directors[0].peopleNm;
30 - var MovieActors = [];
31 - for(var i=0; i<MovieInfo.actors.length && i<5; i++)
32 - {
33 - MovieActors[i] = MovieInfo.actors[i].peopleNm;
34 - }
35 -
36 - request.post(
37 - {
38 - url: LINE_URL,
39 - headers: {
40 - 'Authorization': `Bearer ${TOKEN}`
41 - },
42 - json: {
43 - "replyToken":replyToken,
44 - "messages":[
45 - {
46 - "type":"text",
47 - "text":`영화명: ${MovieName}\n개봉날짜: ${MovieDate}\n상영시간: ${MovieTime}분\n장르: ${MovieGenres}\n감독: ${MovieDirec}\n출연배우: ${MovieActors}`
48 - }
49 - ]
50 - }
51 - },(error, response, body) => {
52 - console.log(body)
53 - });
54 - }
55 - });
56 -}
1 -var express = require('express');
2 -const request = require('request');
3 -var config = require('./config.json');
4 -const TARGET_URL = 'https://api.line.me/v2/bot/message/reply'
5 -const TOKEN = config.TOKEN;
6 -const KOFIC_URL = 'http://www.kobis.or.kr/kobisopenapi/webservice/rest'
7 -
8 -//Enter a movie title in the message variable.
9 -//It will then return the movie title, director, and actor information to Line Messenger.
10 -exports.movielist = function (replyToken, message) {
11 - var encodedMessage = encodeURI(message);
12 - request.get(
13 - {
14 - url: KOFIC_URL+`/movie/searchMovieList.json?key=${config.KOFIC_KEY}&movieNm=${encodedMessage}`,
15 - json:true
16 - },(error, response, body) => {
17 - if(!error && response.statusCode == 200) {
18 - console.log(body.message);
19 - var result = '', movieNm, prdtYear, directors;
20 - for (let i = 0; i < body.movieListResult.movieList.length; i ++){
21 - movieNm = body.movieListResult.movieList[i].movieNm;
22 - prdtYear = body.movieListResult.movieList[i].prdtYear;
23 - movieCd = body.movieListResult.movieList[i].movieCd;
24 - if(body.movieListResult.movieList[i].directors.length === 0){
25 - directors = "감독정보없음"
26 - }
27 - else{
28 - directors = body.movieListResult.movieList[i].directors[0].peopleNm;
29 - }
30 - result += '제목: ' + movieNm + `(${prdtYear})` + '\n' + '감독: ' + directors + '\n' + '영화코드: ' + movieCd + '\n';
31 - }
32 - request.post(
33 - {
34 - url: TARGET_URL,
35 - headers: {
36 - 'Authorization': `Bearer ${TOKEN}`
37 - },
38 - json: {
39 - "replyToken":replyToken,
40 - "messages":[
41 - {
42 - "type":"text",
43 - "text":result
44 - }
45 - ]
46 - }
47 - },(error, response, body) => {
48 - console.log(body)
49 - });
50 - }
51 - });
52 -
53 -}
1 -const request = require('request');
2 -var config = require('./config.json');
3 -const TARGET_URL = 'https://api.line.me/v2/bot/message/reply'
4 -const TOKEN = config.TOKEN;
5 -const KOFIC_URL = 'http://www.kobis.or.kr/kobisopenapi/webservice/rest'
6 -
7 -//Return random integer.
8 -function getRandomInt(min, max) {
9 - min = Math.ceil(min);
10 - max = Math.floor(max);
11 - return Math.floor(Math.random() * (max - min)) + min; //Exclude maximum value, include minimum value
12 -}
13 -
14 -//Get weekend boxoffice movie code.
15 -//Then return list fill with movie code.
16 -function weekendBoxOfficeMovie() {
17 - var year = String(getRandomInt(2010,2023));
18 - var date = String(getRandomInt(1,13));
19 - if(year == 2022){
20 - date = String(getRandomInt(1,6));
21 - }
22 - if(date < 10){
23 - date = '0'+date;
24 - }
25 - date += '15';
26 - return new Promise((resolve) => {
27 - var moviecode = [];
28 - request.get(
29 - {
30 - url: KOFIC_URL+`/boxoffice/searchWeeklyBoxOfficeList.json?key=${config.KOFIC_KEY}&targetDt=${year + date}&itemPerPage=7`,
31 - json:true
32 - },(error, response, body) => {
33 - if(!error && response.statusCode == 200) {
34 - for(let i = 0; i < body.boxOfficeResult.weeklyBoxOfficeList.length; i++){
35 - moviecode.push(body.boxOfficeResult.weeklyBoxOfficeList[i].movieCd)
36 - }
37 - resolve(moviecode)
38 - }
39 - });
40 - });
41 -}
42 -//Returns the title, year of release, names of directors and actors.
43 -//The return format is array and index is as follows:
44 -//[title, year of release, director, actor1, actor2]
45 -async function movieinfo(message){
46 - moviecdlist = await weekendBoxOfficeMovie();
47 -
48 - return new Promise((resolve) => {
49 - movieresult = [];
50 - for(let i = 0; i < moviecdlist.length; i++){
51 - request.get(
52 - {
53 - url: KOFIC_URL + `/movie/searchMovieInfo.json?key=${config.KOFIC_KEY}&movieCd=${moviecdlist[i]}`,
54 - json:true
55 - }
56 - ,(error,response, body) => {
57 - if(!error && response.statusCode == 200) {
58 - for(let j = 0; j < body.movieInfoResult.movieInfo.genres.length; j++){
59 - if(body.movieInfoResult.movieInfo.genres[j].genreNm == message){
60 - var title = body.movieInfoResult.movieInfo.movieNm;
61 - var openyear = body.movieInfoResult.movieInfo.prdtYear;
62 - if(body.movieInfoResult.movieInfo.directors.length == 0){
63 - var director = "감독정보없음"
64 - }
65 - else{
66 - var director = body.movieInfoResult.movieInfo.directors[0].peopleNm
67 - }
68 - if(body.movieInfoResult.movieInfo.actors.length == 0){
69 - var actor_1 = "배우정보없음"
70 - var actor_2 = "배우정보없음"
71 - }
72 - else if(body.movieInfoResult.movieInfo.actors.length == 1){
73 - var actor_1 = body.movieInfoResult.movieInfo.actors[0].peopleNm
74 - var actor_2 = "배우정보없음"
75 - }
76 - else{
77 - var actor_1 = body.movieInfoResult.movieInfo.actors[0].peopleNm
78 - var actor_2 = body.movieInfoResult.movieInfo.actors[1].peopleNm
79 - }
80 - movieresult.push([title, openyear, director, actor_1, actor_2])
81 -
82 - } //제목, 개봉년도, 감독, 배우1, 배우2
83 - }
84 - resolve(movieresult);
85 - }
86 - });
87 - }
88 - });
89 -}
90 -
91 -//Enter a movie genre in the message variable.
92 -//It will then return movie title, year of release, director and actor information to Line Messenger.
93 -exports.movieRecommend = async function(replyToken, message){
94 - var movieresult = [];
95 - while(1){
96 - movielist = await movieinfo(message);
97 - for(let i = 0; i < movielist.length; i ++){
98 - movieresult.push(movielist[i]);
99 - }
100 - if(movieresult.length > 1){
101 - break;
102 - }
103 - }
104 - var movierecommend_output = '';
105 - for(let i = 0; i < movieresult.length; i++){
106 - movierecommend_output += `제목: ${movieresult[i][0]}(${movieresult[i][1]})\n감독: ${movieresult[i][2]}\n배우: ${movieresult[i][3]}, ${movieresult[i][4]}\n`
107 - }
108 - request.post(
109 - {
110 - url: TARGET_URL,
111 - headers: {
112 - 'Authorization': `Bearer ${TOKEN}`
113 - },
114 - json: {
115 - "replyToken":replyToken,
116 - "messages":[
117 - {
118 - "type":"text",
119 - "text":movierecommend_output
120 - }
121 - ]
122 - }
123 - },(error, response, body) => {
124 - console.log(body)
125 - });
126 -}
...\ No newline at end of file ...\ No newline at end of file
1 -{
2 - "TOKEN" : "Insert user token value",
3 - "KOFIC_KEY" : "Insert user key value",
4 - "domain" : "Insert user domain"
5 -}
...\ No newline at end of file ...\ No newline at end of file
1 -//=============================================================
2 -var express = require('express');
3 -const request = require('request');
4 -const config = require('./config.json');
5 -const dailyBoxOfficeList = require('./DailyBoxOfficeList.js');
6 -//=============================================================
7 -const LINE_URL = 'https://api.line.me/v2/bot/message/reply'
8 -const TOKEN = config.TOKEN;
9 -const KOFIC_URL = 'http://www.kobis.or.kr/kobisopenapi/webservice/rest';
10 -const KOFIC_KEY = config.KOFIC_KEY;
11 -//=============================================================
12 -const fs = require('fs');
13 -const path = require('path');
14 -const HTTPS = require('https');
15 -const domain = config.domain;
16 -const sslport = 23023;
17 -const bodyParser = require('body-parser');
18 -var app = express();
19 -app.use(bodyParser.json());
20 -//=============================================================
21 -var BoxOffice = require('./DailyBoxOfficeList.js');
22 -var MovieList = require('./MovieList.js');
23 -var MovieInfo = require('./MovieInfo.js');
24 -
25 -// RECEIVE MESSAGE
26 -app.post('/hook', function (req, res) {
27 -
28 - var eventObj = req.body.events[0];
29 -
30 - // console.log for debugging
31 - console.log('======================', new Date() ,'======================');
32 - console.log('[request]', req.body);
33 - console.log('[request source] ', eventObj.source);
34 - console.log('[request message]', eventObj.message);
35 -
36 - Response(eventObj.replyToken, eventObj.message.text);
37 -
38 - res.sendStatus(200);
39 -});
40 -
41 -
42 -// RESPONSE TO MESSAGE
43 -function Response(replyToken, message){
44 - // 사용자가 보낸 라인 메시지 문자열 안에 특정 문자열이 있으면, 특정 함수 실행
45 - if(message.includes('최신') || message.includes('순위') || message.includes('오늘') || message.includes('추천')) {
46 - BoxOffice.ShowYesterdayRank(replyToken);
47 - } else if (isNaN(message) === false && message.length === 8) {
48 - // (예시) 영화 줄거리 출력
49 - MovieInfo.MovieInfo(replyToken, message);
50 - }
51 - else if (typeof(message) === 'string') {
52 - // (예시) 영화 목록 출력
53 - MovieList.movielist(replyToken, message);
54 - }
55 -}
56 -
57 -
58 -// ※ WARNING: DO NOT TOUCH THIS CODE SECTION ※
59 -try {
60 - const option = {
61 - ca: fs.readFileSync('/etc/letsencrypt/live/' + domain +'/fullchain.pem'),
62 - key: fs.readFileSync(path.resolve(process.cwd(), '/etc/letsencrypt/live/' + domain +'/privkey.pem'), 'utf8').toString(),
63 - cert: fs.readFileSync(path.resolve(process.cwd(), '/etc/letsencrypt/live/' + domain +'/cert.pem'), 'utf8').toString(),
64 - };
65 -
66 - HTTPS.createServer(option, app).listen(sslport, () => {
67 - console.log(`[HTTPS] Server is started on port ${sslport}`);
68 - });
69 -} catch (error) {
70 - console.log('[HTTPS] HTTPS 오류가 발생하였습니다. HTTPS 서버는 실행되지 않습니다.');
71 - console.log(error);
72 -}
...\ No newline at end of file ...\ No newline at end of file
This diff is collapsed. Click to expand it.
1 -{
2 - "name": "trans",
3 - "version": "1.0.0",
4 - "description": "",
5 - "main": "app.js",
6 - "scripts": {
7 - "test": "echo \"Error: no test specified\" && exit 1"
8 - },
9 - "author": "",
10 - "license": "ISC",
11 - "dependencies": {
12 - "express": "^4.17.1",
13 - "request": "^2.88.2"
14 - }
15 -}