app.js 11.3 KB
var express = require('express');
const request = require('request');
const TARGET_URL = 'https://api.line.me/v2/bot/message/reply'
const TOKEN = 'P5+e9JkPRckzKu1Fv7ghZl1MfP0wrYwYcgBVzHWe1OHO4Gtv1PIa9BARYqxoAThaXPSf8MyVKcpDE88V5jOnoS4o2xCNcgH9Ne4wcrPuNX6AT4gsfYEz0Y7n/A4+rT4vXHYARK34YPbkzzQbiXiyiQdB04t89/1O/w1cDnyilFU='
const fs = require('fs');
const path = require('path');
const HTTPS = require('https');
const domain = "2020105659.osschatbot.cf"
const sslport = 23023;

//Open API
const STDICT_URL = 'https://stdict.korean.go.kr/api/search.do'
const STDICT_KEY = '14AA284251F616FF2151DBE4CD7B3D4C'

//Webhook
const bodyParser = require('body-parser');
const { json } = require('body-parser');
const { start } = require('repl');
const { exit } = require('process');
const { callbackify } = require('util');
var app = express();
app.use(bodyParser.json());
app.post('/hook', function (req, res) {

  var eventObj = req.body.events[0];
  var source = eventObj.source;
  var message = eventObj.message;

  // request log
  console.log('======================', new Date() ,'======================');
  console.log('[request]', req.body);
  console.log('[request source] ', source);
  console.log('[request message]', message);


  wordchain(eventObj.replyToken, message.text, source.userId);


  res.sendStatus(200);
});

var playingId = [];
var words = [];

function getIdindex(userId) {
  return playingId.indexOf(userId);
}
function exit_(userId) {
  var index = getIdindex(userId);
  playingId.splice(index, 1);
  words.splice(index, 1);
}
function isCommand(message)
{
		return message == '/시작' || message == '/종료' ? true : false;
}
function all_check(replyToken, userId, word, index) {
  if(words[index] != 0) {
    if(!check_endtoend(word, index)) {
      request.post(
        {
          url: TARGET_URL,
          headers: {
            'Authorization': `Bearer ${TOKEN}`
          },
          json: {
            "replyToken":replyToken,
            "messages":[
              {
                "type":"text",
                "text":"끝음절로 시작해야합니다."
              },
              {
                "type":"text",
                "text":"패배했습니다."
              }
            ]
          }
        },(error, response, body) => {
          console.log(body);
        });
        exit_(userId);
        return false;
    } else if(!check_length(word)) {
      request.post(
        {
          url: TARGET_URL,
          headers: {
            'Authorization': `Bearer ${TOKEN}`
          },
          json: {
            "replyToken":replyToken,
            "messages":[
              {
                "type":"text",
                "text":"한 글자 단어입니다."
              },
              {
                "type":"text",
                "text":"패배했습니다."
              }
            ]
          }
        },(error, response, body) => {
          console.log(body);
        });
        exit_(userId);
        return false;
    } else {
      var uncondition = 0;
      if(uncondition == 0) {
        request.post(
        {
          url: STDICT_URL,
          headers: {
            'Referer': 'https://stdict.korean.go.kr/api/search.do',
            'Content-Type': 'application/x-www-form-urlencoded'
          },
          body: `key=14AA284251F616FF2151DBE4CD7B3D4C&` + `q=${word}&` + 'req_type=json&' + 'advanced=y&' + 'method=exact&' + 'type1=word'
    
        },(error, response, body) => {
          if(!error && response.statusCode == 200) {
              try {console.log(body);
                const parsedData = JSON.parse(body);
                num = parsedData.channel.total; 
                console.log(num);
              } catch (error) {
                console.log("없는 단어");
                {
                  request.post(
                    {
                      url: TARGET_URL,
                      headers: {
                        'Authorization': `Bearer ${TOKEN}`
                      },
                      json: {
                        "replyToken":replyToken,
                        "messages":[
                          {
                            "type":"text",
                            "text":"없는 단어입니다."
                          },
                          {
                            "type":"text",
                            "text":"패배했습니다."
                          }
                        ]
                      }
                    },(error, response, body) => {
                      console.log(body);
                    });
                    exit_(userId);
                    return false;
                  }
              }
          }
          
        });
        
      }
    }
  } else {
    if(!check_length(word)) {
      request.post(
        {
          url: TARGET_URL,
          headers: {
            'Authorization': `Bearer ${TOKEN}`
          },
          json: {
            "replyToken":replyToken,
            "messages":[
              {
                "type":"text",
                "text":"한 글자 단어입니다."
              },
              {
                "type":"text",
                "text":"패배했습니다."
              }
            ]
          }
        },(error, response, body) => {
          console.log(body);
        });
        exit_(userId);
        return false;
    } else {
      var uncondition = 0;
      if(uncondition == 0) {
        request.post(
        {
          url: STDICT_URL,
          headers: {
            'Referer': 'https://stdict.korean.go.kr/api/search.do',
            'Content-Type': 'application/x-www-form-urlencoded'
          },
          body: `key=14AA284251F616FF2151DBE4CD7B3D4C&` + `q=${word}&` + 'req_type=json&' + 'advanced=y&' + 'method=exact&' + 'type1=word'
    
        },(error, response, body) => {
          if(!error && response.statusCode == 200) {
              try {console.log(body);
                const parsedData = JSON.parse(body);
                var num = parsedData.channel.total; 
                console.log(num); 
              } catch (error) {
                console.log("없는 단어");
                {
                  request.post(
                    {
                      url: TARGET_URL,
                      headers: {
                        'Authorization': `Bearer ${TOKEN}`
                      },
                      json: {
                        "replyToken":replyToken,
                        "messages":[
                          {
                            "type":"text",
                            "text":"없는 단어입니다."
                          },
                          {
                            "type":"text",
                            "text":"패배했습니다."
                          }
                        ]
                      }
                    },(error, response, body) => {
                      console.log(body);
                    });
                    exit_(userId);
                    return false;
                  }
              }
          }
          
        });
        
      }
    }
  }
  return true;
}
function check_endtoend(word, index) {
    return word.slice(0, 1) == words[index].slice(-1);
}
function check_exist(word) {
    
}
function check_length(word) {
  return word.length != 1;
}

