app.js 1.86 KB
const express = require('express');
const app = express();
const mysql = require('mysql2/promise');
const axios = require('axios').default;
const bodyParser = require('body-parser');

app.use(bodyParser.json());

const channelToken = 'Bearer ZVI571ynUAVT0U44734ziyjVtStYiUi2UA4txCgVUvugv5YQwToMDgE991Sd4UbsZtJpBhXEtQKX/YkvQVx0PgH9F7qy75eUR0iKMwz33RXD5BG8JuFZ67FqR/GXZQNSk+kXHMBVnCQPeeNqTNn5MgdB04t89/1O/w1cDnyilFU=';

const pool = mysql.createPool({
    host: 'localhost',
    user: 'root',
    password: '0712',
    database: 'tft'
});

app.post('/messages', function(req, res) {
    for(let event of req.body.events) {
        if(event.type == 'message')
            onMessage(event.message, event.replyToken);
    }

    res.sendStatus(200);
});

function onMessage(message, replyToken) {
    if(message.type != 'text')
        return;
    
    if(message.text.indexOf('아이템') >= 0)
        recommendItem(message.text.split(' ')[0], replyToken);
    
    
}

function recommendItem(charAlias, replyToken) {
    let sql = 'SELECT n.`alias`, i.`name` FROM `character_aliases` a JOIN `character_items` c ON a.`character_id`=c.`character_id` JOIN `character_aliases` n ON c.`character_id`=n.`character_id` JOIN `items` i ON c.`item`=i.`id` WHERE a.`alias`=? AND n.`is_name`=1 ORDER BY c.`count` DESC LIMIT 0,5';
    pool.query(sql, [charAlias]).then(function([results]) {
        let reply;
        if(results.length == 0)
            reply = '데이터가 없습니다.';
        else
            reply = `${results[0].alias}의 추천 아이템은 ${results.map(e => e.name).join(', ')} 입니다.`;

        axios.post('https://api.line.me/v2/bot/message/reply', {
            replyToken: replyToken,
            messages: [{type: 'text', text: reply}]
        }, {
            headers: {'Authorization': channelToken}
        });
    });
}

app.listen(3000, () => console.log('TFT Chatbot started'));