권은령

Update display music list

1 -var createServer = require("auto-sni");
2 var express = require("express"); 1 var express = require("express");
3 var app = express(); 2 var app = express();
3 +var cheerio = require('cheerio');
4 const line = require('@line/bot-sdk'); 4 const line = require('@line/bot-sdk');
5 var request = require('request'); 5 var request = require('request');
6 var https=require('https'); 6 var https=require('https');
7 var http=require('http'); 7 var http=require('http');
8 -const lex = require('greenlock-express').create({ 8 +
9 +
10 +var fs = require("fs");
11 +
12 +var httpsOptions = {
13 + hostname: 'oss.chatbot.bu.to',
14 + ca: fs.readFileSync('/etc/letsencrypt/live/oss.chatbot.bu.to/fullchain.pem'),
15 + key: fs.readFileSync('/etc/letsencrypt/live/oss.chatbot.bu.to/privkey.pem'),
16 + cert: fs.readFileSync('/etc/letsencrypt/live/oss.chatbot.bu.to/cert.pem')
17 +};
18 +
19 +http.createServer(app).listen(80);
20 +https.createServer(httpsOptions, app).listen(443);
21 +
22 +/*
23 +const lex= require('greenlock-express').create({
9 version: 'draft-11', // 버전2 24 version: 'draft-11', // 버전2
10 store: require('greenlock-store-fs'), 25 store: require('greenlock-store-fs'),
11 configDir: '/etc/letsencrypt', // 또는 ~/letsencrypt/etc 26 configDir: '/etc/letsencrypt', // 또는 ~/letsencrypt/etc
12 approveDomains: (opts, certs, cb) => { 27 approveDomains: (opts, certs, cb) => {
13 if (certs) { 28 if (certs) {
14 - opts.domains = ['oss.chatbot.bu.to', 'oss.chatbot.bu.to']; 29 + opts.domains = ['oss.chatbot.bu.to', 'www.oss.chatbot.bu.to'];
15 } else { 30 } else {
16 opts.email = 'sweun1@naver.com'; 31 opts.email = 'sweun1@naver.com';
17 opts.agreeTos = true; 32 opts.agreeTos = true;
18 } 33 }
19 cb(null, { options: opts, certs }); 34 cb(null, { options: opts, certs });
35 +
20 }, 36 },
21 renewWithin: 81 * 24 * 60 * 60 * 1000, 37 renewWithin: 81 * 24 * 60 * 60 * 1000,
22 renewBy: 80 * 24 * 60 * 60 * 1000, 38 renewBy: 80 * 24 * 60 * 60 * 1000,
23 -});//papago api 39 +});
24 -
25 -
26 https.createServer(lex.httpsOptions, lex.middleware(app)).listen((process.env.SSL_PORT || 443),()=>{ 40 https.createServer(lex.httpsOptions, lex.middleware(app)).listen((process.env.SSL_PORT || 443),()=>{
27 console.log("server on 443"); 41 console.log("server on 443");
28 }); 42 });
29 http.createServer(lex.middleware(require('redirect-https')())).listen(process.env.PORT || 80,()=>{ 43 http.createServer(lex.middleware(require('redirect-https')())).listen(process.env.PORT || 80,()=>{
30 console.log("server on 80"); 44 console.log("server on 80");
31 }); 45 });
46 +*/
47 +//papago api
48 +
49 +
32 //번역 api_url 50 //번역 api_url
33 var translate_api_url = 'https://openapi.naver.com/v1/papago/n2mt'; 51 var translate_api_url = 'https://openapi.naver.com/v1/papago/n2mt';
34 52
...@@ -45,7 +63,6 @@ const config = { ...@@ -45,7 +63,6 @@ const config = {
45 channelSecret: '75a2fd95ec26d716cac6fcdd520b9b9c' 63 channelSecret: '75a2fd95ec26d716cac6fcdd520b9b9c'
46 64
47 }; 65 };
48 -
49 // create LINE SDK client 66 // create LINE SDK client
50 const client = new line.Client(config); 67 const client = new line.Client(config);
51 // create Express app 68 // create Express app
...@@ -54,83 +71,162 @@ const client = new line.Client(config); ...@@ -54,83 +71,162 @@ const client = new line.Client(config);
54 // register a webhook handler with middleware 71 // register a webhook handler with middleware
55 // about the middleware, please refer to doc 72 // about the middleware, please refer to doc
56 73
74 +// Creates a client
75 +/* google-api
76 +var vision = require('google-vision-api-client');
77 +
78 +var requtil = vision.requtil;
79 +
80 +
81 +
82 +//Prepare your service account from trust preview certificated project
83 +
84 +var jsonfile = '/home/ubuntu/a/LINEBOT/googlevisionapikey.json';
85 +
86 +
87 +//Initialize the api
88 +
89 +vision.init(jsonfile);
90 +
91 +//Build the request payloads
92 +var d = requtil.createRequests().addRequest(
93 +requtil.createRequest('/home/ubuntu/a/LINEBOT/photo/Fancy-TWICE.jpg')
94 +.withFeature('TEXT_DETECTION', 3)
95 +.build());
96 +//Do query to the api server
97 +vision.query(d, function(e, r, d){
98 +if(e) console.log('ERROR:', e);
99 + console.log(JSON.stringify(d));
100 +});
101 +
102 +*/
103 +
57 104
58 app.post('/webhook', line.middleware(config), (req, res) => { 105 app.post('/webhook', line.middleware(config), (req, res) => {
59 -console.log(res.statusCode);
60 Promise 106 Promise
61 .all(req.body.events.map(handleEvent)) 107 .all(req.body.events.map(handleEvent))
62 .then((result) => res.json(result)) 108 .then((result) => res.json(result))
63 .catch((err)=>{console.log(err); 109 .catch((err)=>{console.log(err);
64 - console.log(err.originalError.response)
65 }) 110 })
66 }); 111 });
67 // event handler 112 // event handler
68 -function handleEvent(event) { 113 +function handleEvent(event)
114 +{
69 console.log(event.message); 115 console.log(event.message);
70 - if (event.type !== 'message' || event.message.type !== 'text') { 116 + if (event.type !== 'message' || event.message.type !== 'text')
117 + {
71 // ignore non-text-message event 118 // ignore non-text-message event
72 return Promise.resolve(null); 119 return Promise.resolve(null);
73 } 120 }
74 - return new Promise(function(resolve, reject) { 121 + else if(event.message.text.substring(0, 5)=='순위 보기')
75 - //언어 감지 option 122 + {
76 - var detect_options = { 123 + // music list 출력
77 - url : languagedetect_api_url, 124 + return new Promise(function(resolve, reject){
78 - form : {'query': event.message.text}, 125 + var url="https://www.genie.co.kr/chart/top200";
79 - headers: {'X-Naver-Client-Id': client_id, 'X-Naver-Client-Secret': client_secret} 126 +
80 - }; 127 + request(url, function(error, response, html){
81 - //papago 언어 감지 128 + var $ = cheerio.load(html);
82 - request.post(detect_options,async (error,response,body)=>{ 129 + var songList=[];
83 - console.log(response.statusCode); 130 + const $bodyList= $('#body-content > div.newest-list > div > table > tbody > tr');
84 - if(!error && response.statusCode == 200){ 131 +
85 - var detect_body = JSON.parse(response.body); 132 + $bodyList.each(function(i, elem)
86 - var source = ''; 133 + {
87 - var target = ''; 134 + if(i<20)
88 - var result = { type: 'text', text:''}; 135 + {
89 - 136 + songList.push(
90 - //언어 감지가 제대로 됐는지 확인 137 + {
91 - console.log(detect_body.langCode); 138 + singer: $(this).find("td.info").find("a.artist.ellipsis").text().trim(),
92 - 139 + song: $(this).find("td.info").find("a.title.ellipsis").text().trim(),
93 - 140 + url: 'https://www.genie.co.kr/detail/songInfo?xgnm='+$(this).attr("songid")
94 - //번역은 한국어->영어 / 영어->한국어만 지원 141 + });
95 - if(detect_body.langCode == 'ko'||detect_body.langCode == 'en'){ 142 + }
96 - source = detect_body.langCode == 'ko' ? 'ko':'en'; 143 + else
97 - target = source == 'ko' ? 'en':'ko'; 144 + {
98 - //papago 번역 option 145 + return;
99 - var options = { 146 + }
100 - url: translate_api_url, 147 + });
101 - // 한국어(source : ko), 영어(target: en), 카톡에서 받는 메시지(text) 148 +
102 - form: {'source':source, 'target':target, 'text':event.message.text}, 149 + var result='';
103 - headers: {'X-Naver-Client-Id': client_id, 'X-Naver-Client-Secret': client_secret,"Content-Type": "application/x-www-form-urlencoded"} 150 + for(var i=0; i<songList.length; i++)
104 - }; 151 + {
105 - 152 + result+=i+1 + ". "+ songList[i].singer+" - "+songList[i].song+"\n";
106 - // Naver Post API
107 - await request.post(options, function(error, response, body){
108 - // Translate API Sucess
109 - if(!error && response.statusCode == 200){
110 - // JSON
111 - var objBody = JSON.parse(response.body);
112 - // Message 잘 찍히는지 확인
113 -
114 - result.text = objBody.message.result.translatedText;
115 - console.log(result);
116 - //번역된 문장 보내기
117 - client.replyMessage(event.replyToken,result).then(resolve);
118 - }
119 - });
120 - }
121 - // 메시지의 언어가 영어 또는 한국어가 아닐 경우
122 - else{
123 - result.text = '언어를 감지할 수 없습니다. \n 번역 언어는 한글 또는 영어만 가능합니다.';
124 - client.replyMessage(event.replyToken,result).then(resolve);
125 } 153 }
126 - 154 + console.log(result);
127 - } 155 + });
128 - else{ 156 + client.replyMessage(event.replyToken, result).then(resolve).catch(reject);
129 - console.log("status code is not 200");
130 - }
131 -
132 }); 157 });
133 - 158 + }
159 + else
160 + {
161 + return new Promise(function(resolve, reject)
162 + {
163 + //언어 감지 option
164 + var detect_options =
165 + {
166 + url : languagedetect_api_url,
167 + form : {'query': event.message.text},
168 + headers: {'X-Naver-Client-Id': client_id, 'X-Naver-Client-Secret': client_secret}
169 + };
170 +
171 + //papago 언어 감지
172 + request.post(detect_options, (error,response,body)=>
173 + {
174 + if(!error && response.statusCode == 200)
175 + {
176 + var detect_body = JSON.parse(response.body);
177 + var source = '';
178 + var target = '';
179 + var result = { type: 'text', text:''};
180 +
181 + //언어 감지가 제대로 됐는지 확인
182 + console.log(detect_body.langCode);
183 +
184 + //번역은 한국어->영어 / 영어->한국어만 지원
185 + if(detect_body.langCode == 'ko'||detect_body.langCode == 'en')
186 + {
187 + source = detect_body.langCode == 'ko' ? 'ko':'en';
188 + target = source == 'ko' ? 'en':'ko';
189 + //papago 번역 option
190 + var options = {
191 + url: translate_api_url,
192 + // 한국어(source : ko), 영어(target: en), 카톡에서 받는 메시지(text)
193 + form: {'source':source, 'target':target, 'text':event.message.text},
194 + headers: {'X-Naver-Client-Id': client_id, 'X-Naver-Client-Secret': client_secret}
195 + };
196 +
197 + // Naver Post API
198 + console.log("?!");
199 + request.post(options, function(error, response, body){
200 + // Translate API Sucess
201 + if(!error && response.statusCode == 200){
202 + // JSON
203 + var objBody = JSON.parse(response.body);
204 + // Message 잘 찍히는지 확인
205 +
206 + result.text = objBody.message.result.translatedText;
207 + console.log("result: "+result.text);
208 + //번역된 문장 보내기
209 + client.replyMessage(event.replyToken,result).then(resolve).catch(reject);
210 + }
211 + });
212 + console.log("?!")
213 + }
214 + // 메시지의 언어가 영어 또는 한국어가 아닐 경우
215 + else
216 + {
217 + result.text = '언어를 감지할 수 없습니다. \n 번역 언어는 한글 또는 영어만 가능합니다.';
218 + client.replyMessage(event.replyToken, result).then(resolve).catch(reject);
219 + }
220 + }
221 + else
222 + {
223 + console.log("status code is not 200");
224 + }
225 + });
134 }); 226 });
135 } 227 }
228 +}
136 229
230 +app.get('/',(req,res)=>{
231 + res.send("hello");
232 +})
......
1 +-----BEGIN RSA PRIVATE KEY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LNghhLCiD3hScjErXrQgY98O+3UkBhcAEYU3Nigsp9s+uJWYsirU0X
16 +AoGARj+m5pMOUe4xtOioF1LZ9uilk7VAsFAxX+XuDjHYFIaj8X1gPI87E+8uAunlUwr+Pw9gLG2a
17 +II1aiGfBOapmZGh2YMShccJFYrHYej2yJACEwqARozg5F2BXAfL4+DHyxc0gUnpZ8EXyTg49XjFA
18 +ct1a4jm9Nd6OeNGJ2nyo7JUCgYBDuXSUeCMe7RmIJQ6C0z8DJXfKMGDjFV3/ZMWkrGCoAhvlP4P1
19 +0LdQnGg51SEbDp+/3D9yVSJ0ASzYy0emY0aH7xBf/Mg/S43piU/4BZaEoPUV/c1RNKn5MC8oKBnk
20 +MXVUuqH9Zw374SgOLGZI60wxV0zm+uOosoyU4B6jvx766QKBgGDpM+P1QaAaQob2sUYE42UsDPRE
21 +agfuysocl+QQOmLgLckGcS7MqVOR4PAJzZQxIUnZDaKT/wVab/o9T+X3JhdB5vewFol5elQ9tcho
22 +rlseuY+Nq2D/HAhgCIHtGsnbu8icl88aE0GPN0KU38egZdAlAhAVJGsVPvI2ci6MHs1+
23 +-----END RSA PRIVATE KEY-----
...\ No newline at end of file ...\ No newline at end of file
...@@ -30,12 +30,14 @@ request(url, function(error, response, html) ...@@ -30,12 +30,14 @@ request(url, function(error, response, html)
30 return; 30 return;
31 } 31 }
32 }) 32 })
33 - 33 + var result='';
34 for(var i=0; i<songList.length; i++) 34 for(var i=0; i<songList.length; i++)
35 { 35 {
36 - console.log(songList[i]); 36 + result+=i+1 + ". "+ songList[i].singer+" - "+songList[i].song+"\n";
37 + //console.log(i+1 + ". "+ songList[i].singer+" - "+songList[i].song);
37 } 38 }
38 39
40 + console.log(result);
39 var randnum=function getRandomInt(min, max) 41 var randnum=function getRandomInt(min, max)
40 { 42 {
41 min = Math.ceil(min); 43 min = Math.ceil(min);
......