나혜원

ud

Showing 1 changed file with 220 additions and 0 deletions
1 +var createServer = require("auto-sni");
2 +var express = require("express");
3 +var app = express();
4 +const line = require('@line/bot-sdk');
5 +var request = require('request');
6 +var https=require('https');
7 +var http=require('http');
8 +
9 +const lex = require('greenlock-express').create({
10 + version: 'draft-11', // 버전2
11 + store: require('greenlock-store-fs'),
12 + configDir: '/etc/letsencrypt', // 또는 ~/letsencrypt/etc
13 + approveDomains: (opts, certs, cb) => {
14 + if (certs) {
15 + opts.domains = ['oss.chatbot.bu.to', 'oss.chatbot.bu.to'];
16 + } else {
17 + opts.email = 'sweun1@naver.com';
18 + opts.agreeTos = true;
19 + }
20 + cb(null, { options: opts, certs });
21 + },
22 + renewWithin: 81 * 24 * 60 * 60 * 1000,
23 + renewBy: 80 * 24 * 60 * 60 * 1000,
24 +});//papago api
25 +
26 +
27 +https.createServer(lex.httpsOptions, lex.middleware(app)).listen((process.env.SSL_PORT || 443),()=>{
28 + console.log("server on 443");
29 +});
30 +http.createServer(lex.middleware(require('redirect-https')())).listen(process.env.PORT || 80,()=>{
31 + console.log("server on 80");
32 +});
33 +
34 +//번역 api_url
35 +var translate_api_url = 'https://openapi.naver.com/v1/papago/n2mt';
36 +
37 +//언어감지 api_url
38 +var languagedetect_api_url = 'https://openapi.naver.com/v1/papago/detectLangs'
39 +
40 +// Naver Auth Key
41 +//새로 발급받은 naver papago api id, pw 입력
42 +var client_id = 'bIYcswH22VlQqT8OkkLm';
43 +var client_secret = 'qLaERoks0u';
44 +
45 +const config = {
46 + channelAccessToken: 'dWno95uZ/FLPM5BoTUIM1kPenQ+UsEHYSWphPWcOxyjS7eylg6jhocxvJCeV8YumuVvYf+3bE/696ZSkOPJitxhXbXDe+1p2WoyCbHzD8KxxF1EKo6zvHfnhsIA8kZS93lNzUTQr1FVWaMmRKl7NzwdB04t89/1O/w1cDnyilFU=',
47 + channelSecret: '75a2fd95ec26d716cac6fcdd520b9b9c'
48 +
49 +};
50 +
51 +// create LINE SDK client
52 +const client = new line.Client(config);
53 +// create Express app
54 +// about Express itself: https://expressjs.com/
55 +
56 +// register a webhook handler with middleware
57 +// about the middleware, please refer to doc
58 +
59 +var cheerio = require('cheerio');
60 +var data = require('./event.json');
61 +//json 불러오기
62 +
63 +var data_list = data["DATA"]
64 +var concert_list = [];
65 +
66 +for(var i = 0; i < data_list.length; i++){
67 + if (data_list[i].codename=="콘서트"){
68 + concert_list.push(data_list[i].title);
69 + }
70 + }
71 +
72 +for(var i = 0; i < concert_list.length; i++){
73 + console.log(i+1,'. ',concert_list[i],'\n');
74 + }
75 +//콘서트 목록 만들기
76 +
77 +app.post('/webhook', line.middleware(config), (req, res) => {
78 +console.log(res.statusCode);
79 + Promise
80 + .all(req.body.events.map(handleEvent))
81 + .then((result) => res.json(result))
82 + .catch((err)=>{console.log(err);
83 + })
84 +});
85 +
86 +// event handler
87 +function handleEvent(event) {
88 + console.log(event.message);
89 + if (event.type !== 'message' || event.message.type !== 'text') {
90 + // ignore non-text-message event
91 + return Promise.resolve(null);
92 + }
93 + else if(event.message.text.substring(0,6)=='콘서트 보기'){
94 +
95 + return new Promise(function(resolve, reject)
96 + {
97 + var showlist = { type: 'text', text:''};
98 + for(var i = 0; i < concert_list.length; i++)
99 + {
100 + showlist.text+=i+1 + ". " + concert_list[i] + "\n";
101 + }
102 + console.log(showlist.text);
103 + var result={type:'text',text:showlist.text}
104 +
105 + client.replyMessage(event.replyToken, result).then(resolve).catch(reject);
106 + });
107 +
108 + }
109 + else if(isNaN(event.message.text)){
110 +
111 + var selectnum = (event.message.text*1);
112 +
113 + if(selectnum >=0 || selectnum <=27){
114 + result.text = '목록에 존재하지 않는 콘서트입니다.';
115 + client.replyMessage(event.replyToken, result).then(resolve).catch(reject);
116 + }
117 +
118 + return new Promise(function(resolve, reject){
119 + var concert_name = concert_list[selectnum-1];
120 + var $ = cheerio.load(concert_name);
121 + var keyword = $.text();
122 + console.log(keyword);
123 +
124 + var options = {method: 'GET',
125 + url: 'https://www.googleapis.com/youtube/v3/search',
126 + qs: { key: 'AIzaSyB4b-n8SSv73CLDKvFigpLPYA6yWG2JQ9A',
127 + part: 'id',
128 + maxResults: '1',
129 + order: 'relevance',
130 + q: keyword,
131 + type: 'video'}
132 + };
133 +
134 + var videourl = { type: 'url', label: '관련 영상', url:''};
135 +
136 + request(options, function(error,result,body){
137 + if(error) throw new Error(error);
138 +
139 + var temp = body.split(':');
140 + videourl.url += "https://www.youtube.com/watch?v=" + temp1[13].substr(2,11);
141 + });
142 +
143 + console.log(videourl.url);
144 +
145 + client.replyMessage(event.replyToken, videourl).then(resolve).catch(reject);
146 + })};
147 +
148 + app.post('/webhook', line.middleware(config), (req, res) => {
149 + console.log(res.statusCode);
150 + Promise
151 + .all(req.body.events.map(handleEvent2))
152 + .then((result) => res.json(result))
153 + .catch((err)=>{console.log(err);
154 + })
155 + });
156 +
157 + return new Promise(function(resolve, reject) {
158 + //언어 감지 option
159 + var detect_options = {
160 + url : languagedetect_api_url,
161 + form : {'query': event.message.text},
162 + headers: {'X-Naver-Client-Id': client_id, 'X-Naver-Client-Secret': client_secret}
163 + };
164 + //papago 언어 감지
165 +
166 + request.post(detect_options,async (error,response,body)=>{
167 + console.log(response.statusCode);
168 + if(!error && response.statusCode == 200){
169 + var detect_body = JSON.parse(response.body);
170 + var source = '';
171 + var target = '';
172 + var result = { type: 'text', text:''};
173 +
174 + //언어 감지가 제대로 됐는지 확인
175 + console.log(detect_body.langCode);
176 +
177 +
178 + //번역은 한국어->영어 / 영어->한국어만 지원
179 + if(detect_body.langCode == 'ko'||detect_body.langCode == 'en'){
180 + source = detect_body.langCode == 'ko' ? 'ko':'en';
181 + target = source == 'ko' ? 'en':'ko';
182 + //papago 번역 option
183 + var options = {
184 + url: translate_api_url,
185 + // 한국어(source : ko), 영어(target: en), 카톡에서 받는 메시지(text)
186 + form: {'source':source, 'target':target, 'text':event.message.text},
187 + headers: {'X-Naver-Client-Id': client_id, 'X-Naver-Client-Secret': client_secret,"Content-Type": "application/x-www-form-urlencoded"}
188 + };
189 +
190 + // Naver Post API
191 + await request.post(options, function(error, response, body){
192 + // Translate API Sucess
193 + if(!error && response.statusCode == 200){
194 + // JSON
195 + var objBody = JSON.parse(response.body);
196 + // Message 잘 찍히는지 확인
197 +
198 + result.text = objBody.message.result.translatedText;
199 + console.log(result);
200 + //번역된 문장 보내기
201 + client.replyMessage(event.replyToken,result).then(resolve);
202 + }
203 + });
204 + }
205 + // 메시지의 언어가 영어 또는 한국어가 아닐 경우
206 + else{
207 + result.text = '언어를 감지할 수 없습니다. \n 번역 언어는 한글 또는 영어만 가능합니다.';
208 + client.replyMessage(event.replyToken,result).then(resolve);
209 + }
210 +
211 + }
212 + else{
213 + console.log("status code is not 200");
214 + }
215 +
216 + });
217 +
218 + });
219 + }
220 +