[add] CPBL功能

[add] Postback
This commit is contained in:
建喵 2021-04-24 21:18:34 +08:00
parent 79d240ed2e
commit a9ff89d8b8
7 changed files with 581 additions and 63 deletions

347
CPBLClass.js Normal file
View File

@ -0,0 +1,347 @@
const dateFormat = require('dateformat');
const XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
const schedule = require('node-schedule');
const { decode } = require('querystring');
/** CPBL */
class CPBLClass {
constructor(app) {
this.app = app;
this.TimeList = [];
// var rule = new schedule.RecurrenceRule();
// // rule.minute = [0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55];
// rule.second = [0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55];
// // console.log(`設定任務 每${JSON.stringify(rule.minute)}分鐘 現在時間: ` + dateFormat(new Date(), "yyyy-mm-dd HH:MM:ss"));
// console.log(`設定任務 每${JSON.stringify(rule.second)}秒鐘 現在時間: ` + dateFormat(new Date(), "yyyy-mm-dd HH:MM:ss"));
// this.Timer = schedule.scheduleJob(rule, this.Update.bind(this));
}
async Update() {
// let datetime = dateFormat(new Date(), "yyyy-mm-dd HH:MM:ss");
// console.log("執行任務 現在時間: " + datetime);
// if (dateFormat(new Date(), "ss") === "00") {
// this.Timer.cancel();
// // console.log("取消任務 現在時間: " + datetime);
// }
if (this.TimeList.length > 0) {
for (let i = 0; i < this.TimeList.length; i++) {
this.RunTime(this.TimeList[i]);
}
} else {
this.CloseTime();
}
}
async AddTime(Data, event) {
let game_id = Data["game_id"];
let cpbldata = Data["cpbldata"];
let LineID = Data["LineID"];
let Isgame_id = false;
let IsLineID = false;
let Time = {
game_id: game_id,
cpbldata: cpbldata,
LineID: [LineID]
}
for (let i = 0; i < this.TimeList.length; i++) {
if (this.TimeList[i]["game_id"] === game_id) {
Isgame_id = true;
Time = this.TimeList[i];
for (let j = 0; j < this.TimeList[i]["LineID"].length; j++) {
if (this.TimeList[i]["LineID"][j] === LineID) {
IsLineID = true;
break;
}
}
break;
}
}
let IsRUN = true;
let Response = await this.GetCPBL(Time);
if (Response[Response.length - 1]["title"].indexOf("比賽結束") !== -1) {
IsRUN = false;
}
let replyMsg = "";
for (let i = 0; i < Response.length; i++) {
replyMsg += Response[i]["title"];
if (i !== Response.length - 1) {
replyMsg += "\n\n";
}
}
if (IsRUN) {
if (!Isgame_id) {
// 沒有這場賽事
if (this.TimeList.length === 0) {
this.StartTime();
}
this.TimeList.push(Time);
} else if (Isgame_id && !IsLineID) {
// 有這場賽事但沒這個帳號
Time["LineID"].push(LineID);
}
let Extra = {
cpbldata: cpbldata,
count: Response.length
}
let datetime = dateFormat(new Date(), "yyyy-mm-dd HH:MM:ss");
let Query = `UPDATE \`line-cost-status\` SET \`datetime\`='${datetime}', \`Status\`='CPBL RUN', \`Extra\`='${JSON.stringify(Extra)}' WHERE (\`userid\`='${LineID}');`;
let res_Query = await this.app.Tools_MYSQLDB.Query(Query);
} else {
replyMsg += "\n\n已停止中職轉播功能";
}
if (event) {
event.reply(replyMsg).then(function (data) {
// 當訊息成功回傳後的處理
}).catch(function (error) {
// 當訊息回傳失敗後的處理
});
}
}
StartTime() {
// var rule = '0 1 * * * *';
// * * * * * *
// ┬ ┬ ┬ ┬ ┬ ┬
// │ │ │ │ │ |
// │ │ │ │ │ └ 星期几取值0 - 7其中 0 和 7 都表示是周日
// │ │ │ │ └─── 月份取值1 - 12
// │ │ │ └────── 日期取值1 - 31
// │ │ └───────── 时取值0 - 23
// │ └──────────── 分取值0 - 59
// └─────────────── 秒取值0 - 59可选
var rule = new schedule.RecurrenceRule();
let minute = 2;
let minute_arr = [];
for (let i = 0; i < 60; i++) {
if (i % minute === 0) {
minute_arr.push(i);
}
}
rule.minute = minute_arr;
// rule.second = [0];
// rule.second = [0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55];
// console.log(`設定任務 每${JSON.stringify(rule.minute)}分鐘 現在時間: ` + dateFormat(new Date(), "yyyy-mm-dd HH:MM:ss"));
// console.log(`設定任務 每${JSON.stringify(rule.second)}秒鐘 現在時間: ` + dateFormat(new Date(), "yyyy-mm-dd HH:MM:ss"));
this.Timer = schedule.scheduleJob(rule, this.Update.bind(this));
}
CloseTime() {
this.Timer.cancel();
}
async GetCPBL(Time) {
let game_id = Time["game_id"];
let cpbldata = Time["cpbldata"];
let LineID = Time["LineID"];
let url = "https://jianmiau.ml:3333/CPBL";
let Data = {
URL: `http://www.cpbl.com.tw/games/play_by_play.html?&game_type=${cpbldata["game_type"]}&game_id=${cpbldata["game_id"]}&game_date=${cpbldata["game_date"]}&pbyear=${cpbldata["pbyear"]}`
};
let Response = await this.GetData(url, Data);
Response = [].concat.apply([], JSON.parse(Response));
return new Promise((resolve, reject) => {
// 傳入 resolve 與 reject表示資料成功與失敗
resolve(Response);
// reject()
});
}
DelTime(game_id) {
for (let i = 0; i < this.TimeList.length; i++) {
if (this.TimeList[i]["game_id"] === game_id) {
this.TimeList.splice(i, 1);
if (this.TimeList.length === 0) {
this.CloseTime();
}
}
}
}
async RunTime(Time) {
let game_id = Time["game_id"];
let cpbldata = Time["cpbldata"];
let LineID = Time["LineID"];
let url = "https://jianmiau.ml:3333/CPBL";
let Data = {
URL: `http://www.cpbl.com.tw/games/play_by_play.html?&game_type=${cpbldata["game_type"]}&game_id=${cpbldata["game_id"]}&game_date=${cpbldata["game_date"]}&pbyear=${cpbldata["pbyear"]}`
};
let Response = await this.GetData(url, Data);
Response = [].concat.apply([], JSON.parse(Response));
let IsRUN = true;
if (Response[Response.length - 1]["title"].indexOf("比賽結束") !== -1 || Response[Response.length - 1]["title"].indexOf("final") !== -1) {
IsRUN = false;
}
for (let i = 0; i < LineID.length; i++) {
let Query = `SELECT * FROM \`line-cost-status\` WHERE \`userId\` = '${LineID[i]}' LIMIT 1;`;
let res_Query = await this.app.Tools_MYSQLDB.Query(Query);
let Data = res_Query;
let Status = Data[0]['Status'];
if (Status === "CPBL RUN") {
let Extra = JSON.parse(Data[0]["Extra"]);
let cpbldata = Extra["cpbldata"];
let count = Extra["count"];
if (Response.length > count) {
let replyMsg = "";
for (let j = count; j < Response.length; j++) {
replyMsg += Response[j]["title"];
if (j !== Response.length - 1) {
replyMsg += "\n\n";
}
}
if (IsRUN) {
let Extra = {
cpbldata: cpbldata,
count: Response.length
}
let datetime = dateFormat(new Date(), "yyyy-mm-dd HH:MM:ss");
let Query = `UPDATE \`line-cost-status\` SET \`datetime\`='${datetime}', \`Status\`='CPBL RUN', \`Extra\`='${JSON.stringify(Extra)}' WHERE (\`userid\`='${LineID[i]}');`;
let res_Query = await this.app.Tools_MYSQLDB.Query(Query);
} else {
let datetime = dateFormat(new Date(), "yyyy-mm-dd HH:MM:ss");
let Query = `UPDATE \`line-cost-status\` SET \`datetime\`='${datetime}', \`Status\`='', \`Extra\`='' WHERE (\`userid\`='${LineID[i]}');`;
let res_Query = await this.app.Tools_MYSQLDB.Query(Query);
replyMsg += "\n\n已停止中職轉播功能";
}
let res_Msg = this.app.bot.push(LineID[i], replyMsg);
}
}
}
if (!IsRUN) {
this.DelTime(game_id);
}
}
async GetCPBLList(Date) {
// let game_id = Time["game_id"];
// let cpbldata = Time["cpbldata"];
// let LineID = Time["LineID"];
let url = "https://jianmiau.ml:3333/CPBLList";
let Data = {
Date: Date
};
let Response = await this.GetData(url, Data);
Response = [].concat.apply([], JSON.parse(Response));
let columns = [];
for (let i = 0; i < Response.length; i++) {
let img = [];
let team = [];
let data = "";
let href = Response[i]["href"];
for (let j = 1; j <= 2; j++) {
if (Response[i][`img${j}`].indexOf("AJL011_logo_01") !== -1) {
img.push("https://jianmiau.ml/MyWeb/Resources/CPBL/R.png");
team.push("樂天桃猿");
} else if (Response[i][`img${j}`].indexOf("B04_logo_01") !== -1) {
img.push("https://jianmiau.ml/MyWeb/Resources/CPBL/F.png");
team.push("富邦悍將");
} else if (Response[i][`img${j}`].indexOf("D01_logo_01") !== -1) {
img.push("https://jianmiau.ml/MyWeb/Resources/CPBL/D.png");
team.push("味全龍");
} else if (Response[i][`img${j}`].indexOf("E02_logo_01") !== -1) {
img.push("https://jianmiau.ml/MyWeb/Resources/CPBL/B.png");
team.push("中信兄弟");
} else if (Response[i][`img${j}`].indexOf("L01_logo_01") !== -1) {
img.push("https://jianmiau.ml/MyWeb/Resources/CPBL/L.png");
team.push("統一獅");
}
}
if (href["time"]) {
data = `action=nogame&game_type=${href["game_type"]}&game_id=${href["game_id"]}&game_date=${href["game_date"]}&pbyear=${href["game_date"].substr(0, 4)}&time=${href["time"]}`;
} else {
data = `action=hasgame&game_type=${href["game_type"]}&game_id=${href["game_id"]}&game_date=${href["game_date"]}&pbyear=${href["game_date"].substr(0, 4)}`;
}
let url = `http://www.cpbl.com.tw/games/play_by_play.html?&game_type=${href["game_type"]}&game_id=${href["game_id"]}&game_date=${href["game_date"]}&pbyear=${href["game_date"].substr(0, 4)}`;
let Data_columns = {
"thumbnailImageUrl": img[0],
"imageBackgroundColor": "#FFFFFF",
"title": `${team[0]} VS ${team[1]}`,
"text": `比賽場地 ${Response[i]["address"]} ${href["game_date"]}`,
"defaultAction": {
"type": "uri",
"label": "比賽網站",
"uri": url
},
"actions": [
{
"type": "postback",
"label": "追蹤比賽",
"data": data
}
]
};
columns.push(Data_columns);
}
// columns = [
// {
// "thumbnailImageUrl": "https://jianmiau.ml/MyWeb/Resources/CPBL/L.png",
// "imageBackgroundColor": "#FFFFFF",
// "title": "this is menu",
// "text": "description",
// "defaultAction": {
// "type": "uri",
// "label": "View detail",
// "uri": "http://example.com/page/123"
// },
// "actions": [
// {
// "type": "postback",
// "label": "Buy",
// "data": "action=buy&itemid=111"
// }
// ]
// },
// {
// "thumbnailImageUrl": "https://jianmiau.ml/MyWeb/Resources/CPBL/B.png",
// "imageBackgroundColor": "#000000",
// "title": "this is menu",
// "text": "description",
// "defaultAction": {
// "type": "uri",
// "label": "View detail",
// "uri": "http://example.com/page/222"
// },
// "actions": [
// {
// "type": "postback",
// "label": "Buy",
// "data": "action=buy&itemid=222"
// }
// ]
// }
// ]
return new Promise((resolve, reject) => {
// 傳入 resolve 與 reject表示資料成功與失敗
resolve(columns);
// reject()
});
}
/**
* 取得表
* @param Url Url
* @param arrange 是否需要整理
*/
GetData(Url, Data) {
return new Promise((resolve, reject) => {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status >= 200 && xhr.status < 400) {
var response = xhr.responseText;
resolve(response);
} else {
reject("");
}
}
};
xhr.open("POST", Url, true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.send(JSON.stringify(Data));
});
}
}
module.exports = CPBLClass

