check.js 15.6 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448
var Info = require('./Info');
var ids = require('./all_ids')
const request = require('request');
const fs = require('fs');
const TARGET_URL = 'https://api.line.me/v2/bot/message/reply'
var { google } = require('googleapis');
var service = google.youtube('v3');
// var app = express();
// app.use(bodyParser.json());

//세팅,설정값
var setting_userId = []; //유저아이디보관
var setting_Thumbnail = []; // 1:썸네일 출력(기본값) / 0:미출력
var setting_SendAmount = []; // 보낼 양 (1이상, 10이하의 정수) (기본값:1)
var setting_SendAddress = []; // 1:유튜브 주소 출력(기본값) / 0:미출력

function SEND(replyToken,title,url2,thumbnail,SendAmount,sendaddress) //검색해서 나온 내용 전송하는 함수
{
    //sendMessage = JSON.stringify(response.data.items[0].snippet.title);
    
    sendMessage = "";
    var temp_title = [], temp_url = [], temp_url2 = [], temp_thumpnail = [];
    for (var i = 0; i < SendAmount; i++) {

        temp_title[i] = title[i];

        temp_url2[i] = url2[i];
        if (sendaddress) //주소 전송 활성화
            temp_url[i] = 'https://www.youtube.com/watch?v=' + (temp_url2[i].replace(/\"/gi, ""));
        else 
            temp_url[i] = "";
        sendMessage += temp_title[i] + "\n" +
            temp_url[i] + "\n" + "\n";
    }

    console.log(sendMessage);
    if (thumbnail) //썸네일을 활성화시켰을 경우, 맨 첫번째 작품 리스트 썸네일만 보여줌.
        request.post(
            {
                url: TARGET_URL,
                headers:
                {
                    'Authorization': `Bearer ${Info.TOKEN}`
                },
                json:
                {
                    "replyToken": replyToken,
                    "messages":
                    [
                        {
                            "type": "image",
                            "originalContentUrl": "https://img.youtube.com/vi/" + url2[0] + "/hqdefault.jpg",
                            "previewImageUrl": "https://img.youtube.com/vi/" + url2[0] + "/hqdefault.jpg"
                        },
                        {
                            "type": "text",
                            "text": sendMessage
                        }
                    ]
                }
            }
        );
    else //썸네일 비활성화
        request.post(
            {
                url: TARGET_URL,
                headers:
                {
                    'Authorization': `Bearer ${Info.TOKEN}`
                },
                json:
                {
                    "replyToken": replyToken,
                    "messages":
                    [
                        {
                            "type": "text",
                            "text": sendMessage
                        }
                    ]
                }
            }
        );
}

function shuffle(array) { //플레이리스트에서 랜덤으로 골라서 출력할 수 있도록 shuffle 함수를 추가함
    for (let i = array.length - 1; i > 0; i--) {
        let j = Math.floor(Math.random() * (i + 1));
        [array[i], array[j]] = [array[j], array[i]];
    }
}

function SEND_LIST(replyToken,response,choice,thumbnail,SendAmount,sendaddress)//플레이리스트에서 나온 내용 전송하는 함수
{
    var random_order=[0,1,2,3,4,5,6,7,8,9];
    shuffle(random_order)

    sendMessage = "";
    var temp_title = [], temp_url = [], temp_url2 = [], temp_thumpnail = [];
    for (var i = 0; i < SendAmount; i++) {

        temp_title[i] = JSON.stringify(response.data.items[random_order[i]].snippet.title).replace(/\"/gi, "");

        temp_url2[i] = JSON.stringify(response.data.items[random_order[i]].snippet.resourceId.videoId);
        if (sendaddress) //주소 활성화
            temp_url[i] = 'https://www.youtube.com/watch?v=' + (temp_url2[i].replace(/\"/gi, ""));
        else 
            temp_url[i] = "";
        sendMessage += temp_title[i] + "\n" +
            temp_url[i] + "\n" + "\n";
    }


    console.log(sendMessage);
    if (thumbnail) //썸네일을 활성화시켰을 경우, 맨 첫번째 작품 리스트 썸네일만 보여줌.
        request.post(
            {
                url: TARGET_URL,
                headers:
                {
                    'Authorization': `Bearer ${Info.TOKEN}`
                },
                json:
                {
                    "replyToken": replyToken,
                    "messages":
                    [
                        {
                            "type": "image",
                            "originalContentUrl": "https://img.youtube.com/vi/" + (temp_url2[0].replace(/\"/gi, "")) + "/hqdefault.jpg",
                            "previewImageUrl": "https://img.youtube.com/vi/" + (temp_url2[0].replace(/\"/gi, "")) + "/hqdefault.jpg"
                        },
                        {
                            "type": "text",
                            "text": sendMessage
                        }
                    ]
                }
            }
        );
    else //썸네일 비활성화
        request.post(
            {
                url: TARGET_URL,
                headers:
                {
                    'Authorization': `Bearer ${Info.TOKEN}`
                },
                json:
                {
                    "replyToken": replyToken,
                    "messages":
                    [
                        {
                            "type": "text",
                            "text": sendMessage
                        }
                    ]
                }
            }
        );
}

function SEND_TEXT(replyToken,sendMessage) //단순 텍스트 전송하는 함수
{
    console.log(sendMessage);
    request.post(
        {
            url: TARGET_URL,
            headers:
            {
                'Authorization': `Bearer ${Info.TOKEN}`
            },
            json:
            {
                "replyToken": replyToken,
                "messages":
                [
                    {
                        "type": "text",
                        "text": sendMessage
                    }
                ]
            }
        }
    );
}

function SETTINGS(replyToken,sendMessage) //설정 함수
{
    console.log(sendMessage);
    request.post(
        {
            url: TARGET_URL,
            headers:
            {
                'Authorization': `Bearer ${Info.TOKEN}`
            },
            json:
            {
                "replyToken": replyToken,
                "messages":
                [
                    {
                        "type": "text",
                        "text": sendMessage
                    },
                    {
                        "type": "template",
                        "altText": "설정메뉴입니다.",
                        "template": {
                            "type": "buttons",
                            "title": "설정",
                            "text": "설정하려는 항목을 골라주세요.",
                            "actions": [
                                {
                                  "type": "postback",
                                  "label": "썸네일 출력 여부 변경",
                                  "data": "썸네일"
                                },
                                {
                                  "type": "postback",
                                  "label": "추천 음악 개수 조정",
                                  "data": "개수"
                                },
                                {
                                  "type": "postback",
                                  "label": "유튜브 주소 출력 여부 변경",
                                  "data": "주소"
                                }
                            ]
                        }
                    }
                ]
            }
        }
    );
}

exports.thumbnail_settings = function (thumbnail_yes,userId)
{
    
    // 여기서 썸네일을 출력할지 말지 물어보고나서, 웹훅의 응답을 받아 그 응답에 따라서
    // setting_Thumbnail[setting_userId.indexOf(userId)] 의 값를 수정합니다.
    // https://developers.line.biz/en/reference/messaging-api/#template-messages 의 confirm 를 참고해서 응용하시면 될 것 같습니다.
    // 이곳에 userid에 맞게 setting_Thumbnail, setting_SendAmount, setting_SendAddress 의 값을 수정해주시면 됩니다.
   // var thumbnail;
    
    //console.log("111");
    //console.log("111222");
   
    // var eventObj = req.body.events[0];
    //console.log("setting_userId.indexOf(userId) : before :  " + setting_userId.indexOf(userId));

    
    setting_Thumbnail[setting_userId.indexOf(userId)] = thumbnail_yes;
    //console.log("setting_userId.indexOf(userId) : after : " + setting_Thumbnail[setting_userId.indexOf(userId)])
    
    
    console.log(thumbnail_yes + "after");

    console.log("111111");

}

exports.amount_settings = function (replyToken, userId)
{
    console.log('출력량 설정');
    // 여기서 노래 몇개를 출력할지 물어보고나서, 웹훅의 응답을 받아 그 응답에 따라서
    // setting_SendAmount[setting_userId.indexOf(userId)] 의 값를 수정합니다.
    // 이거는 단순하게 숫자를 입력받으면 될 것 같습니다. 다만 1,2,3,4,5,6,7,8,9,10 의 응답만 받도록 해주셔야 합니다. (예외처리 필수)
}

exports.address_settings = function (replyToken, userId)
{
    console.log('유튜브 주소 출력 설정');
    // 여기서 유튜브 주소를 출력할지 말지 물어보고나서, 웹훅의 응답을 받아 그 응답에 따라서
    // setting_SendAddress[setting_userId.indexOf(userId)] 의 값를 수정합니다.
    // https://developers.line.biz/en/reference/messaging-api/#template-messages 의 confirm 를 참고해서 응용하시면 될 것 같습니다.
}

exports.check = function (message, replyToken, userId) {
    if (setting_userId.indexOf(userId)==-1) // 새로운 사용자가 이용할때, 설정 초기값 세팅
    {
        setting_userId.push(userId);
        setting_Thumbnail.push(1);
        setting_SendAmount.push(1);
        setting_SendAddress.push(1);
        console.log("알림: 새로운 사용자가 발견됨");
    }
    
    //const rand_0to9 = Math.floor(Math.random() * 10);   // 0~9까지 난수생성
    var choice;
    var choose;

    switch (message) {

        case "힙합 플레이리스트":
            choose = 101;
            choice = ids.all_ids[choose]
            break;
        case "피아노 플레이리스트":
            choose = 102;
            choice = ids.all_ids[choose]
            break;
        case "팝 플레이리스트":
            choose = 103;
            choice = ids.all_ids[choose]
            break;
        case "신나는 플레이리스트":
            choose = 201;
            choice = ids.all_ids[choose]
            break;
        case "슬픈 플레이리스트":
            choose = 202;
            choice = ids.all_ids[choose]
            break;
        case "블랙핑크 플레이리스트":
            choose = 301;
            choice = ids.all_ids[choose]
            break;
        case "아이유 플레이리스트":
            choose = 302;
            choice = ids.all_ids[choose]
            break;
        case "레드벨벳 플레이리스트":
            choose = 303;
            choice = ids.all_ids[choose]
            break;
        case "트와이스 플레이리스트":
            choose = 304;
            choice = ids.all_ids[choose]
            break;
        case "도움말":
            choose = 001;
            choice = 0;
            break;
        case "설정":
            choose = 002;
            choice = 0;
            break;
        // 아래는 case 추가를 위한 템플릿     
        // case "":
        //     choose = ;
        //     choice = ids.all_ids[choose]

        default:
            choose = 500;
            choice = 0;
    }

    if (choose == 500) { //일반 검색
        
        var optionParams={
            q:message,
            part:"snippet",
            key:Info.YoutubeKey,
            maxResults:10
         };
        optionParams.q=encodeURI(optionParams.q);
        var url="https://www.googleapis.com/youtube/v3/search?";
        for(var option in optionParams){
            url+=option+"="+optionParams[option]+"&";
        }
        
        //url의마지막에 붙어있는 & 정리
        url=url.substr(0, url.length-1);
        
        request(url, function(err, res, body){
            var title=[]
            var url2=[]
            var data=JSON.parse(body).items;
            for(var content in data)
            {
                title.push(data[content].snippet.title);
                url2.push(data[content].id.videoId);
            }
            if (title.length==0)
                console.log('검색된 동영상이 없습니다.');
            else
                SEND(replyToken,title,url2,setting_Thumbnail[setting_userId.indexOf(userId)],setting_SendAmount[setting_userId.indexOf(userId)],setting_SendAddress[setting_userId.indexOf(userId)]);
        });
        
        
       /*
        service.videos.list
            (
                {
                    key: 'AIzaSyBInggOtXxPFYIRee0Xs3vb5iZ9YE9_518',
                    part: 'snippet',
                    id: choice,
                    fields: 'items(snippet(title))'
                },
                function (err, response) {
                    if (err) {
                        console.log('The API returned an error: ', err);
                        return;
                    }

                    var video = response.data.items;

                    if (video.length == 0) {
                        console.log('검색된 동영상이 없습니다.');
                    }
                    else {
                        SEND(replyToken,response,choice,1,1,1);
                    }
                }

            )
            */
    }

    else if (choose == 001){ // 도움말
        sendMessage = "- 기본적으로 찾고 싶은 음악을 입력하여 보내면 적절한 음악 영상을 찾아 추천해드립니다."
                +"\n"+"예시) 소녀시대 노래"
                +"\n"+"- '플레이리스트'를 입력하면 분류에 따라 엄선한 음악을 추천드립니다!"
                +"\n"+"- '설정'을 입력하면 썸네일 출력 여부, 추천 음악 개수(1~10), 유튜브 주소 전송 여부를 설정하실 수 있습니다."
                +"\n"+"- 이 도움말을 다시 보고 싶으시다면 '도움말'을 입력하시면 됩니다! 음악과 함께 좋은 하루 보내세요.";
        SEND_TEXT(replyToken,sendMessage);
    }
    else if (choose == 002) { // 설정
        sendMessage = "설정 예시";
        SETTINGS(replyToken,sendMessage);
    }

    else { //플레이리스트
        service.playlistItems.list(
            {
            key: Info.YoutubeKey,
            part: 'snippet',
            fields: 'items(snippet(title,resourceId,thumbnails(high(url))))', //제목, VideoId, Thumbnail 이미지 정보.
            maxResults: 10,
            playlistId: choice
            }, function (err, response){
                if (err) {
                    console.log('The API returned an error: ', err);
                    return;
                }
                var video = response.data.items;
                if (video.length == 0) 
                    console.log('검색된 동영상이 없습니다.');
                else
                    SEND_LIST(replyToken,response,choice,setting_Thumbnail[setting_userId.indexOf(userId)],setting_SendAmount[setting_userId.indexOf(userId)],setting_SendAddress[setting_userId.indexOf(userId)]);
            }
        )
    }
}