은승우

Update app.js

Showing 1 changed file with 190 additions and 35 deletions
1 var express = require("express"); 1 var express = require("express");
2 var app = express(); 2 var app = express();
3 +var cheerio = require('cheerio');
3 const line = require('@line/bot-sdk'); 4 const line = require('@line/bot-sdk');
4 var request = require('request'); 5 var request = require('request');
5 var https=require('https'); 6 var https=require('https');
...@@ -18,33 +19,6 @@ var httpsOptions = { ...@@ -18,33 +19,6 @@ var httpsOptions = {
18 http.createServer(app).listen(80); 19 http.createServer(app).listen(80);
19 https.createServer(httpsOptions, app).listen(443); 20 https.createServer(httpsOptions, app).listen(443);
20 21
21 -/*
22 -const lex= require('greenlock-express').create({
23 - version: 'draft-11', // 버전2
24 - store: require('greenlock-store-fs'),
25 - configDir: '/etc/letsencrypt', // 또는 ~/letsencrypt/etc
26 - approveDomains: (opts, certs, cb) => {
27 - if (certs) {
28 - opts.domains = ['oss.chatbot.bu.to', 'www.oss.chatbot.bu.to'];
29 - } else {
30 - opts.email = 'sweun1@naver.com';
31 - opts.agreeTos = true;
32 - }
33 - cb(null, { options: opts, certs });
34 -
35 - },
36 - renewWithin: 81 * 24 * 60 * 60 * 1000,
37 - renewBy: 80 * 24 * 60 * 60 * 1000,
38 -});
39 -https.createServer(lex.httpsOptions, lex.middleware(app)).listen((process.env.SSL_PORT || 443),()=>{
40 - console.log("server on 443");
41 -});
42 -http.createServer(lex.middleware(require('redirect-https')())).listen(process.env.PORT || 80,()=>{
43 - console.log("server on 80");
44 -});
45 -*/
46 -//papago api
47 -
48 22
49 //번역 api_url 23 //번역 api_url
50 var translate_api_url = 'https://openapi.naver.com/v1/papago/n2mt'; 24 var translate_api_url = 'https://openapi.naver.com/v1/papago/n2mt';
...@@ -71,6 +45,8 @@ const client = new line.Client(config); ...@@ -71,6 +45,8 @@ const client = new line.Client(config);
71 // about the middleware, please refer to doc 45 // about the middleware, please refer to doc
72 46
73 47
48 +var songList=[]; // list to store music(singer, song, lyric url)
49 +
74 50
75 app.post('/webhook', line.middleware(config), (req, res) => { 51 app.post('/webhook', line.middleware(config), (req, res) => {
76 Promise 52 Promise
...@@ -82,12 +58,195 @@ app.post('/webhook', line.middleware(config), (req, res) => { ...@@ -82,12 +58,195 @@ app.post('/webhook', line.middleware(config), (req, res) => {
82 // event handler 58 // event handler
83 function handleEvent(event) { 59 function handleEvent(event) {
84 console.log(event.message); 60 console.log(event.message);
85 - if (event.type !== 'message'&& event.message.type !== 'text') { 61 + if (event.type !== 'message' || event.message.type !== 'text') {
86 // ignore non-text-message event 62 // ignore non-text-message event
87 return Promise.resolve(null); 63 return Promise.resolve(null);
88 } 64 }
65 + else if(event.message.text.substring(0, 5)=='차트 보기')
66 + {
67 + // music list 출력
68 + var url="https://www.genie.co.kr/chart/top200";
69 +
70 + request(url, function(error, response, html){
71 + var $ = cheerio.load(html);
72 + const $bodyList= $('#body-content > div.newest-list > div > table > tbody > tr');
73 +
74 + $bodyList.each(function(i, elem){
75 + if(i<20)
76 + {
77 + songList.push(
78 + {
79 + singer: $(this).find("td.info").find("a.artist.ellipsis").text().trim(),
80 + song: $(this).find("td.info").find("a.title.ellipsis").text().trim(),
81 + url: 'https://www.genie.co.kr/detail/songInfo?xgnm='+$(this).attr("songid")
82 + });
83 + }
84 + else
85 + {
86 + return;
87 + }
88 + });
89 +
90 + return new Promise(function(resolve, reject)
91 + {
92 + var result = { type: 'text', text:''};
93 +
94 + for(var i=0; i<songList.length; i++)
95 + {
96 + result.text+=i+1 + ". "+ songList[i].singer+" - "+songList[i].song+"\n";
97 + }
98 + console.log(result.text);
99 + client.replyMessage(event.replyToken, result).then(resolve).catch(reject);
100 + });
101 + });
102 + }
103 + else if(event.message.text.substring(0, 5)=='가사 검색')
104 + {
105 + var userNum=event.message.text[6]
106 + var newUrl=songList[userNum-1].url;
107 + var lyric='';
108 +
109 + request(newUrl, function(error, response, html)
110 + {
111 + var $ = cheerio.load(html);
112 +
113 + lyric=$('#pLyrics > p').text();
114 + lyric=lyric.substring(0, 150);
115 +
116 + return new Promise(function(resolve, reject)
117 + {
118 + //언어 감지 option
119 + var detect_options =
120 + {
121 + url : languagedetect_api_url,
122 + form : {'query': lyric},
123 + headers: {'X-Naver-Client-Id': client_id, 'X-Naver-Client-Secret': client_secret}
124 + };
125 +
126 + console.log(songList[userNum].song);
127 + console.log(lyric);
128 +
129 + //papago 언어 감지
130 + request.post(detect_options, (error,response,body)=>
131 + {
132 + if(!error && response.statusCode == 200)
133 + {
134 + var detect_body = JSON.parse(response.body);
135 + var source = '';
136 + var target = '';
137 + var result = { type: 'text', text:''};
138 +
139 + //언어 감지가 제대로 됐는지 확인
140 + console.log(detect_body.langCode);
89 141
90 - if (event.type == 'message'&& event.message.type == 'text') { 142 + //번역은 한국어->영어 / 영어->한국어만 지원
143 + if(detect_body.langCode == 'ko'||detect_body.langCode == 'en')
144 + {
145 + source = detect_body.langCode == 'ko' ? 'ko':'en';
146 + target = source == 'ko' ? 'en':'ko';
147 + //papago 번역 option
148 + var options = {
149 + url: translate_api_url,
150 + // 한국어(source : ko), 영어(target: en), 카톡에서 받는 메시지(text)
151 + form: {'source':source, 'target':target, 'text': lyric},
152 + headers: {'X-Naver-Client-Id': client_id, 'X-Naver-Client-Secret': client_secret}
153 + };
154 +
155 + // Naver Post API
156 + request.post(options, function(error, response, body){
157 + // Translate API Sucess
158 + if(!error && response.statusCode == 200){
159 + // JSON
160 + var objBody = JSON.parse(response.body);
161 + // Message 잘 찍히는지 확인
162 +
163 + result.text = objBody.message.result.translatedText;
164 + console.log("result: "+result.text);
165 + //번역된 문장 보내기
166 + client.replyMessage(event.replyToken,result).then(resolve).catch(reject);
167 + }
168 + });
169 + }
170 + // 메시지의 언어가 영어 또는 한국어가 아닐 경우
171 + else
172 + {
173 + result.text = '언어를 감지할 수 없습니다. \n 번역 언어는 한글 또는 영어만 가능합니다.';
174 + client.replyMessage(event.replyToken, result).then(resolve).catch(reject);
175 + }
176 + }
177 + else
178 + {
179 + console.log("status code is not 200");
180 + }
181 + });
182 + });
183 + });
184 + }
185 + else if (event.message.text.indexOf('http')!=-1) {
186 + return new Promise(async(resolve,reject)=>{
187 + var uriBase = 'https://koreacentral.api.cognitive.microsoft.com/vision/v2.1/ocr';
188 + var imageUrl=event.message.text;
189 + var options = {
190 + uri: uriBase,
191 + qs: {
192 + 'language': 'unk',
193 + 'detectOrientation': 'true',
194 + },
195 + headers: {
196 + 'Content-Type': 'application/json',
197 + 'Ocp-Apim-Subscription-Key': '979dc5d63344438fa4701c62feebb7dc'
198 + },
199 + body:'{"url": ' + '"' + imageUrl + '"}',
200 + };
201 +
202 + request.post(options, function (error, response, body) {
203 + var data=JSON.stringify(body);
204 + console.log(data);
205 + var text='';
206 + while(data.indexOf('text\\')!=-1)
207 + {
208 + data=data.substring(data.indexOf('text\\')+9);
209 + text+=data.substring(0,data.indexOf("\\"))+" ";
210 + }
211 + text=text.substring(text.length/10+1,text.length/8+2);
212 + text=text.replace(' ','');
213 + text=text.substr(0,text.indexOf(' '));
214 + console.log(text);
215 + var url="https://www.genie.co.kr/search/searchLyrics?query="+text;
216 + request(url, function(error, response, html)
217 + {
218 + console.log(url);
219 + var $ = cheerio.load(html);
220 + const $bodyList= $('#body-content > div.search_lyrics > div.music-list-wrap.type-lyrics > table > tbody > tr');
221 +
222 + var songs=[];
223 + $bodyList.each(function(i, elem){
224 + if(i<20){
225 + songs.push({
226 + singer: $(this).find("td.info").find("a.artist.ellipsis").text().trim(),
227 + song: $(this).find("td.info").find("a.title.ellipsis").text().trim(),
228 + });
229 +
230 + }
231 + })
232 + console.log(songs);
233 + var resultm='';
234 + for(var i=0;i<songs.length;i++){
235 + if(songs[i].singer!=''){
236 + resultm+=songs[i].singer+", "+songs[i].song+"\n";
237 + console.log(resultm);
238 + }
239 + }
240 + console.log(resultm);
241 + var result = { type: 'text', text: resultm};
242 + console.log(result);
243 + client.replyMessage(event.replyToken,result).then(resolve).catch(reject);
244 +
245 + });
246 + });
247 + });
248 + }
249 + else{
91 return new Promise(function(resolve, reject) { 250 return new Promise(function(resolve, reject) {
92 //언어 감지 option 251 //언어 감지 option
93 var detect_options = { 252 var detect_options = {
...@@ -142,19 +301,15 @@ function handleEvent(event) { ...@@ -142,19 +301,15 @@ function handleEvent(event) {
142 result.text = '언어를 감지할 수 없습니다. \n 번역 언어는 한글 또는 영어만 가능합니다.'; 301 result.text = '언어를 감지할 수 없습니다. \n 번역 언어는 한글 또는 영어만 가능합니다.';
143 client.replyMessage(event.replyToken,result).then(resolve).catch(reject); 302 client.replyMessage(event.replyToken,result).then(resolve).catch(reject);
144 } 303 }
145 -
146 } 304 }
147 else{ 305 else{
148 console.log("status code is not 200"); 306 console.log("status code is not 200");
149 } 307 }
150 -
151 -
152 -
153 }); 308 });
154 -
155 }); 309 });
156 } 310 }
157 } 311 }
312 +
158 app.get('/',(req,res)=>{ 313 app.get('/',(req,res)=>{
159 - res.send("hellow"); 314 + res.send("hello");
160 }) 315 })
...\ No newline at end of file ...\ No newline at end of file
......