58
LineBotClass.js Normal file
View File

@ -0,0 +1,58 @@
// 背景執行 forever start -a -l line-cost-js.log app.js
// npm start
// npm run dev
// Debug nodemon --inspect=192.168.168.15:9229 app.js
const dateFormat = require('dateformat');
const { decode } = require('querystring');
const Tools_MYSQLDBClass = require('./Tools_MYSQLDBClass');
const MessageClass = require('./MessageClass');
const PostbackClass = require('./PostbackClass');
const CPBLClass = require('./CPBLClass');
/** LineBot */
class LineBotClass {
constructor(path, port, credentials, bot, JianMiaubot) {
let self = this;
this.bot = bot;
this.JianMiaubot = JianMiaubot;
this.Tools_MYSQLDB = new Tools_MYSQLDBClass();
this.Message = new MessageClass(this);
this.Postback = new PostbackClass(this);
this.CPBL = new CPBLClass(this);
// 當有人傳送訊息給Bot時
bot.on('event', function (event) {
switch (event.type) {
case 'message': {
self.Message.Message(event);
break;
}
case 'postback': {
self.Postback.Postback(event);
break;
}
case 'join':
case 'leave':
case 'follow':
case 'unfollow':
case 'memberJoin':
case 'memberLeave':
case 'accountLink':
case 'fallback':
default:
break;
}
});
bot.listen(path, port, credentials, function () {
let datetime = dateFormat(new Date(), "yyyy-mm-dd HH:MM:ss");
console.log(`${datetime} listening on ${port}`);
console.log(`${datetime} [BOT已準備就緒]`);
// Tools_MYSQLDB.readData();
});
}
}
module.exports = LineBotClass

