app.js 6.18 KB
var express = require('express');
const request = require('request');
const TARGET_URL = 'https://api.line.me/v2/bot/message/reply'
const TOKEN = 'm79m/yBsTVzZeC9pYqSLzEL00Hp0HqsVE/0ZsZxW2HNAwdnb9TwDgBcOyCn3/aJASXsE8ekpyGg4Gts/4r8LO72OTZec9Np5Mh9g1vrgyDj5theWv4g2miE5F1Cqax4X3waj1aIzDGHcUZdHD6fQvAdB04t89/1O/w1cDnyilFU='
const PAPAGO_URL = 'https://openapi.naver.com/v1/papago/n2mt'
const PAPAGO_D_URL = 'https://openapi.naver.com/v1/papago/detectLangs'
const PAPAGO_ID = 'tA41WEd_nbzy0nZcUQks'
const PAPAGO_SECRET = '6DHwov9gg2'
const bodyParser = require('body-parser');
var app = express();
var async = require('async');
const { resolve } = require('path');
var Language_Detect_Array = new Array();
var User_Info_Array = new Array();
Language_Detect_Array[0] =
{
    "Message" : '영어',
    "PapagoLanguage" : 'en'
}
Language_Detect_Array[1] =
{
    "Message" : '일본어',
    "PapagoLanguage" : 'ja'
}
Language_Detect_Array[2] =
{
    "Message" : '프랑스어',
    "PapagoLanguage" : 'fr'
}
Language_Detect_Array[3] =
{
    "Message" : '한국어',
    "PapagoLanguage" : 'ko'
}

User_Info_Array[0] =
{
    UserId : null,
    UserPapagoLanguage : ''
}

app.use(bodyParser.json());
app.post('/hook', function (req, res) {

    var eventObj = req.body.events[0];
    var message = eventObj.message.text;
    var replyToken = eventObj.replyToken;
    var userid = eventObj.source.userId;
    
    AsyncFunction(message, replyToken, userid);

    res.sendStatus(200);
});

async function AsyncFunction(message, replyToken, userid)
{
    var User_Location = search_user_info(userid); 
    var DetectLanguage = await detector(message);
    if(DetectLanguage != 'ko') var TransToKoreanMessage = await trans(DetectLanguage, message, 'ko'); else var TransToKoreanMessage = message;
    var DetectLanguageChange = Detect_Papago_Language_Change(TransToKoreanMessage, User_Location);
    if(DetectLanguage != User_Info_Array[User_Location].UserPapagoLanguage) var TransToUserSettingMessage = await trans(DetectLanguage, message, User_Info_Array[User_Location].UserPapagoLanguage);
    var Messaging = await messaging(TransToUserSettingMessage, replyToken, DetectLanguageChange);
    console.log("log-Message: ", Messaging);
}

function detector (message)
//언어 감지
{  
    return new Promise(function(resolve, reject)
    {
        request.post
        (
            {
                url: PAPAGO_D_URL,
                headers:
                {
                    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
                    'X-Naver-Client-Id': `${PAPAGO_ID}`,
                    'X-Naver-Client-Secret': `${PAPAGO_SECRET}`
                },
                body: 'query='+message,
                json:true
            },(error, response, body) => 
            {
                if(!error && response.statusCode == 200)
                {
                    var DetectLanguage = body.langCode;
                    resolve(DetectLanguage);
                }
                else
                {
                    reject(new Error('Request is failed'));
                }
            }
        )
    })
}

function messaging(message, replyToken, DetectLanguageChange)
//메시지 보내기
{
    return new Promise(function(resolve, reject)
    {
        if(DetectLanguageChange)
        request.post
        (
            {
                url: TARGET_URL,
                headers: 
                {
                    'Authorization': `Bearer ${TOKEN}`
                },
                json: 
                {
                    "replyToken":replyToken,
                    "messages":
                    [
                        {
                            "type":"text",
                            "text":message
                        }
                    ]
    
                }
            }, (error, response, body) =>
            {
                if(!error && response.statusCode == 200)
                resolve('정상적으로 전송 되었습니다.');
            }
        );
    })
}

function trans (DetectLanguage, message, TransLanguage)
//언어 번역
{
    return new Promise(function(resolve, reject)
    {
        request.post(
            {
                url: PAPAGO_URL,
                headers: 
                {
                    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
                    'X-Naver-Client-Id': `${PAPAGO_ID}`,
                    'X-Naver-Client-Secret': `${PAPAGO_SECRET}`
                },
                body: 'source='+DetectLanguage+'&target='+TransLanguage+'&text='+message,
                json:true
            },(error, response, body) => 
            {
                if(!error && response.statusCode == 200)
                {
                    var transMessage = body.message.result.translatedText;
                    console.log('transMessage: ', transMessage);
                    resolve(transMessage);
                }
            }
            );
    })
}

function search_user_info (userid)
//유저 생성 또는 위치 찾기
{
    for(var i in User_Info_Array)
    {
        if (User_Info_Array[i].UserId == userid)
        {
            //기존 유저
            return i;
            break;
        }
        else if ( i == User_Info_Array.length-1)
        {
            //새로운 유저
        User_Info_Array[User_Info_Array.length] = 
            {
                UserId : userid,
                UserPapagoLanguage : 'en'
            }
            return User_Info_Array.length-1;
        }
    }
}

function Detect_Papago_Language_Change (TransToKoreanMessage, User_Location)
//번역 언어 변경 감지
{
    console.log('user의 정보는',User_Info_Array[User_Location]);
    for(var i in Language_Detect_Array) // Detect Language change 
    {
        if (TransToKoreanMessage == Language_Detect_Array[i].Message)
        {
            //언어 변경 감지o
            User_Info_Array[User_Location].UserPapagoLanguage = Language_Detect_Array[i].PapagoLanguage;
            return 0;
            break;
        }
        else if ( i == Language_Detect_Array.length-1)
        {
            //언어 변경 감지x
            return 1;
        }
    }
}

  app.listen(3000, function () {
    console.log('Linebot listening on port 3000!');
  });