function wordchain(replyToken, message, userId) {
  if (isCommand(message)){

    if(message == '/시작') {
    playingId.push(userId);
    words.push(0);
    request.post(
      {
          url: TARGET_URL,
          headers: {
              'Authorization': `Bearer ${TOKEN}`
          },
          json: {
              "replyToken":replyToken,
              "messages":[
                  {
                      "type":"text",
                      "text": "게임이 시작되었습니다.\n단어를 제시해주세요."
                  }
              ]
          }
      },(error, response, body) => {
          console.log(body);
      });
    } else {
      request.post(
        {
            url: TARGET_URL,
            headers: {
                'Authorization': `Bearer ${TOKEN}`
            },
            json: {
                "replyToken":replyToken,
                "messages":[
                    {
                        "type":"text",
                        "text": "게임이 종료되었습니다."
                    }
                ]
            }
        },(error, response, body) => {
            console.log(body);
        });
      exit_(userId);
    };
  } else {

    if(!playingId.includes(userId)) {
      request.post(
         {
          url: TARGET_URL,
          headers: {
              'Authorization': `Bearer ${TOKEN}`
          },
          json: {
              "replyToken":replyToken,
              "messages":[
                  {
                      "type":"text",
                      "text": "안녕하세요. 끝말잇기봇입니다.\n-표준어 내의 명사만 가능\n\t(표준국어대사전에 근거)\n-한 글자 단어 금지\n시작: '/시작', 종료: '/종료' 입력"
                  }
              ]
          }
      },(error, response, body) => {
          console.log(body);
      });
    } else {

      var word = message;
      index = getIdindex(userId);

      if(all_check(replyToken, userId, word, index)) {
        let letter = word.slice(-1);

        request.post(
        {
          url: STDICT_URL,
          headers: {
            'Referer': 'https://stdict.korean.go.kr/api/search.do',
            'Content-Type': 'application/x-www-form-urlencoded'
          },
          body: `key=14AA284251F616FF2151DBE4CD7B3D4C&` + `q=${letter}&` + 'req_type=json&' + 'advanced=y&' + 'method=start&' + 'type1=word&' + 'letter_s=2'

        },(error, response, body) => {
          if(!error && response.statusCode == 200) {
              console.log(body);
              const parsedData = JSON.parse(body);
              var nextword = parsedData.channel.item[0].word;
              var word_definition = parsedData.channel.item[0].sense.definition;
              words.splice(getIdindex(userId), 1, nextword);
  
              request.post(
                      {
                      url: TARGET_URL,
                      headers: {
                          'Authorization': `Bearer ${TOKEN}`
                      },
                      json: {
                          "replyToken":replyToken,
                          "messages":[
                              {
                                  "type":"text",
                                  "text":nextword + ': ' + word_definition
                              }
                          ]
                      }
                  },(error, response, body) => {
                      console.log(body);
                  });
          }
        });
      }
     }
    
  }
}

//SSL
try {
    const option = {
      ca: fs.readFileSync('/etc/letsencrypt/live/' + domain +'/fullchain.pem'),
      key: fs.readFileSync(path.resolve(process.cwd(), '/etc/letsencrypt/live/' + domain +'/privkey.pem'), 'utf8').toString(),
      cert: fs.readFileSync(path.resolve(process.cwd(), '/etc/letsencrypt/live/' + domain +'/cert.pem'), 'utf8').toString(),
    };
  
    HTTPS.createServer(option, app).listen(sslport, () => {
      console.log(`[HTTPS] Server is started on port ${sslport}`);
    });
  } catch (error) {
    console.log('[HTTPS] HTTPS 오류가 발생하였습니다. HTTPS 서버는 실행되지 않습니다.');
    console.log(error);
  }