View File

@ -1,11 +1,21 @@
const dateFormat = require('dateformat'); const dateFormat = require('dateformat');
const { decode } = require('querystring');
/** Message */ /** Message */
class MessageClass { class MessageClass {
constructor(bot, JianMiaubot, Tools_MYSQLDB) { constructor(app) {
this.bot = bot; this.app = app;
this.JianMiaubot = JianMiaubot; // this.app.CPBL.AddTime({
this.Tools_MYSQLDB = Tools_MYSQLDB; // game_id: 64,
// cpbldata: {
// "http://www.cpbl.com.tw/games/play_by_play.html?": "",
// game_type: "01",
// game_id: "63",
// game_date: "2021-04-20",
// pbyear: "2021",
// },
// LineID: 1
// });
} }
Message(event) { Message(event) {
@ -45,7 +55,7 @@ class MessageClass {
case "user": { case "user": {
let userId = event.source.userId; let userId = event.source.userId;
let displayName = ""; let displayName = "";
let profile = await this.bot.getUserProfile(userId); let profile = await this.app.bot.getUserProfile(userId);
if (profile) { if (profile) {
displayName = profile.displayName; displayName = profile.displayName;
} }
@ -54,10 +64,10 @@ class MessageClass {
//ToJianMiau------------------------------------------------------------------------------------------------------ //ToJianMiau------------------------------------------------------------------------------------------------------
if (userId !== process.env.toZhuHantoJianMiau) { if (userId !== process.env.toZhuHantoJianMiau) {
let ToJM_message = "已接收訊息:"; let ToJM_message = "已接收訊息:";
ToJM_message += "\ndisplayName: $displayName"; ToJM_message += `\ndisplayName: ${displayName}`;
ToJM_message += "\nuserId: $userId"; ToJM_message += `\nuserId: ${userId}`;
ToJM_message += "\n" + replyMsg; ToJM_message += "\n" + replyMsg;
let res_toJianMiau = this.JianMiaubot.push(process.env.toJianMiau, ToJM_message); let res_toJianMiau = this.app.JianMiaubot.push(process.env.toJianMiau, ToJM_message);
} }
let res_reply = event.reply(replyMsg).then(function (data) { let res_reply = event.reply(replyMsg).then(function (data) {
// 當訊息成功回傳後的處理 // 當訊息成功回傳後的處理
@ -80,7 +90,7 @@ class MessageClass {
let replyMsg = event.message.text; let replyMsg = event.message.text;
let displayName = ""; let displayName = "";
let datetime = dateFormat(new Date(), "yyyy-mm-dd HH:MM:ss"); let datetime = dateFormat(new Date(), "yyyy-mm-dd HH:MM:ss");
let profile = await this.bot.getUserProfile(userId); let profile = await this.app.bot.getUserProfile(userId);
if (profile) { if (profile) {
displayName = profile.displayName; displayName = profile.displayName;
} }
@ -91,7 +101,7 @@ class MessageClass {
ToJM_message += `\ndisplayName: ${displayName}`; ToJM_message += `\ndisplayName: ${displayName}`;
ToJM_message += `\nuserId: ${userId}`; ToJM_message += `\nuserId: ${userId}`;
ToJM_message += `\nmessage: ${replyMsg}`; ToJM_message += `\nmessage: ${replyMsg}`;
let res_toJianMiau = this.JianMiaubot.push(process.env.toJianMiau, ToJM_message); let res_toJianMiau = this.app.JianMiaubot.push(process.env.toJianMiau, ToJM_message);
} }
// JianMiau特別功能 // JianMiau特別功能
@ -115,7 +125,7 @@ class MessageClass {
for (let i = 2; i < Msg.length; i++) { for (let i = 2; i < Msg.length; i++) {
replyMsg += Msg[i] + (i === Msg.length - 1 ? "" : " "); replyMsg += Msg[i] + (i === Msg.length - 1 ? "" : " ");
} }
let res_Msg = this.bot.push(Msg[1], replyMsg); let res_Msg = this.app.bot.push(Msg[1], replyMsg);
let ToJM_message = "已發送訊息:"; let ToJM_message = "已發送訊息:";
ToJM_message += `\nuserId: ${Msg[1]}`; ToJM_message += `\nuserId: ${Msg[1]}`;
@ -129,9 +139,35 @@ class MessageClass {
return; return;
} }
case "中職": {
let URL = Msg[1];
let Isplay_by_play = URL.indexOf("play_by_play");
let data = decode(URL);
if (Isplay_by_play === -1 || !data["game_id"]) {
return;
}
this.app.CPBL.AddTime({
game_id: data["game_id"],
cpbldata: data,
LineID: userId
}, event);
return;
}
case "今日賽事":
case "我愛建喵今日賽事": {
let columns = await this.app.CPBL.GetCPBLList(Msg[1] ? Msg[1] : dateFormat(new Date(), "yyyymmdd"));
let res_reply = event.replyimagemap("建喵也愛你", columns).then(function (data) {
// 當訊息成功回傳後的處理
}).catch(function (error) {
// 當訊息回傳失敗後的處理
});
return;
}
default: { default: {
let Query = `SELECT * FROM \`line-cost-status\` WHERE \`userId\` = '${userId}' LIMIT 1;`; let Query = `SELECT * FROM \`line-cost-status\` WHERE \`userId\` = '${userId}' LIMIT 1;`;
let res_Query = await this.Tools_MYSQLDB.Query(Query); let res_Query = await this.app.Tools_MYSQLDB.Query(Query);
let Data = res_Query; let Data = res_Query;
let Status = Data[0]['Status']; let Status = Data[0]['Status'];
switch (Status) { switch (Status) {
@ -151,7 +187,7 @@ class MessageClass {
} }
replyMsg += "\n" + Extra["answer"]; replyMsg += "\n" + Extra["answer"];
Query = `UPDATE \`line-cost-status\` SET \`datetime\`='${datetime}', \`Status\`='', \`Extra\`='' WHERE (\`userId\`='${userId}');`; Query = `UPDATE \`line-cost-status\` SET \`datetime\`='${datetime}', \`Status\`='', \`Extra\`='' WHERE (\`userId\`='${userId}');`;
res_Query = await this.Tools_MYSQLDB.Query(Query); res_Query = await this.app.Tools_MYSQLDB.Query(Query);
event.reply(replyMsg).then(function (data) { event.reply(replyMsg).then(function (data) {
// 當訊息成功回傳後的處理 // 當訊息成功回傳後的處理
}).catch(function (error) { }).catch(function (error) {
@ -160,12 +196,33 @@ class MessageClass {
return; return;
} }
case "CPBL RUN": {
switch (Instruction) {
case "停止": {
replyMsg = "已停止中職轉播功能";
Query = `UPDATE \`line-cost-status\` SET \`datetime\`='${datetime}', \`Status\`='', \`Extra\`='' WHERE (\`userId\`='${userId}');`;
res_Query = await this.app.Tools_MYSQLDB.Query(Query);
event.reply(replyMsg).then(function (data) {
// 當訊息成功回傳後的處理
}).catch(function (error) {
// 當訊息回傳失敗後的處理
});
break;
}
default:
break;
}
return;
}
default: default:
break; break;
} }
break; break;
} }
} }
}
if (replyMsg !== "") { if (replyMsg !== "") {
replyMsg = event.message.text; replyMsg = event.message.text;
// 使用event.reply(要回傳的訊息)方法可將訊息回傳給使用者 // 使用event.reply(要回傳的訊息)方法可將訊息回傳給使用者
@ -177,6 +234,5 @@ class MessageClass {
} }
} }
} }
}
module.exports = MessageClass module.exports = MessageClass

49
PostbackClass.js Normal file
View File

@ -0,0 +1,49 @@
const dateFormat = require('dateformat');
const { decode } = require('querystring');
/** Postback */
class PostbackClass {
constructor(app) {
this.app = app;
}
Postback(event) {
let action = event.postback.data;
let data = decode(action);
switch (data["action"]) {
case 'nogame': {
this.NoGame(event, data);
break;
}
case 'hasgame': {
this.HasGame(event, data);
break;
}
default:
break;
}
}
NoGame(event, data) {
let replyMsg = `比賽還沒開始\n時間是${data["game_date"]} ${data["time"]}`;
if (event) {
event.reply(replyMsg).then(function (data) {
// 當訊息成功回傳後的處理
}).catch(function (error) {
// 當訊息回傳失敗後的處理
});
}
}
HasGame(event, data) {
this.app.CPBL.AddTime({
game_id: data["game_id"],
cpbldata: data,
LineID: event.source.userId
}, event);
}
}
module.exports = PostbackClass

View File

@ -1,8 +1,10 @@
const mysql = require('mysql'); const mysql = require('mysql');
const dateFormat = require('dateformat');
/** Tools_MYSQLDB */ /** Tools_MYSQLDB */
class Tools_MYSQLDBClass { class Tools_MYSQLDBClass {
constructor() { constructor() {
let datetime = dateFormat(new Date(), "yyyy-mm-dd HH:MM:ss");
let config = { let config = {
host: 'jianmiau.tk', host: 'jianmiau.tk',
user: 'jianmiau', user: 'jianmiau',
@ -14,11 +16,11 @@ class Tools_MYSQLDBClass {
this.conn.connect( this.conn.connect(
function (err) { function (err) {
if (err) { if (err) {
console.log("!!! Cannot connect !!! Error:"); console.log(`${datetime} !!! Cannot connect !!! Error:`);
throw err; throw err;
} }
else { else {
console.log("jianmiau.tk Connect."); console.log(`${datetime} jianmiau.tk Connect.`);
} }
}); });
} }
@ -39,7 +41,7 @@ class Tools_MYSQLDBClass {
this.conn.end( this.conn.end(
function (err) { function (err) {
if (err) throw err; if (err) throw err;
else console.log('Closing connection.') else console.log(`${datetime} Closing connection.`)
}); });
} }

71
app.js
View File

@ -1,6 +1,7 @@
// 背景執行 forever start -w -a -l line-cost-js.log app.js // 背景執行 forever start -a -l line-cost-js.log app.js
// 監聽檔案變化 nodemon "npm start" // npm start
// Debug node --inspect=192.168.168.15:9229 app.js // npm run dev
// Debug nodemon --inspect=192.168.168.15:9229 app.js
const dateFormat = require('dateformat'); const dateFormat = require('dateformat');
require('dotenv').config() require('dotenv').config()
@ -33,40 +34,42 @@ var JianMiaubot = linebot({
channelAccessToken: process.env.channelAccessToken channelAccessToken: process.env.channelAccessToken
}); });
const Tools_MYSQLDBClass = require('./Tools_MYSQLDBClass'); const LineBotAPI = require('./LineBotClass');
const MessageClass = require('./MessageClass');
const Tools_MYSQLDB = new Tools_MYSQLDBClass();
const Message = new MessageClass(bot, JianMiaubot, Tools_MYSQLDB);
// Bot所監聽的webhook路徑與port // Bot所監聽的webhook路徑與port
const path = process.env.URLPATH || "/"; const path = process.env.URLPATH || "/";
const port = process.env.PORT || 3001; const port = process.env.PORT || 3001;
// 當有人傳送訊息給Bot時 new LineBotAPI(path, port, credentials, bot, JianMiaubot);
bot.on('event', function (event) {
switch (event.type) {
case 'message': {
Message.Message(event);
break;
}
case 'join': // // 當有人傳送訊息給Bot時
case 'leave': // bot.on('event', function (event) {
case 'follow': // switch (event.type) {
case 'unfollow': // case 'message': {
case 'memberJoin': // Message.Message(event);
case 'memberLeave': // break;
case 'postback': // }
case 'accountLink':
case 'fallback': // case 'postback': {
default: // Postback.Postback(this, event);
break; // break;
} // }
});
bot.listen(path, port, credentials, function () { // case 'join':
let datetime = dateFormat(new Date(), "yyyy-mm-dd HH:MM:ss"); // case 'leave':
console.log(`${datetime} listening on ${port}`); // case 'follow':
console.log(`${datetime} [BOT已準備就緒]`); // case 'unfollow':
// Tools_MYSQLDB.readData(); // case 'memberJoin':
}); // case 'memberLeave':
// case 'accountLink':
// case 'fallback':
// default:
// break;
// }
// });
// bot.listen(path, port, credentials, function () {
// let datetime = dateFormat(new Date(), "yyyy-mm-dd HH:MM:ss");
// console.log(`${datetime} listening on ${port}`);
// console.log(`${datetime} [BOT已準備就緒]`);
// // Tools_MYSQLDB.readData();
// });

View File

@ -1,5 +1,5 @@
{ {
"name": "line-bot-js", "name": "line-cost-js",
"version": "1.0.0", "version": "1.0.0",
"description": "", "description": "",
"main": "app.js", "main": "app.js",
@ -8,13 +8,16 @@
"dotenv": "^8.2.0", "dotenv": "^8.2.0",
"express": "^4.17.1", "express": "^4.17.1",
"linebot": "^1.6.1", "linebot": "^1.6.1",
"mysql": "^2.18.1" "mysql": "^2.18.1",
"node-schedule": "^2.0.0",
"xmlhttprequest": "^1.8.0"
}, },
"devDependencies": { "devDependencies": {
"nodemon": "^2.0.7" "nodemon": "^2.0.7"
}, },
"scripts": { "scripts": {
"start": "node --inspect=192.168.168.15:9229 app.js" "start": "forever start -a -l line-cost-js.log app.js",
"dev": "nodemon --inspect=127.0.0.1:9229 app.js"
}, },
"keywords": [], "keywords": [],
"author": "", "author": "",