From a9ff89d8b8de86485d33394d6d514c17c8c7fb6b Mon Sep 17 00:00:00 2001 From: JianMiau Date: Sat, 24 Apr 2021 21:18:34 +0800 Subject: [PATCH] =?UTF-8?q?[add]=20CPBL=E5=8A=9F=E8=83=BD=20[add]=20Postba?= =?UTF-8?q?ck?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CPBLClass.js | 347 ++++++++++++++++++++++++++++++++++++++++++ LineBotClass.js | 58 +++++++ MessageClass.js | 100 +++++++++--- PostbackClass.js | 49 ++++++ Tools_MYSQLDBClass.js | 8 +- app.js | 71 ++++----- package.json | 11 +- 7 files changed, 581 insertions(+), 63 deletions(-) create mode 100644 CPBLClass.js create mode 100644 LineBotClass.js create mode 100644 PostbackClass.js diff --git a/CPBLClass.js b/CPBLClass.js new file mode 100644 index 0000000..46b6db7 --- /dev/null +++ b/CPBLClass.js @@ -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 \ No newline at end of file diff --git a/LineBotClass.js b/LineBotClass.js new file mode 100644 index 0000000..b108406 --- /dev/null +++ b/LineBotClass.js @@ -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 \ No newline at end of file diff --git a/MessageClass.js b/MessageClass.js index 2f54fd4..0347e0e 100644 --- a/MessageClass.js +++ b/MessageClass.js @@ -1,11 +1,21 @@ const dateFormat = require('dateformat'); +const { decode } = require('querystring'); /** Message */ class MessageClass { - constructor(bot, JianMiaubot, Tools_MYSQLDB) { - this.bot = bot; - this.JianMiaubot = JianMiaubot; - this.Tools_MYSQLDB = Tools_MYSQLDB; + constructor(app) { + this.app = app; + // this.app.CPBL.AddTime({ + // 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) { @@ -45,7 +55,7 @@ class MessageClass { case "user": { let userId = event.source.userId; let displayName = ""; - let profile = await this.bot.getUserProfile(userId); + let profile = await this.app.bot.getUserProfile(userId); if (profile) { displayName = profile.displayName; } @@ -54,10 +64,10 @@ class MessageClass { //ToJianMiau------------------------------------------------------------------------------------------------------ if (userId !== process.env.toZhuHantoJianMiau) { let ToJM_message = "已接收訊息:"; - ToJM_message += "\ndisplayName: $displayName"; - ToJM_message += "\nuserId: $userId"; + ToJM_message += `\ndisplayName: ${displayName}`; + ToJM_message += `\nuserId: ${userId}`; 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) { // 當訊息成功回傳後的處理 @@ -80,7 +90,7 @@ class MessageClass { 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); + let profile = await this.app.bot.getUserProfile(userId); if (profile) { displayName = profile.displayName; } @@ -91,7 +101,7 @@ class MessageClass { ToJM_message += `\ndisplayName: ${displayName}`; ToJM_message += `\nuserId: ${userId}`; 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特別功能 @@ -115,7 +125,7 @@ class MessageClass { for (let i = 2; i < Msg.length; i++) { 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 = "已發送訊息:"; ToJM_message += `\nuserId: ${Msg[1]}`; @@ -129,9 +139,35 @@ class MessageClass { 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: { 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 Status = Data[0]['Status']; switch (Status) { @@ -151,7 +187,7 @@ class MessageClass { } 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); + res_Query = await this.app.Tools_MYSQLDB.Query(Query); event.reply(replyMsg).then(function (data) { // 當訊息成功回傳後的處理 }).catch(function (error) { @@ -160,21 +196,41 @@ class MessageClass { 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: break; } break; } } - if (replyMsg !== "") { - replyMsg = event.message.text; - // 使用event.reply(要回傳的訊息)方法可將訊息回傳給使用者 - event.reply(replyMsg).then(function (data) { - // 當訊息成功回傳後的處理 - }).catch(function (error) { - // 當訊息回傳失敗後的處理 - }); - } + } + if (replyMsg !== "") { + replyMsg = event.message.text; + // 使用event.reply(要回傳的訊息)方法可將訊息回傳給使用者 + event.reply(replyMsg).then(function (data) { + // 當訊息成功回傳後的處理 + }).catch(function (error) { + // 當訊息回傳失敗後的處理 + }); } } } diff --git a/PostbackClass.js b/PostbackClass.js new file mode 100644 index 0000000..ebf5778 --- /dev/null +++ b/PostbackClass.js @@ -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 \ No newline at end of file diff --git a/Tools_MYSQLDBClass.js b/Tools_MYSQLDBClass.js index 4e03909..e6c124b 100644 --- a/Tools_MYSQLDBClass.js +++ b/Tools_MYSQLDBClass.js @@ -1,8 +1,10 @@ const mysql = require('mysql'); +const dateFormat = require('dateformat'); /** Tools_MYSQLDB */ class Tools_MYSQLDBClass { constructor() { + let datetime = dateFormat(new Date(), "yyyy-mm-dd HH:MM:ss"); let config = { host: 'jianmiau.tk', user: 'jianmiau', @@ -14,11 +16,11 @@ class Tools_MYSQLDBClass { this.conn.connect( function (err) { if (err) { - console.log("!!! Cannot connect !!! Error:"); + console.log(`${datetime} !!! Cannot connect !!! Error:`); throw err; } else { - console.log("jianmiau.tk Connect."); + console.log(`${datetime} jianmiau.tk Connect.`); } }); } @@ -39,7 +41,7 @@ class Tools_MYSQLDBClass { this.conn.end( function (err) { if (err) throw err; - else console.log('Closing connection.') + else console.log(`${datetime} Closing connection.`) }); } diff --git a/app.js b/app.js index 0cb3738..bde623b 100644 --- a/app.js +++ b/app.js @@ -1,6 +1,7 @@ -// 背景執行 forever start -w -a -l line-cost-js.log app.js -// 監聽檔案變化 nodemon "npm start" -// Debug node --inspect=192.168.168.15:9229 app.js +// 背景執行 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'); require('dotenv').config() @@ -33,40 +34,42 @@ var JianMiaubot = linebot({ channelAccessToken: process.env.channelAccessToken }); -const Tools_MYSQLDBClass = require('./Tools_MYSQLDBClass'); -const MessageClass = require('./MessageClass'); - -const Tools_MYSQLDB = new Tools_MYSQLDBClass(); -const Message = new MessageClass(bot, JianMiaubot, Tools_MYSQLDB); +const LineBotAPI = require('./LineBotClass'); // Bot所監聽的webhook路徑與port const path = process.env.URLPATH || "/"; const port = process.env.PORT || 3001; -// 當有人傳送訊息給Bot時 -bot.on('event', function (event) { - switch (event.type) { - case 'message': { - Message.Message(event); - break; - } +new LineBotAPI(path, port, credentials, bot, JianMiaubot); - case 'join': - case 'leave': - case 'follow': - case 'unfollow': - case 'memberJoin': - case 'memberLeave': - case 'postback': - 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(); -}); \ No newline at end of file +// // 當有人傳送訊息給Bot時 +// bot.on('event', function (event) { +// switch (event.type) { +// case 'message': { +// Message.Message(event); +// break; +// } + +// case 'postback': { +// Postback.Postback(this, 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(); +// }); \ No newline at end of file diff --git a/package.json b/package.json index d8422d3..17c2215 100644 --- a/package.json +++ b/package.json @@ -1,5 +1,5 @@ { - "name": "line-bot-js", + "name": "line-cost-js", "version": "1.0.0", "description": "", "main": "app.js", @@ -8,15 +8,18 @@ "dotenv": "^8.2.0", "express": "^4.17.1", "linebot": "^1.6.1", - "mysql": "^2.18.1" + "mysql": "^2.18.1", + "node-schedule": "^2.0.0", + "xmlhttprequest": "^1.8.0" }, "devDependencies": { "nodemon": "^2.0.7" }, "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": [], "author": "", "license": "ISC" -} +} \ No newline at end of file