[add] 機智問答

This commit is contained in:
建喵 2021-03-22 19:58:40 +08:00
parent ea46097ae9
commit f29639106e
4 changed files with 128 additions and 18 deletions

View File

@ -1,8 +1,11 @@
const dateFormat = require('dateformat');
/** Message */
class MessageClass {
constructor(bot, JianMiaubot) {
constructor(bot, JianMiaubot, Tools_MYSQLDB) {
this.bot = bot;
this.JianMiaubot = JianMiaubot;
this.Tools_MYSQLDB = Tools_MYSQLDB;
}
Message(event) {
@ -76,12 +79,13 @@ class MessageClass {
let userId = event.source.userId;
let replyMsg = event.message.text;
let displayName = "";
let datetime = dateFormat(new Date(), "yyyy-mm-dd HH:MM:ss");
let profile = await this.bot.getUserProfile(userId);
if (profile) {
displayName = profile.displayName;
}
// JianMiau特別功能
if (userId === process.env.toJianMiau || userId === process.env.toZhuHan) {
if (userId === process.env.toZhuHantoJianMiau || userId === process.env.toZhuHantoZhuHan) {
/** 訊息 */
let Msg = event.message.text.split(" ");
@ -112,18 +116,54 @@ class MessageClass {
// 當訊息回傳失敗後的處理
});
}
break;
return;
}
default: {
let Query = `SELECT * FROM \`line-cost-status\` WHERE \`userId\` = '${userId}' LIMIT 1;`;
let res_Query = await this.Tools_MYSQLDB.Query(Query);
let Data = res_Query;
let Status = Data[0]['Status'];
switch (Status) {
case "Love_Pig_QA OK": {
let Extra = JSON.parse(Data[0]["Extra"]);
let answer = false;
let keyword = Extra["keyword"].split(",");
for (let i = 0; i < keyword.length; i++) {
if (!keyword[i] || event.message.text.indexOf(keyword[i]) !== -1) {
answer = true;
}
}
if (answer) {
replyMsg = "答對, 答案就是:";
} else {
replyMsg = "答錯, 正確答案是:";
}
replyMsg += "\n" + Extra["answer"];
Query = `UPDATE \`line-cost-status\` SET \`datetime\`='${datetime}', \`Status\`='', \`Extra\`='' WHERE (\`userId\`='${userId}');`;
res_Query = await this.Tools_MYSQLDB.Query(Query);
event.reply(replyMsg).then(function (data) {
// 當訊息成功回傳後的處理
}).catch(function (error) {
// 當訊息回傳失敗後的處理
});
return;
}
default:
break;
}
break;
}
}
if (replyMsg !== "") {
replyMsg = event.message.text;
// 使用event.reply(要回傳的訊息)方法可將訊息回傳給使用者
event.reply(replyMsg).then(function (data) {
// 當訊息成功回傳後的處理
}).catch(function (error) {
// 當訊息回傳失敗後的處理
});
break;
}
}
}
}

64
Tools_MYSQLDBClass.js Normal file
View File

@ -0,0 +1,64 @@
const mysql = require('mysql');
/** Tools_MYSQLDB */
class Tools_MYSQLDBClass {
constructor() {
let config = {
host: 'jianmiau.tk',
user: 'jianmiau',
password: 'VQ*ZetC7xcc9%dTW',
database: 'line-cost-php',
port: 3307
};
this.conn = new mysql.createConnection(config);
this.conn.connect(
function (err) {
if (err) {
console.log("!!! Cannot connect !!! Error:");
throw err;
}
else {
console.log("Connection established.");
}
});
}
Query(Query) {
return new Promise((resolve, reject) => {
this.conn.query(Query,
function (err, results, fields) {
if (err) {
reject(err);
}
resolve(results);
});
})
}
CloseDB() {
this.conn.end(
function (err) {
if (err) throw err;
else console.log('Closing connection.')
});
}
// readData() {
// this.conn.query('SELECT * FROM `LoveZhuHan` LIMIT 2',
// function (err, results, fields) {
// if (err) throw err;
// else console.log('Selected ' + results.length + ' row(s).');
// for (let i = 0; i < results.length; i++) {
// console.log('Row: ' + JSON.stringify(results[i]));
// }
// console.log('Done.');
// });
// // this.conn.end(
// // function (err) {
// // if (err) throw err;
// // else console.log('Closing connection.')
// // });
// }
}
module.exports = Tools_MYSQLDBClass

20
app.js
View File

@ -3,11 +3,10 @@
// Debug node --inspect=192.168.168.15:9229 app.js
require('dotenv').config()
// require("./plug/DateFormat");
// 引用linebot SDK
var linebot = require('linebot');
const fs = require('fs');
const express = require('express');
const app = express();
//讀取憑證及金鑰
const prikey = fs.readFileSync('privkey.pem', 'utf8');
@ -33,8 +32,15 @@ var JianMiaubot = linebot({
channelAccessToken: process.env.channelAccessToken
});
const MessageClass = require('./MessageClass')
const Message = new MessageClass(bot, JianMiaubot);
const Tools_MYSQLDBClass = require('./Tools_MYSQLDBClass');
const MessageClass = require('./MessageClass');
const Tools_MYSQLDB = new Tools_MYSQLDBClass();
const Message = new MessageClass(bot, JianMiaubot, Tools_MYSQLDB);
// Bot所監聽的webhook路徑與port
const path = process.env.URLPATH || "/";
const port = process.env.PORT || 3001;
// 當有人傳送訊息給Bot時
bot.on('event', function (event) {
@ -57,10 +63,8 @@ bot.on('event', function (event) {
break;
}
});
// Bot所監聽的webhook路徑與port
const port = process.env.PORT || 3000;
bot.listen('/linewebhook', port, credentials, function () {
bot.listen(path, port, credentials, function () {
console.log(`listening on ${port}`);
console.log('[BOT已準備就緒]');
// Tools_MYSQLDB.readData();
});

View File

@ -4,9 +4,11 @@
"description": "",
"main": "app.js",
"dependencies": {
"dateformat": "^4.5.1",
"dotenv": "^8.2.0",
"express": "^4.17.1",
"linebot": "^1.6.1"
"linebot": "^1.6.1",
"mysql": "^2.18.1"
},
"devDependencies": {
"nodemon": "^2.0.7"