권은령

Update display music list

var createServer = require("auto-sni");
var express = require("express");
var app = express();
var cheerio = require('cheerio');
const line = require('@line/bot-sdk');
var request = require('request');
var https=require('https');
var http=require('http');
const lex = require('greenlock-express').create({
var fs = require("fs");
var httpsOptions = {
hostname: 'oss.chatbot.bu.to',
ca: fs.readFileSync('/etc/letsencrypt/live/oss.chatbot.bu.to/fullchain.pem'),
key: fs.readFileSync('/etc/letsencrypt/live/oss.chatbot.bu.to/privkey.pem'),
cert: fs.readFileSync('/etc/letsencrypt/live/oss.chatbot.bu.to/cert.pem')
};
http.createServer(app).listen(80);
https.createServer(httpsOptions, app).listen(443);
/*
const lex= require('greenlock-express').create({
version: 'draft-11', // 버전2
store: require('greenlock-store-fs'),
configDir: '/etc/letsencrypt', // 또는 ~/letsencrypt/etc
approveDomains: (opts, certs, cb) => {
if (certs) {
opts.domains = ['oss.chatbot.bu.to', 'oss.chatbot.bu.to'];
opts.domains = ['oss.chatbot.bu.to', 'www.oss.chatbot.bu.to'];
} else {
opts.email = 'sweun1@naver.com';
opts.agreeTos = true;
}
cb(null, { options: opts, certs });
},
renewWithin: 81 * 24 * 60 * 60 * 1000,
renewBy: 80 * 24 * 60 * 60 * 1000,
});//papago api
});
https.createServer(lex.httpsOptions, lex.middleware(app)).listen((process.env.SSL_PORT || 443),()=>{
console.log("server on 443");
});
http.createServer(lex.middleware(require('redirect-https')())).listen(process.env.PORT || 80,()=>{
console.log("server on 80");
});
*/
//papago api
//번역 api_url
var translate_api_url = 'https://openapi.naver.com/v1/papago/n2mt';
......@@ -45,7 +63,6 @@ const config = {
channelSecret: '75a2fd95ec26d716cac6fcdd520b9b9c'
};
// create LINE SDK client
const client = new line.Client(config);
// create Express app
......@@ -54,83 +71,162 @@ const client = new line.Client(config);
// register a webhook handler with middleware
// about the middleware, please refer to doc
// Creates a client
/* google-api
var vision = require('google-vision-api-client');
var requtil = vision.requtil;
//Prepare your service account from trust preview certificated project
var jsonfile = '/home/ubuntu/a/LINEBOT/googlevisionapikey.json';
//Initialize the api
vision.init(jsonfile);
//Build the request payloads
var d = requtil.createRequests().addRequest(
requtil.createRequest('/home/ubuntu/a/LINEBOT/photo/Fancy-TWICE.jpg')
.withFeature('TEXT_DETECTION', 3)
.build());
//Do query to the api server
vision.query(d, function(e, r, d){
if(e) console.log('ERROR:', e);
console.log(JSON.stringify(d));
});
*/
app.post('/webhook', line.middleware(config), (req, res) => {
console.log(res.statusCode);
Promise
.all(req.body.events.map(handleEvent))
.then((result) => res.json(result))
.catch((err)=>{console.log(err);
console.log(err.originalError.response)
})
});
// event handler
function handleEvent(event) {
function handleEvent(event)
{
console.log(event.message);
if (event.type !== 'message' || event.message.type !== 'text') {
if (event.type !== 'message' || event.message.type !== 'text')
{
// ignore non-text-message event
return Promise.resolve(null);
}
return new Promise(function(resolve, reject) {
//언어 감지 option
var detect_options = {
url : languagedetect_api_url,
form : {'query': event.message.text},
headers: {'X-Naver-Client-Id': client_id, 'X-Naver-Client-Secret': client_secret}
};
//papago 언어 감지
request.post(detect_options,async (error,response,body)=>{
console.log(response.statusCode);
if(!error && response.statusCode == 200){
var detect_body = JSON.parse(response.body);
var source = '';
var target = '';
var result = { type: 'text', text:''};
//언어 감지가 제대로 됐는지 확인
console.log(detect_body.langCode);
//번역은 한국어->영어 / 영어->한국어만 지원
if(detect_body.langCode == 'ko'||detect_body.langCode == 'en'){
source = detect_body.langCode == 'ko' ? 'ko':'en';
target = source == 'ko' ? 'en':'ko';
//papago 번역 option
var options = {
url: translate_api_url,
// 한국어(source : ko), 영어(target: en), 카톡에서 받는 메시지(text)
form: {'source':source, 'target':target, 'text':event.message.text},
headers: {'X-Naver-Client-Id': client_id, 'X-Naver-Client-Secret': client_secret,"Content-Type": "application/x-www-form-urlencoded"}
};
// Naver Post API
await request.post(options, function(error, response, body){
// Translate API Sucess
if(!error && response.statusCode == 200){
// JSON
var objBody = JSON.parse(response.body);
// Message 잘 찍히는지 확인
result.text = objBody.message.result.translatedText;
console.log(result);
//번역된 문장 보내기
client.replyMessage(event.replyToken,result).then(resolve);
}
});
}
// 메시지의 언어가 영어 또는 한국어가 아닐 경우
else{
result.text = '언어를 감지할 수 없습니다. \n 번역 언어는 한글 또는 영어만 가능합니다.';
client.replyMessage(event.replyToken,result).then(resolve);
else if(event.message.text.substring(0, 5)=='순위 보기')
{
// music list 출력
return new Promise(function(resolve, reject){
var url="https://www.genie.co.kr/chart/top200";
request(url, function(error, response, html){
var $ = cheerio.load(html);
var songList=[];
const $bodyList= $('#body-content > div.newest-list > div > table > tbody > tr');
$bodyList.each(function(i, elem)
{
if(i<20)
{
songList.push(
{
singer: $(this).find("td.info").find("a.artist.ellipsis").text().trim(),
song: $(this).find("td.info").find("a.title.ellipsis").text().trim(),
url: 'https://www.genie.co.kr/detail/songInfo?xgnm='+$(this).attr("songid")
});
}
else
{
return;
}
});
var result='';
for(var i=0; i<songList.length; i++)
{
result+=i+1 + ". "+ songList[i].singer+" - "+songList[i].song+"\n";
}
}
else{
console.log("status code is not 200");
}
console.log(result);
});
client.replyMessage(event.replyToken, result).then(resolve).catch(reject);
});
}
else
{
return new Promise(function(resolve, reject)
{
//언어 감지 option
var detect_options =
{
url : languagedetect_api_url,
form : {'query': event.message.text},
headers: {'X-Naver-Client-Id': client_id, 'X-Naver-Client-Secret': client_secret}
};
//papago 언어 감지
request.post(detect_options, (error,response,body)=>
{
if(!error && response.statusCode == 200)
{
var detect_body = JSON.parse(response.body);
var source = '';
var target = '';
var result = { type: 'text', text:''};
//언어 감지가 제대로 됐는지 확인
console.log(detect_body.langCode);
//번역은 한국어->영어 / 영어->한국어만 지원
if(detect_body.langCode == 'ko'||detect_body.langCode == 'en')
{
source = detect_body.langCode == 'ko' ? 'ko':'en';
target = source == 'ko' ? 'en':'ko';
//papago 번역 option
var options = {
url: translate_api_url,
// 한국어(source : ko), 영어(target: en), 카톡에서 받는 메시지(text)
form: {'source':source, 'target':target, 'text':event.message.text},
headers: {'X-Naver-Client-Id': client_id, 'X-Naver-Client-Secret': client_secret}
};
// Naver Post API
console.log("?!");
request.post(options, function(error, response, body){
// Translate API Sucess
if(!error && response.statusCode == 200){
// JSON
var objBody = JSON.parse(response.body);
// Message 잘 찍히는지 확인
result.text = objBody.message.result.translatedText;
console.log("result: "+result.text);
//번역된 문장 보내기
client.replyMessage(event.replyToken,result).then(resolve).catch(reject);
}
});
console.log("?!")
}
// 메시지의 언어가 영어 또는 한국어가 아닐 경우
else
{
result.text = '언어를 감지할 수 없습니다. \n 번역 언어는 한글 또는 영어만 가능합니다.';
client.replyMessage(event.replyToken, result).then(resolve).catch(reject);
}
}
else
{
console.log("status code is not 200");
}
});
});
}
}
app.get('/',(req,res)=>{
res.send("hello");
})
......
-----BEGIN RSA PRIVATE KEY-----
MIIEowIBAAKCAQEArYTK96Vagqd1gQS6LOKELZL0TrnRXAOZiGVjcEo/bAdZzW6XnKPkdQuMqmy7
BgpmkimASdDnAINkfYPcrrx1Tb/943uOGlqDr7wtz9v8OZr5yihrCqseopd9vG2fyQ2uTXfUzbv0
EboOyHcSBhougFXhlj42/dWsIeUu+UxMqRMffDuDr97FG5zDjYhaatLaaez5rIiPtOWp8LHH8gNj
EbZF5S5jWOaFH1AWB4UeHheZMvPcN9O7BqBUFFJwIHtns6/ehRbGRDAfzH5pbo3J8Z+0PHWqYhUJ
ELOCVLMqCVO+/c3ZpwfwZQKSGejBcoa9B35by7mVLY6yIMn7jt+jYwIDAQABAoIBAQCWLKe9TU7Y
ZTY9Q2oeDq13BAiNWiToDfWDJry5IolhZbtDIMP2vaGr6yMDHLeAst+zAFgXisVinFUMjGMil9iu
QcvqZbTG+i+emK7Nhwb0lDw7yl9aDF+nOJWJzxbLWxvP0DZNGK5T6UOCHAttXJuCVtG2xoGxjow7
ia7t9Csk6AloBYpfko+9vUgkeZ6OGDXVtpSwhEpmTUb+Sx4g01JiKcgq5lZeEaLqUSYG+3AuNv/I
IKYbSuWuyW5rPO1Fr0TyIli8BqyTxmSZc6uWocyqqyCFp7o44lIkmuzY1GFbre1MqQFQgqoNnsRW
7RknHA2RnSo6shq3oBg9w0uxXl+BAoGBAOjKNI6Ret4Nvf+J6KyPY1g5OGCMryGTeH/8Cdbcky6L
UB04MBMMEoaFU21qzoamqXfE3EIXQVT/qh/LhNcT/+7Li/ujS6OFo52qOFxY2tU6PxRfRg72OyaA
hCpT5CIOMxM4lM2J7V5FpeGxAZkF30CaRGsVY8HCudi6H0y6SYOVAoGBAL7Ru+p66SQlbO3j/GOD
hSe3CleFjxKD0epIV8zHOTxMpRVNGXXnZym7VOcvcj6ZaSgmYaE4+c4d25HaaIgRDCRWYO46HUbg
Z2yv2UYD8jNqEqeWYO4aoCLNghhLCiD3hScjErXrQgY98O+3UkBhcAEYU3Nigsp9s+uJWYsirU0X
AoGARj+m5pMOUe4xtOioF1LZ9uilk7VAsFAxX+XuDjHYFIaj8X1gPI87E+8uAunlUwr+Pw9gLG2a
II1aiGfBOapmZGh2YMShccJFYrHYej2yJACEwqARozg5F2BXAfL4+DHyxc0gUnpZ8EXyTg49XjFA
ct1a4jm9Nd6OeNGJ2nyo7JUCgYBDuXSUeCMe7RmIJQ6C0z8DJXfKMGDjFV3/ZMWkrGCoAhvlP4P1
0LdQnGg51SEbDp+/3D9yVSJ0ASzYy0emY0aH7xBf/Mg/S43piU/4BZaEoPUV/c1RNKn5MC8oKBnk
MXVUuqH9Zw374SgOLGZI60wxV0zm+uOosoyU4B6jvx766QKBgGDpM+P1QaAaQob2sUYE42UsDPRE
agfuysocl+QQOmLgLckGcS7MqVOR4PAJzZQxIUnZDaKT/wVab/o9T+X3JhdB5vewFol5elQ9tcho
rlseuY+Nq2D/HAhgCIHtGsnbu8icl88aE0GPN0KU38egZdAlAhAVJGsVPvI2ci6MHs1+
-----END RSA PRIVATE KEY-----
\ No newline at end of file
......@@ -30,12 +30,14 @@ request(url, function(error, response, html)
return;
}
})
var result='';
for(var i=0; i<songList.length; i++)
{
console.log(songList[i]);
result+=i+1 + ". "+ songList[i].singer+" - "+songList[i].song+"\n";
//console.log(i+1 + ". "+ songList[i].singer+" - "+songList[i].song);
}
console.log(result);
var randnum=function getRandomInt(min, max)
{
min = Math.ceil(min);
......