신지원

Connect chatbot with playlists and songs that user want

1 -node_modules/
2 -.vscode/
...\ No newline at end of file ...\ No newline at end of file
1 + *.json
2 + node_modules/
3 + vscode/
4 + Info.js
......
1 -const { google } = require("googleapis");
2 -var service = google.youtube('v3');
3 -
4 -service.playlistItems.list({
5 - key: 'AIzaSyBInggOtXxPFYIRee0Xs3vb5iZ9YE9_518',
6 - part: 'snippet',
7 - fields: 'items(snippet(title,resourceId,thumbnails(high(url))))', //제목, VideoId, Thumbnail 이미지 정보.
8 - maxResults: 10,
9 - playlistId: 'PLfVO1GXBPp3s03voaFAWN7AkzEnpsGF1U'
10 -}, function (err, response) {
11 - if (err) {
12 - console.log('The API returned an error: ', err);
13 - return;
14 - }
15 -
16 - var video = response.data.items;
17 - if (video.length == 0) {
18 - console.log('검색된 동영상이 없습니다.');
19 - } else {
20 - for (var i = 0; i < 10; i++) {
21 - console.log('{');
22 - console.log(JSON.stringify(response.data.items[i].snippet.title).replace(/\"/gi, ""));
23 - var a = JSON.stringify(response.data.items[i].snippet.resourceId.videoId);
24 - console.log('https://www.youtube.com/watch?v=' + a.replace(/\"/gi, "")); //JSON stringify 큰따옴표 제거후 URL로 전환
25 - console.log(JSON.stringify(response.data.items[i].snippet.thumbnails.high.url).replace(/\"/gi, ""));
26 - console.log('}');
27 - }
28 - }
29 -})
1 -const { google } = require("googleapis");
2 -var service = google.youtube('v3');
3 -
4 -service.playlistItems.list({
5 - key: 'AIzaSyBInggOtXxPFYIRee0Xs3vb5iZ9YE9_518',
6 - part: 'snippet',
7 - fields: 'items(snippet(title,resourceId,thumbnails(high(url))))', //제목, VideoId, Thumbnail 이미지 정보.
8 - maxResults: 10,
9 - playlistId: 'PLfVO1GXBPp3t4Wp8l-cR9s8wpWI2Fnz4g'
10 -}, function (err, response) {
11 - if (err) {
12 - console.log('The API returned an error: ', err);
13 - return;
14 - }
15 -
16 - var video = response.data.items;
17 - if (video.length == 0) {
18 - console.log('검색된 동영상이 없습니다.');
19 - } else {
20 - for (var i = 0; i < 10; i++) {
21 - console.log('{');
22 - console.log(JSON.stringify(response.data.items[i].snippet.title).replace(/\"/gi, ""));
23 - var a = JSON.stringify(response.data.items[i].snippet.resourceId.videoId);
24 - console.log('https://www.youtube.com/watch?v=' + a.replace(/\"/gi, "")); //JSON stringify 큰따옴표 제거후 URL로 전환
25 - console.log(JSON.stringify(response.data.items[i].snippet.thumbnails.high.url).replace(/\"/gi, ""));
26 - console.log('}');
27 - }
28 - }
29 -})
1 -const { google } = require("googleapis");
2 -var service = google.youtube('v3');
3 -
4 -service.playlistItems.list({
5 - key: 'AIzaSyBInggOtXxPFYIRee0Xs3vb5iZ9YE9_518',
6 - part: 'snippet',
7 - fields: 'items(snippet(title,resourceId,thumbnails(high(url))))', //제목, VideoId, Thumbnail 이미지 정보.
8 - maxResults: 10,
9 - playlistId: 'PLfVO1GXBPp3vXaFB2VtbdQ2h6ljGZOSlj'
10 -}, function (err, response) {
11 - if (err) {
12 - console.log('The API returned an error: ', err);
13 - return;
14 - }
15 -
16 - var video = response.data.items;
17 - if (video.length == 0) {
18 - console.log('검색된 동영상이 없습니다.');
19 - } else {
20 - for (var i = 0; i < 10; i++) {
21 - console.log('{');
22 - console.log(JSON.stringify(response.data.items[i].snippet.title).replace(/\"/gi, ""));
23 - var a = JSON.stringify(response.data.items[i].snippet.resourceId.videoId);
24 - console.log('https://www.youtube.com/watch?v=' + a.replace(/\"/gi, "")); //JSON stringify 큰따옴표 제거후 URL로 전환
25 - console.log(JSON.stringify(response.data.items[i].snippet.thumbnails.high.url).replace(/\"/gi, ""));
26 - console.log('}');
27 - }
28 - }
29 -})
1 -const { google } = require("googleapis");
2 -var service = google.youtube('v3');
3 -
4 -service.playlistItems.list({
5 - key: 'AIzaSyBInggOtXxPFYIRee0Xs3vb5iZ9YE9_518',
6 - part: 'snippet',
7 - fields: 'items(snippet(title,resourceId,thumbnails(high(url))))', //제목, VideoId, Thumbnail 이미지 정보.
8 - maxResults: 10,
9 - playlistId: 'PLfVO1GXBPp3tdasvQuIu_BmSNm4GVwnNj'
10 -}, function (err, response) {
11 - if (err) {
12 - console.log('The API returned an error: ', err);
13 - return;
14 - }
15 -
16 - var video = response.data.items;
17 - if (video.length == 0) {
18 - console.log('검색된 동영상이 없습니다.');
19 - } else {
20 - for (var i = 0; i < 10; i++) {
21 - console.log('{');
22 - console.log(JSON.stringify(response.data.items[i].snippet.title).replace(/\"/gi, ""));
23 - var a = JSON.stringify(response.data.items[i].snippet.resourceId.videoId);
24 - console.log('https://www.youtube.com/watch?v=' + a.replace(/\"/gi, "")); //JSON stringify 큰따옴표 제거후 URL로 전환
25 - console.log(JSON.stringify(response.data.items[i].snippet.thumbnails.high.url).replace(/\"/gi, ""));
26 - console.log('}');
27 - }
28 - }
29 -})
1 -const { google } = require("googleapis");
2 -var service = google.youtube('v3');
3 -
4 -service.playlistItems.list({
5 - key: 'AIzaSyBInggOtXxPFYIRee0Xs3vb5iZ9YE9_518',
6 - part: 'snippet',
7 - fields: 'items(snippet(title,resourceId,thumbnails(high(url))))', //제목, VideoId, Thumbnail 이미지 정보.
8 - maxResults: 10,
9 - playlistId: 'PLfVO1GXBPp3vrR3ZcQFlCEC6oNdo_MQ_R'
10 -}, function (err, response) {
11 - if (err) {
12 - console.log('The API returned an error: ', err);
13 - return;
14 - }
15 -
16 - var video = response.data.items;
17 - if (video.length == 0) {
18 - console.log('검색된 동영상이 없습니다.');
19 - } else {
20 - for (var i = 0; i < 10; i++) {
21 - console.log('{');
22 - console.log(JSON.stringify(response.data.items[i].snippet.title).replace(/\"/gi, ""));
23 - var a = JSON.stringify(response.data.items[i].snippet.resourceId.videoId);
24 - console.log('https://www.youtube.com/watch?v=' + a.replace(/\"/gi, "")); //JSON stringify 큰따옴표 제거후 URL로 전환
25 - console.log(JSON.stringify(response.data.items[i].snippet.thumbnails.high.url).replace(/\"/gi, ""));
26 - console.log('}');
27 - }
28 - }
29 -})
1 -const { google } = require("googleapis");
2 -var service = google.youtube('v3');
3 -
4 -service.playlistItems.list({
5 - key: 'AIzaSyBInggOtXxPFYIRee0Xs3vb5iZ9YE9_518',
6 - part: 'snippet',
7 - fields: 'items(snippet(title,resourceId,thumbnails(high(url))))', //제목, VideoId, Thumbnail 이미지 정보.
8 - maxResults: 10,
9 - playlistId: 'PLfVO1GXBPp3tgrwk3GDJi3v-E_Hnq3lDO'
10 -}, function (err, response) {
11 - if (err) {
12 - console.log('The API returned an error: ', err);
13 - return;
14 - }
15 -
16 - var video = response.data.items;
17 - if (video.length == 0) {
18 - console.log('검색된 동영상이 없습니다.');
19 - } else {
20 - for (var i = 0; i < 10; i++) {
21 - console.log('{');
22 - console.log(JSON.stringify(response.data.items[i].snippet.title).replace(/\"/gi, ""));
23 - var a = JSON.stringify(response.data.items[i].snippet.resourceId.videoId);
24 - console.log('https://www.youtube.com/watch?v=' + a.replace(/\"/gi, "")); //JSON stringify 큰따옴표 제거후 URL로 전환
25 - console.log(JSON.stringify(response.data.items[i].snippet.thumbnails.high.url).replace(/\"/gi, ""));
26 - console.log('}');
27 - }
28 - }
29 -})
1 -const { google } = require("googleapis");
2 -var service = google.youtube('v3');
3 -
4 -service.playlistItems.list({
5 - key: 'AIzaSyBInggOtXxPFYIRee0Xs3vb5iZ9YE9_518',
6 - part: 'snippet',
7 - fields: 'items(snippet(title,resourceId,thumbnails(high(url))))', //제목, VideoId, Thumbnail 이미지 정보.
8 - maxResults: 10,
9 - playlistId: 'PLfVO1GXBPp3ubihJVPi6HSltRIuvSqSI1'
10 -}, function (err, response) {
11 - if (err) {
12 - console.log('The API returned an error: ', err);
13 - return;
14 - }
15 -
16 - var video = response.data.items;
17 - if (video.length == 0) {
18 - console.log('검색된 동영상이 없습니다.');
19 - } else {
20 - for (var i = 0; i < 10; i++) {
21 - console.log('{');
22 - console.log(JSON.stringify(response.data.items[i].snippet.title).replace(/\"/gi, ""));
23 - var a = JSON.stringify(response.data.items[i].snippet.resourceId.videoId);
24 - console.log('https://www.youtube.com/watch?v=' + a.replace(/\"/gi, "")); //JSON stringify 큰따옴표 제거후 URL로 전환
25 - console.log(JSON.stringify(response.data.items[i].snippet.thumbnails.high.url).replace(/\"/gi, ""));
26 - console.log('}');
27 - }
28 - }
29 -})
1 -const { google } = require("googleapis");
2 -var service = google.youtube('v3');
3 -
4 -service.playlistItems.list({
5 - key: 'AIzaSyBInggOtXxPFYIRee0Xs3vb5iZ9YE9_518',
6 - part: 'snippet',
7 - fields: 'items(snippet(title,resourceId,thumbnails(high(url))))', //제목, VideoId, Thumbnail 이미지 정보.
8 - maxResults: 10,
9 - playlistId: 'PLfVO1GXBPp3u0ckIfYZkADGlSQ6LQoAIQ'
10 -}, function (err, response) {
11 - if (err) {
12 - console.log('The API returned an error: ', err);
13 - return;
14 - }
15 -
16 - var video = response.data.items;
17 - if (video.length == 0) {
18 - console.log('검색된 동영상이 없습니다.');
19 - } else {
20 - for (var i = 0; i < 10; i++) {
21 - console.log('{');
22 - console.log(JSON.stringify(response.data.items[i].snippet.title).replace(/\"/gi, ""));
23 - var a = JSON.stringify(response.data.items[i].snippet.resourceId.videoId);
24 - console.log('https://www.youtube.com/watch?v=' + a.replace(/\"/gi, "")); //JSON stringify 큰따옴표 제거후 URL로 전환
25 - console.log(JSON.stringify(response.data.items[i].snippet.thumbnails.high.url).replace(/\"/gi, ""));
26 - console.log('}');
27 - }
28 - }
29 -})
1 -const { google } = require("googleapis");
2 -var service = google.youtube('v3');
3 -
4 -service.playlistItems.list({
5 - key: 'AIzaSyBInggOtXxPFYIRee0Xs3vb5iZ9YE9_518',
6 - part: 'snippet',
7 - fields: 'items(snippet(title,resourceId,thumbnails(high(url))))', //제목, VideoId, Thumbnail 이미지 정보.
8 - maxResults: 10,
9 - playlistId: 'PLfVO1GXBPp3vo3sivJPfFzREBECRFepVK'
10 -}, function (err, response) {
11 - if (err) {
12 - console.log('The API returned an error: ', err);
13 - return;
14 - }
15 -
16 - var video = response.data.items;
17 - if (video.length == 0) {
18 - console.log('검색된 동영상이 없습니다.');
19 - } else {
20 - for (var i = 0; i < 10; i++) {
21 - console.log('{');
22 - console.log(JSON.stringify(response.data.items[i].snippet.title).replace(/\"/gi, ""));
23 - var a = JSON.stringify(response.data.items[i].snippet.resourceId.videoId);
24 - console.log('https://www.youtube.com/watch?v=' + a.replace(/\"/gi, "")); //JSON stringify 큰따옴표 제거후 URL로 전환
25 - console.log(JSON.stringify(response.data.items[i].snippet.thumbnails.high.url).replace(/\"/gi, ""));
26 - console.log('}');
27 - }
28 - }
29 -})
1 -const { google } = require("googleapis");
2 -var service = google.youtube('v3');
3 -
4 -service.search.list({
5 - key: 'AIzaSyBInggOtXxPFYIRee0Xs3vb5iZ9YE9_518',
6 - part: 'id, snippet',
7 - fields: 'items(id(videoId),snippet(title,thumbnails(high(url))))', //제목, VideoId, Thumbnail 이미지 정보.
8 - maxResults: 1, // 최상단의 1개만 출력
9 - q: '경희대학교', // eventObj.message.text 를 input하도록 연결하시면 됩니다.
10 - regionCode: 'KR'
11 -}, function (err, response) {
12 - if (err) {
13 - console.log('The API returned an error: ', err);
14 - return;
15 - }
16 -
17 - var video = response.data.items;
18 - if (video.length == 0) {
19 - console.log('검색된 동영상이 없습니다.');
20 - } else {
21 -
22 - console.log('{');
23 - console.log(JSON.stringify(response.data.items[0].snippet.title).replace(/\"/gi, ""));
24 - var a = JSON.stringify(response.data.items[0].id.videoId);
25 - console.log('https://www.youtube.com/watch?v=' + a.replace(/\"/gi, "")); //JSON stringify 큰따옴표 제거후 URL로 전환
26 - console.log(JSON.stringify(response.data.items[0].snippet.thumbnails.high.url).replace(/\"/gi, ""));
27 - console.log('}');
28 -
29 - }
30 -})
1 -수동으로 googleapis 를 npm install 해야합니다.
...\ No newline at end of file ...\ No newline at end of file
1 +// 아래 주석을 참고해 플레이리스트 or 노래의 배열을 직접 만드시면 됩니다.
2 +// 배열을 만들 때, 활용하실 id값이 플레이리스트의 id인지, 특정 노래의 id인지 구별해서 배열을 만드셔야 합니다.
3 +// '플레이리스트'의 id라면 인덱스 500 이하로,
4 +// '특정 노래'의 id라면 인덱스 500 이상으로 넣어주세요!
5 +// 아래 예시를 보고 이해 안되시면, 편하게 카톡으로 말씀해주세요
6 +
7 +
8 +// index < 500 = 플레이리스트
9 +// index > 500 = 개별 곡
10 +
11 +// index 100번대 = 장르 플레이리스트
12 +// index 200번대 = 무드 플레이리스트
13 +// index 300번대 = 가수 플레이리스트
14 +// index 500번대 = 특정 플레이리스트의 노래 10곡
15 +
16 +// index 101 = 장르 - 힙합
17 +// index 102 = 장르 - 피아노
18 +// index 103 = 장르 - 팝
19 +
20 +// index 201 = 무드 - 익사이팅
21 +// index 202 = 무드 - 새드
22 +
23 +// index 301 = 가수 - 블랙핑크
24 +// index 302 = 가수 - 아이유
25 +// index 303 = 가수 - 레드벨벳
26 +// index 304 = 가수 - 트와이스
27 +
28 +// index 501 = 슬픈노래 10곡
29 +
30 +exports.all_ids = [];
31 +
32 +exports.all_ids[101] = 'PLfVO1GXBPp3s03voaFAWN7AkzEnpsGF1U'
33 +exports.all_ids[102] = 'PLfVO1GXBPp3t4Wp8l-cR9s8wpWI2Fnz4g'
34 +exports.all_ids[103] = 'PLfVO1GXBPp3vXaFB2VtbdQ2h6ljGZOSlj'
35 +
36 +exports.all_ids[201] = 'PLfVO1GXBPp3tdasvQuIu_BmSNm4GVwnNj'
37 +exports.all_ids[202] = 'PLfVO1GXBPp3vrR3ZcQFlCEC6oNdo_MQ_R'
38 +
39 +exports.all_ids[301] = 'PLfVO1GXBPp3tgrwk3GDJi3v-E_Hnq3lDO'
40 +exports.all_ids[302] = 'PLfVO1GXBPp3ubihJVPi6HSltRIuvSqSI1'
41 +exports.all_ids[303] = 'PLfVO1GXBPp3u0ckIfYZkADGlSQ6LQoAIQ'
42 +exports.all_ids[304] = 'PLfVO1GXBPp3vo3sivJPfFzREBECRFepVK'
43 +
44 +exports.all_ids[501] = ['p5iu1V30myk', 'i-SBnhaZSSU', 'Etfgb6A7hSI', 'IN2mml9xs_s',
45 + 'tp1uoFAfgHE', 'Qx22TnVVIfU', '3y1QIqR115A', 'VXBI1wt8XII', 'aWMBn2--E0Q', 'HyTbgBlnLCo'];
...\ No newline at end of file ...\ No newline at end of file
1 +var Info = require('./Info');
2 +var ids = require('./all_ids')
3 +const request = require('request');
4 +const fs = require('fs');
5 +const TARGET_URL = 'https://api.line.me/v2/bot/message/reply'
6 +var { google } = require('googleapis');
7 +var service = google.youtube('v3');
8 +
9 +
10 +exports.check = function (message, replyToken) {
11 +
12 + const rand_0to9 = Math.floor(Math.random() * 10); // 0~9까지 난수생성
13 +
14 + var choice;
15 + var choose;
16 +
17 + switch (message) {
18 + case "슬픈 노래":
19 + choose = 501;
20 + choice = ids.all_ids[choose][rand_0to9]
21 + break;
22 + case "힙합 플레이리스트":
23 + choose = 101;
24 + choice = ids.all_ids[choose]
25 + break;
26 + case "피아노 플레이리스트":
27 + choose = 102;
28 + choice = ids.all_ids[choose]
29 + break;
30 + case "팝 플레이리스트":
31 + choose = 103;
32 + choice = ids.all_ids[choose]
33 + break;
34 + case "신나는 플레이리스트":
35 + choose = 201;
36 + choice = ids.all_ids[choose]
37 + break;
38 + case "슬픈 플레이리스트":
39 + choose = 202;
40 + choice = ids.all_ids[choose]
41 + break;
42 + case "블랙핑크 플레이리스트":
43 + choose = 301;
44 + choice = ids.all_ids[choose]
45 + break;
46 + case "아이유 플레이리스트":
47 + choose = 302;
48 + choice = ids.all_ids[choose]
49 + break;
50 + case "레드벨벳 플레이리스트":
51 + choose = 303;
52 + choice = ids.all_ids[choose]
53 + break;
54 + case "트와이스 플레이리스트":
55 + choose = 304;
56 + choice = ids.all_ids[choose]
57 + break;
58 +
59 + // 아래는 case 추가를 위한 템플릿
60 + // case "":
61 + // choose = ;
62 + // choice = ids.all_ids[choose]
63 +
64 + default:
65 + console.log("잘못 입력했어요~ 다시 입력하세요");
66 + choice = -1;
67 + }
68 +
69 + if (choose > 500) {
70 +
71 + service.videos.list
72 + (
73 + {
74 + key: 'AIzaSyBInggOtXxPFYIRee0Xs3vb5iZ9YE9_518',
75 + part: 'snippet',
76 + id: choice,
77 + fields: 'items(snippet(title))'
78 + },
79 + function (err, response) {
80 + if (err) {
81 + console.log('The API returned an error: ', err);
82 + return;
83 + }
84 +
85 + var video = response.data.items;
86 +
87 + if (video.length == 0) {
88 + console.log('검색된 동영상이 없습니다.');
89 + }
90 + else {
91 + sendMessage = JSON.stringify(response.data.items[0].snippet.title);
92 + console.log(sendMessage);
93 + request.post(
94 + {
95 + url: TARGET_URL,
96 + headers:
97 + {
98 + 'Authorization': `Bearer ${Info.TOKEN}`
99 + },
100 + json:
101 + {
102 + "replyToken": replyToken,
103 + "messages":
104 + [
105 + {
106 + "type": "image",
107 + "originalContentUrl": "https://img.youtube.com/vi/" + choice + "/hqdefault.jpg",
108 + "previewImageUrl": "https://img.youtube.com/vi/" + choice + "/hqdefault.jpg"
109 + },
110 + {
111 + "type": "text",
112 + "text": sendMessage
113 + }
114 + ]
115 + }
116 + }
117 + );
118 + }
119 + }
120 +
121 + )
122 + }
123 +
124 + else {
125 + if (choice == -1) {
126 + sendMessage = "잘못 입력했어요~ 다시 입력하세요";
127 + request.post(
128 + {
129 + url: TARGET_URL,
130 + headers:
131 + {
132 + 'Authorization': `Bearer ${Info.TOKEN}`
133 + },
134 + json:
135 + {
136 + "replyToken": replyToken,
137 + "messages":
138 + [
139 + {
140 + "type": "text",
141 + "text": sendMessage
142 + }
143 + ]
144 + }
145 + }
146 + );
147 + }
148 + else {
149 + service.playlistItems.list({
150 + key: 'AIzaSyBInggOtXxPFYIRee0Xs3vb5iZ9YE9_518',
151 + part: 'snippet',
152 + fields: 'items(snippet(title,resourceId,thumbnails(high(url))))', //제목, VideoId, Thumbnail 이미지 정보.
153 + maxResults: 10,
154 + playlistId: choice
155 + }, function (err, response) {
156 + if (err) {
157 + console.log('The API returned an error: ', err);
158 + return;
159 + }
160 +
161 + var video = response.data.items;
162 + if (video.length == 0) {
163 + console.log('검색된 동영상이 없습니다.');
164 + } else {
165 + sendMessage = "";
166 + var temp_title = [], temp_url = [], temp_url2 = [], temp_thumpnail = [];
167 + for (var i = 0; i < 10; i++) {
168 +
169 + temp_title[i] = JSON.stringify(response.data.items[i].snippet.title).replace(/\"/gi, "");
170 +
171 + temp_url2[i] = JSON.stringify(response.data.items[i].snippet.resourceId.videoId);
172 + temp_url[i] = 'https://www.youtube.com/watch?v=' + (temp_url2[i].replace(/\"/gi, ""));
173 +
174 + //temp_thumpnail[i] = "https://img.youtube.com/vi/" + JSON.stringify(response.data.items[i].snippet.thumbnails.high.url).replace(/\"/gi, "") + "/hqdefault.jpg";
175 + // 썸네일 : 사용자가 플레이리스트로 입력 시 리턴으로 너무 많은 정보들을 줘야함. 그래서 뺌.
176 +
177 + sendMessage += temp_title[i] + "\n" +
178 + temp_url[i] + "\n" + "\n";
179 + // temp_thumpnail[i] + "\n" + "\n";
180 + } console.log(sendMessage);
181 + request.post(
182 + {
183 + url: TARGET_URL,
184 + headers:
185 + {
186 + 'Authorization': `Bearer ${Info.TOKEN}`
187 + },
188 + json:
189 + {
190 + "replyToken": replyToken,
191 + "messages":
192 + [
193 + // {
194 + // "type": "image",
195 + // "originalContentUrl": temp_thumpnail[0],
196 + // "previewImageUrl": temp_thumpnail[0]
197 + // },
198 + {
199 + "type": "text",
200 + "text": sendMessage
201 + }
202 + ]
203 + }
204 + }
205 + );
206 + }
207 + })
208 + }
209 + }
210 +
211 +
212 +
213 +
214 +}
...@@ -6,55 +6,46 @@ const HTTPS = require('https'); ...@@ -6,55 +6,46 @@ const HTTPS = require('https');
6 const domain = "2020105631.oss2021.tk" 6 const domain = "2020105631.oss2021.tk"
7 const sslport = 23023; 7 const sslport = 23023;
8 const bodyParser = require('body-parser'); 8 const bodyParser = require('body-parser');
9 +const TARGET_URL = 'https://api.line.me/v2/bot/message/reply';
10 +// var Info = require('./Info');
9 var app = express(); 11 var app = express();
10 app.use(bodyParser.json()); 12 app.use(bodyParser.json());
11 - 13 +var songs = require('./check');
12 -// var { google } = require('googleapis');
13 -
14 -var sad = require('./video_sad');
15 -
16 14
17 app.post('/hook', function (req, res) { 15 app.post('/hook', function (req, res) {
18 16
19 var eventObj = req.body.events[0]; 17 var eventObj = req.body.events[0];
20 - var source = eventObj.source;
21 var message = eventObj.message; 18 var message = eventObj.message;
22 19
23 // request log 20 // request log
24 - console.log('======================', new Date() ,'======================'); 21 + console.log('======================', new Date(), '======================');
25 - send(eventObj.replyToken, eventObj.message.text); 22 + send(eventObj.replyToken, message.text);
26 res.sendStatus(200); 23 res.sendStatus(200);
27 }); 24 });
28 -function send(replyToken, message){ 25 +function send(replyToken, message) {
29 26
30 request.post( 27 request.post(
31 { 28 {
32 body: message 29 body: message
33 }, 30 },
34 31
35 - function() { 32 + function () {
36 - if (message == "슬픈노래") { 33 + songs.check(message, replyToken);
37 - sad.check(message,replyToken);
38 34
39 } 35 }
40 - else {
41 - sad.check(message, replyToken);
42 - }
43 - }
44 ); 36 );
45 } 37 }
46 try { 38 try {
47 const option = { 39 const option = {
48 - ca: fs.readFileSync('/etc/letsencrypt/live/' + domain +'/fullchain.pem'), 40 + ca: fs.readFileSync('/etc/letsencrypt/live/' + domain + '/fullchain.pem'),
49 - key: fs.readFileSync(path.resolve(process.cwd(), '/etc/letsencrypt/live/' + domain +'/privkey.pem'), 'utf8').toString(), 41 + key: fs.readFileSync(path.resolve(process.cwd(), '/etc/letsencrypt/live/' + domain + '/privkey.pem'), 'utf8').toString(),
50 - cert: fs.readFileSync(path.resolve(process.cwd(), '/etc/letsencrypt/live/' + domain +'/cert.pem'), 'utf8').toString(), 42 + cert: fs.readFileSync(path.resolve(process.cwd(), '/etc/letsencrypt/live/' + domain + '/cert.pem'), 'utf8').toString(),
51 }; 43 };
52 44
53 HTTPS.createServer(option, app).listen(sslport, () => { 45 HTTPS.createServer(option, app).listen(sslport, () => {
54 console.log(`[HTTPS] Server is started on port ${sslport}`); 46 console.log(`[HTTPS] Server is started on port ${sslport}`);
55 }); 47 });
56 - } catch (error) { 48 +} catch (error) {
57 console.log('[HTTPS] HTTPS 오류가 발생하였습니다. HTTPS 서버는 실행되지 않습니다.'); 49 console.log('[HTTPS] HTTPS 오류가 발생하였습니다. HTTPS 서버는 실행되지 않습니다.');
58 console.log(error); 50 console.log(error);
59 - }
60 -
...\ No newline at end of file ...\ No newline at end of file
51 +}
......
1 -var express = require('express');
2 -const request = require('request');
3 -const TARGET_URL = 'https://api.line.me/v2/bot/message/reply'
4 -const TOKEN = 'Kb1/rQYz4MUhF8XyKQv7z9x0MxVQ5bX/XO8S/yt/1qQEJVAbsEFAaMvXKEOx9Umr7KhivfyDPfZHRRLFPngR0O4ZGWV2VFses8ufPE7uAdvYr4G6keBNAU69nBz5IC71HfbIrUHxXYqD7GfhVwXzpwdB04t89/1O/w1cDnyilFU='
5 -const PAPAGO_URL = 'https://openapi.naver.com/v1/papago/n2mt'
6 -const PAPAGO_ID = 'kwoxKGTi6azBaW9aSVxe'
7 -const PAPAGO_SECRET = 'svB_MM61oD'
8 -const fs = require('fs');
9 -const path = require('path');
10 -const HTTPS = require('https');
11 -const domain = "2020105631.oss2021.tk"
12 -const sslport = 23023;
13 -const bodyParser = require('body-parser');
14 -var app = express();
15 -app.use(bodyParser.json());
16 -
17 -var { google } = require('googleapis');
18 -
19 -/// ----
20 -
21 -
22 -app.post('/hook', function (req, res) {
23 -
24 - var eventObj = req.body.events[0];
25 - var source = eventObj.source;
26 - var message = eventObj.message;
27 -
28 - // request log
29 - console.log('======================', new Date(), '======================');
30 - console.log('[request]', req.body);
31 - console.log('[request source] ', eventObj.source);
32 - console.log('[request message]', eventObj.message);
33 -
34 - trans(eventObj.replyToken, eventObj.message.text);
35 -
36 -
37 - res.sendStatus(200);
38 -});
39 -function trans(replyToken, message) {
40 -
41 - request.post(
42 -
43 - {
44 - url: PAPAGO_URL,
45 - headers: {
46 - 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
47 - 'X-Naver-Client-Id': `${PAPAGO_ID}`,
48 - 'X-Naver-Client-Secret': `${PAPAGO_SECRET}`
49 - },
50 - body: 'source=ko&target=en&text=' + message,
51 - json: true
52 - },
53 -
54 - (error, response, body) => {
55 - if (!error && response.statusCode == 200) {
56 - // message 가 사용자에게서 입력받은 메시지 내용입니다. sendMessage 는 보낼 메시지 내용입니다.
57 - // 위에 PAPAGO API부분은 추후 API를 연동시킬 때 맞춰서 작성하기 쉽도록 템플릿을 남겨놓았습니다. 자세한 정보는 교수님 학습 자료의 experiment의 trans 폴더를 참고하세요.
58 - // (현재 코드에선 PAPAGO API의 작동 결과는 반영되지 않습니다.)
59 - //↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
60 - // var sendMessage;
61 -
62 - // --------
63 - if (message == "노래 추천해줘") {
64 - sendMessage = "아이유의 노래를 추천드립니다.";
65 - console.log(typeof (sendMessage));
66 - console.log(sendMessage);
67 -
68 - request.post(
69 - {
70 - url: TARGET_URL,
71 - headers: {
72 - 'Authorization': `Bearer ${TOKEN}`
73 - },
74 - json: {
75 - "replyToken": replyToken,
76 - "messages": [
77 - {
78 - "type": "text",
79 - "text": sendMessage
80 - }
81 - ]
82 - }
83 - }, (error, response, body) => {
84 - console.log(body)
85 - });
86 -
87 - }
88 - else {
89 - // var sendMessage = "무슨 말인지 못알아먹겠습니다";
90 -
91 - // --------
92 - var service = google.youtube('v3');
93 - service.videos.list({
94 - key: 'AIzaSyBInggOtXxPFYIRee0Xs3vb5iZ9YE9_518',
95 - part: 'snippet,statistics',
96 - id: 'p5iu1V30myk', // 동영상 Id
97 - fields: 'items(snippet(title))'
98 - }, function (err, response) {
99 - if (err) {
100 - console.log('The API returned an error: ', err);
101 - return;
102 - }
103 -
104 - var video = response.data.items;
105 - if (video.length == 0) {
106 - console.log('검색된 동영상이 없습니다.');
107 - } else {
108 - // var sendMessage ="123";
109 - // console.log(JSON.stringify(response.data.items[0].snippet.title));// 콘솔에 출력
110 - // console.log(JSON.stringify(response.data.items[0].snippet));// 콘솔에 출력
111 - // console.log(JSON.stringify(response.data.items[0]));// 콘솔에 출력
112 - // console.log(JSON.stringify(response.data));// 콘솔에 출력
113 -
114 -
115 - var sendMessage = JSON.stringify(response.data.items[0].snippet.title);
116 - // sendMessage = response.data.items[0].snippet.title;
117 - console.log(sendMessage);
118 - console.log(typeof (sendMessage));
119 - }
120 - request.post(
121 - {
122 - url: TARGET_URL,
123 - headers: {
124 - 'Authorization': `Bearer ${TOKEN}`
125 - },
126 - json: {
127 - "replyToken": replyToken,
128 - "messages": [
129 - {
130 - "type": "text",
131 - "text": sendMessage
132 - }
133 - ]
134 - }
135 - }, (error, response, body) => {
136 - console.log(body)
137 - });
138 - })
139 - // // --------
140 - }
141 -
142 - }
143 - });
144 -}
145 -// function trans(replyToken, message) {
146 -// request.post(
147 -// {
148 -// url: PAPAGO_URL,
149 -// headers: {
150 -// 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
151 -// 'X-Naver-Client-Id': `${PAPAGO_ID}`,
152 -// 'X-Naver-Client-Secret': `${PAPAGO_SECRET}`
153 -// },
154 -// body: 'source=ko&target=en&text=' + message,
155 -// json:true
156 -// },
157 -
158 -// (error, response, body) => {
159 -// if(!error && response.statusCode == 200)
160 -// {
161 -// // message 가 사용자에게서 입력받은 메시지 내용입니다. sendMessage 는 보낼 메시지 내용입니다.
162 -// // 위에 PAPAGO API부분은 추후 API를 연동시킬 때 맞춰서 작성하기 쉽도록 템플릿을 남겨놓았습니다. 자세한 정보는 교수님 학습 자료의 experiment의 trans 폴더를 참고하세요.
163 -// // (현재 코드에선 PAPAGO API의 작동 결과는 반영되지 않습니다.)
164 -// //↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
165 -
166 -
167 -
168 -// var sendMessage;
169 -// // --------
170 -// if (message=="노래 추천해줘")
171 -// {
172 -// sendMessage = "아이유의 노래를 추천드립니다.";
173 -// console.log(typeof(sendMessage));
174 -// console.log(sendMessage);
175 -
176 -
177 -// console.log("11111");
178 -// console.log(body.message);
179 -// console.log("11111");
180 -// // console.log(typeof(response.data.items[0].snippet.title));
181 -
182 -// request.post(
183 -// {
184 -// url: TARGET_URL,
185 -// headers: {
186 -// 'Authorization': `Bearer ${TOKEN}`
187 -// },
188 -// json: {
189 -// "replyToken": replyToken,
190 -// "messages": [
191 -// {
192 -// "type": "text",
193 -// "text": sendMessage
194 -// }
195 -// ]
196 -// }
197 -// }, (error, response, body) => {
198 -// console.log(body)
199 -// });
200 -// }
201 -// else
202 -// {
203 -// // var sendMessage = "무슨 말인지 못알아먹겠습니다";
204 -// // --------
205 -// var service = google.youtube('v3');
206 -
207 -// service.videos.list({
208 -// key: 'AIzaSyBInggOtXxPFYIRee0Xs3vb5iZ9YE9_518',
209 -// part: 'snippet,statistics',
210 -// id: 'p5iu1V30myk', // 동영상 Id
211 -// fields: 'items(snippet(title))'
212 -// }, function (err, response) {
213 -// if (err) {
214 -// console.log('The API returned an error: ', err);
215 -// return;
216 -// }
217 -
218 -// var video = response.data.items;
219 -// if (video.length == 0) {
220 -// console.log('검색된 동영상이 없습니다.');
221 -// } else {
222 -// // var sendMessage ="123";
223 -// // console.log(JSON.stringify(response.data.items[0].snippet.title));// 콘솔에 출력
224 -// // console.log(JSON.stringify(response.data.items[0].snippet));// 콘솔에 출력
225 -// // console.log(JSON.stringify(response.data.items[0]));// 콘솔에 출력
226 -// // console.log(JSON.stringify(response.data));// 콘솔에 출력
227 -
228 -// sendMessage = JSON.stringify(response.data.items[0].snippet.title);
229 -// // sendMessage = response.data.items[0].snippet.title;
230 -// console.log(sendMessage);
231 -// console.log(typeof (sendMessage));
232 -// }
233 -// //console.log(sendMessage);
234 -// })
235 -// //console.log(sendMessage);
236 -// // // --------
237 -// /// ----
238 -
239 -
240 -// console.log("11111");
241 -// console.log(body.message);
242 -// console.log("11111");
243 -// // console.log(typeof(response.data.items[0].snippet.title));
244 -
245 -// request.post(
246 -// {
247 -// url: TARGET_URL,
248 -// headers: {
249 -// 'Authorization': `Bearer ${TOKEN}`
250 -// },
251 -// json: {
252 -// "replyToken": replyToken,
253 -// "messages": [
254 -// {
255 -// "type": "text",
256 -// "text": sendMessage
257 -// }
258 -// ]
259 -// }
260 -// }, (error, response, body) => {
261 -// console.log(body)
262 -// });
263 -// }
264 -// //↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑
265 -
266 -// }
267 -// });
268 -// }
269 -
270 -try {
271 - const option = {
272 - ca: fs.readFileSync('/etc/letsencrypt/live/' + domain + '/fullchain.pem'),
273 - key: fs.readFileSync(path.resolve(process.cwd(), '/etc/letsencrypt/live/' + domain + '/privkey.pem'), 'utf8').toString(),
274 - cert: fs.readFileSync(path.resolve(process.cwd(), '/etc/letsencrypt/live/' + domain + '/cert.pem'), 'utf8').toString(),
275 - };
276 -
277 - HTTPS.createServer(option, app).listen(sslport, () => {
278 - console.log(`[HTTPS] Server is started on port ${sslport}`);
279 - });
280 -} catch (error) {
281 - console.log('[HTTPS] HTTPS 오류가 발생하였습니다. HTTPS 서버는 실행되지 않습니다.');
282 - console.log(error);
283 -}
1 -exports.check = function(message,replyToken){
2 -
3 - const rand_0to9 = Math.floor(Math.random() * 10); // 0~9까지 난수생성
4 - var ids = ['p5iu1V30myk', 'i-SBnhaZSSU', 'Etfgb6A7hSI', 'IN2mml9xs_s', // 모든 동영상 id를 관리하는 배열
5 - 'tp1uoFAfgHE', 'Qx22TnVVIfU', '3y1QIqR115A', 'VXBI1wt8XII', 'aWMBn2--E0Q', 'HyTbgBlnLCo'];
6 -
7 - const request = require('request');
8 - const TARGET_URL = 'https://api.line.me/v2/bot/message/reply'
9 - //라인 고유 토큰
10 - const TOKEN = 'Kb1/rQYz4MUhF8XyKQv7z9x0MxVQ5bX/XO8S/yt/1qQEJVAbsEFAaMvXKEOx9Umr7KhivfyDPfZHRRLFPngR0O4ZGWV2VFses8ufPE7uAdvYr4G6keBNAU69nBz5IC71HfbIrUHxXYqD7GfhVwXzpwdB04t89/1O/w1cDnyilFU='
11 - var { google } = require('googleapis');
12 -
13 - var service = google.youtube('v3');
14 - service.videos.list
15 - (
16 - {
17 - key: 'AIzaSyBInggOtXxPFYIRee0Xs3vb5iZ9YE9_518',
18 - part: 'snippet',
19 - id: ids[rand_0to9], // 동영상 Id random input
20 - fields: 'items(snippet(title))'
21 - },
22 - function (err, response)
23 - {
24 - if (err)
25 - {
26 - console.log('The API returned an error: ', err);
27 - return;
28 - }
29 -
30 - var video = response.data.items;
31 -
32 - if (video.length == 0)
33 - {
34 - console.log('검색된 동영상이 없습니다.');
35 - }
36 - else
37 - {
38 - sendMessage = JSON.stringify(response.data.items[0].snippet.title);
39 - console.log(sendMessage);
40 - request.post(
41 - {
42 - url: TARGET_URL,
43 - headers:
44 - {
45 - 'Authorization': `Bearer ${TOKEN}`
46 - },
47 - json:
48 - {
49 - "replyToken": replyToken,
50 - "messages":
51 - [
52 - {
53 - "type": "text",
54 - "text": sendMessage
55 - }
56 - ]
57 - }
58 - }
59 - );
60 - }
61 - }
62 - )
63 -
64 -
65 -
66 -
67 -
68 -}