[fix] CPBL賽事判斷錯誤

This commit is contained in:
建喵 2021-04-27 08:42:22 +08:00
parent a9ff89d8b8
commit 74b941a94e
5 changed files with 774 additions and 762 deletions

View File

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

View File

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

View File

@ -1,238 +1,249 @@
const dateFormat = require('dateformat'); const dateFormat = require('dateformat');
const { decode } = require('querystring'); const { decode } = require('querystring');
/** Message */ /** Message */
class MessageClass { class MessageClass {
constructor(app) { constructor(app) {
this.app = app; this.app = app;
// this.app.CPBL.AddTime({ // this.app.CPBL.AddTime({
// game_id: 64, // game_id: 64,
// cpbldata: { // cpbldata: {
// "http://www.cpbl.com.tw/games/play_by_play.html?": "", // "http://www.cpbl.com.tw/games/play_by_play.html?": "",
// game_type: "01", // game_type: "01",
// game_id: "63", // game_id: "63",
// game_date: "2021-04-20", // game_date: "2021-04-20",
// pbyear: "2021", // pbyear: "2021",
// }, // },
// LineID: 1 // LineID: 1
// }); // });
} }
Message(event) { Message(event) {
switch (event.message.type) { switch (event.message.type) {
case 'text': { case 'text': {
this.Text(event); this.Text(event);
break; break;
} }
case 'sticker': { case 'sticker': {
this.Sticker(event); this.Sticker(event);
break; break;
} }
default: default:
break; break;
} }
} }
Text(event) { Text(event) {
switch (event.source.type) { switch (event.source.type) {
case "user": { case "user": {
this.User(event); this.User(event);
break; break;
} }
case "group": case "group":
break; break;
default: default:
break; break;
} }
} }
async Sticker(event) { async Sticker(event) {
switch (event.source.type) { switch (event.source.type) {
case "user": { case "user": {
let userId = event.source.userId; let userId = event.source.userId;
let displayName = ""; let displayName = "";
let profile = await this.app.bot.getUserProfile(userId); let profile = await this.app.bot.getUserProfile(userId);
if (profile) { if (profile) {
displayName = profile.displayName; displayName = profile.displayName;
} }
let replyMsg = `line://app/1602687308-GXq4Vvk9?type=sticker&stk=noanim&sid=${event.message.stickerId}&pkg=${event.message.packageId}`; let replyMsg = `line://app/1602687308-GXq4Vvk9?type=sticker&stk=noanim&sid=${event.message.stickerId}&pkg=${event.message.packageId}`;
//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.app.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) {
// 當訊息成功回傳後的處理 // 當訊息成功回傳後的處理
}).catch(function (error) { }).catch(function (error) {
// 當訊息回傳失敗後的處理 // 當訊息回傳失敗後的處理
}); });
break; break;
} }
case "group": case "group":
break; break;
default: default:
break; break;
} }
} }
async User(event) { async User(event) {
let userId = event.source.userId; let userId = event.source.userId;
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.app.bot.getUserProfile(userId); let profile = await this.app.bot.getUserProfile(userId);
if (profile) { if (profile) {
displayName = profile.displayName; displayName = profile.displayName;
} }
//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 += `\nmessage: ${replyMsg}`; ToJM_message += `\nmessage: ${replyMsg}`;
let res_toJianMiau = this.app.JianMiaubot.push(process.env.toJianMiau, ToJM_message); let res_toJianMiau = this.app.JianMiaubot.push(process.env.toJianMiau, ToJM_message);
} }
// JianMiau特別功能 // JianMiau特別功能
if (userId === process.env.toZhuHantoJianMiau || userId === process.env.toZhuHantoZhuHan) { if (userId === process.env.toZhuHantoJianMiau || userId === process.env.toZhuHantoZhuHan) {
/** 訊息 */ /** 訊息 */
let Msg = event.message.text.split(" "); let Msg = event.message.text.split(" ");
/** 指令 */ /** 指令 */
let Instruction = Msg[0]; let Instruction = Msg[0];
switch (Instruction) { switch (Instruction) {
case "msg": case "msg":
case "Msg": case "Msg":
case "MSG": { case "MSG": {
if (userId == process.env.toZhuHantoJianMiau) { if (userId == process.env.toZhuHantoJianMiau) {
if (Msg[1] === "豬涵") { if (Msg[1] === "豬涵") {
Msg[1] = process.env.toZhuHantoZhuHan; Msg[1] = process.env.toZhuHantoZhuHan;
} else if (Msg[1] === "建喵") { } else if (Msg[1] === "建喵") {
Msg[1] = process.env.toZhuHantoJianMiau; Msg[1] = process.env.toZhuHantoJianMiau;
} }
replyMsg = ""; replyMsg = "";
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.app.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]}`;
ToJM_message += `\nmessage: ${replyMsg}`; ToJM_message += `\nmessage: ${replyMsg}`;
let res_reply = event.reply(ToJM_message).then(function (data) { let res_reply = event.reply(ToJM_message).then(function (data) {
// 當訊息成功回傳後的處理 // 當訊息成功回傳後的處理
}).catch(function (error) { }).catch(function (error) {
// 當訊息回傳失敗後的處理 // 當訊息回傳失敗後的處理
}); });
} }
return; return;
} }
case "中職": { case "中職": {
let URL = Msg[1]; let URL = Msg[1];
let Isplay_by_play = URL.indexOf("play_by_play"); let Isplay_by_play = URL.indexOf("play_by_play");
let data = decode(URL); let data = decode(URL);
if (Isplay_by_play === -1 || !data["game_id"]) { if (Isplay_by_play === -1 || !data["game_id"]) {
return; return;
} }
this.app.CPBL.AddTime({ this.app.CPBL.AddTime({
game_id: data["game_id"], game_id: data["game_id"],
cpbldata: data, cpbldata: data,
LineID: userId LineID: userId
}, event); }, event);
return; return;
} }
case "今日賽事": case "今日賽事":
case "我愛建喵今日賽事": { case "我愛建喵今日賽事": {
let columns = await this.app.CPBL.GetCPBLList(Msg[1] ? Msg[1] : dateFormat(new Date(), "yyyymmdd")); let columns = await this.app.CPBL.GetCPBLList(Msg[1] ? Msg[1] : dateFormat(new Date(), "yyyymmdd"));
let res_reply = event.replyimagemap("建喵也愛你", columns).then(function (data) { if (columns.length > 0) {
// 當訊息成功回傳後的處理 let res_reply = event.replyimagemap("建喵也愛你", columns).then(function (data) {
}).catch(function (error) { // 當訊息成功回傳後的處理
// 當訊息回傳失敗後的處理 }).catch(function (error) {
}); // 當訊息回傳失敗後的處理
return; });
} } else {
replyMsg = "今天沒有比賽";
default: { event.reply(replyMsg)
let Query = `SELECT * FROM \`line-cost-status\` WHERE \`userId\` = '${userId}' LIMIT 1;`; .then(function (data) {
let res_Query = await this.app.Tools_MYSQLDB.Query(Query); // 當訊息成功回傳後的處理
let Data = res_Query; })
let Status = Data[0]['Status']; .catch(function (error) {
switch (Status) { // 當訊息回傳失敗後的處理
case "Love_Pig_QA OK": { });
let Extra = JSON.parse(Data[0]["Extra"]); }
let answer = false; return;
let keyword = Extra["keyword"].split(","); }
for (let i = 0; i < keyword.length; i++) {
if (!keyword[i] || event.message.text.indexOf(keyword[i]) !== -1) { default: {
answer = true; let Query = `SELECT * FROM \`line-cost-status\` WHERE \`userId\` = '${userId}' LIMIT 1;`;
} let res_Query = await this.app.Tools_MYSQLDB.Query(Query);
} let Data = res_Query;
if (answer) { let Status = Data[0]['Status'];
replyMsg = "答對, 答案就是:"; switch (Status) {
} else { case "Love_Pig_QA OK": {
replyMsg = "答錯, 正確答案是:"; let Extra = JSON.parse(Data[0]["Extra"]);
} let answer = false;
replyMsg += "\n" + Extra["answer"]; let keyword = Extra["keyword"].split(",");
Query = `UPDATE \`line-cost-status\` SET \`datetime\`='${datetime}', \`Status\`='', \`Extra\`='' WHERE (\`userId\`='${userId}');`; for (let i = 0; i < keyword.length; i++) {
res_Query = await this.app.Tools_MYSQLDB.Query(Query); if (!keyword[i] || event.message.text.indexOf(keyword[i]) !== -1) {
event.reply(replyMsg).then(function (data) { answer = true;
// 當訊息成功回傳後的處理 }
}).catch(function (error) { }
// 當訊息回傳失敗後的處理 if (answer) {
}); replyMsg = "答對, 答案就是:";
return; } else {
} replyMsg = "答錯, 正確答案是:";
}
case "CPBL RUN": { replyMsg += "\n" + Extra["answer"];
switch (Instruction) { Query = `UPDATE \`line-cost-status\` SET \`datetime\`='${datetime}', \`Status\`='', \`Extra\`='' WHERE (\`userId\`='${userId}');`;
case "停止": { res_Query = await this.app.Tools_MYSQLDB.Query(Query);
replyMsg = "已停止中職轉播功能"; event.reply(replyMsg).then(function (data) {
Query = `UPDATE \`line-cost-status\` SET \`datetime\`='${datetime}', \`Status\`='', \`Extra\`='' WHERE (\`userId\`='${userId}');`; // 當訊息成功回傳後的處理
res_Query = await this.app.Tools_MYSQLDB.Query(Query); }).catch(function (error) {
event.reply(replyMsg).then(function (data) { // 當訊息回傳失敗後的處理
// 當訊息成功回傳後的處理 });
}).catch(function (error) { return;
// 當訊息回傳失敗後的處理 }
});
break; case "CPBL RUN": {
} switch (Instruction) {
case "停止": {
default: replyMsg = "已停止中職轉播功能";
break; Query = `UPDATE \`line-cost-status\` SET \`datetime\`='${datetime}', \`Status\`='', \`Extra\`='' WHERE (\`userId\`='${userId}');`;
} res_Query = await this.app.Tools_MYSQLDB.Query(Query);
return; event.reply(replyMsg).then(function (data) {
} // 當訊息成功回傳後的處理
}).catch(function (error) {
default: // 當訊息回傳失敗後的處理
break; });
} break;
break; }
}
} default:
} break;
if (replyMsg !== "") { }
replyMsg = event.message.text; return;
// 使用event.reply(要回傳的訊息)方法可將訊息回傳給使用者 }
event.reply(replyMsg).then(function (data) {
// 當訊息成功回傳後的處理 default:
}).catch(function (error) { break;
// 當訊息回傳失敗後的處理 }
}); break;
} }
} }
} }
if (replyMsg !== "") {
replyMsg = event.message.text;
// 使用event.reply(要回傳的訊息)方法可將訊息回傳給使用者
event.reply(replyMsg).then(function (data) {
// 當訊息成功回傳後的處理
}).catch(function (error) {
// 當訊息回傳失敗後的處理
});
}
}
}
module.exports = MessageClass module.exports = MessageClass

View File

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

149
app.js
View File

@ -1,75 +1,76 @@
// 背景執行 forever start -a -l line-cost-js.log app.js // 背景執行 forever start -a -l line-cost-js.log app.js
// npm start // 重新背景執行 forever restart -a -l line-cost-js.log app.js
// npm run dev // npm start
// Debug nodemon --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');
require('dotenv').config() const dateFormat = require('dateformat');
// require("./plug/DateFormat"); require('dotenv').config()
// 引用linebot SDK // require("./plug/DateFormat");
var linebot = require('linebot'); // 引用linebot SDK
const fs = require('fs'); var linebot = require('linebot');
const fs = require('fs');
//讀取憑證及金鑰
const prikey = fs.readFileSync('privkey.pem', 'utf8'); //讀取憑證及金鑰
const cert = fs.readFileSync('cert.pem', 'utf8'); const prikey = fs.readFileSync('privkey.pem', 'utf8');
const cafile = fs.readFileSync('chain.pem', 'utf-8'); const cert = fs.readFileSync('cert.pem', 'utf8');
const cafile = fs.readFileSync('chain.pem', 'utf-8');
//建立憑證及金鑰
const credentials = { //建立憑證及金鑰
key: prikey, const credentials = {
cert: cert, key: prikey,
ca: cafile cert: cert,
}; ca: cafile
};
// 用於辨識Line Channel的資訊
var bot = linebot({ // 用於辨識Line Channel的資訊
channelId: process.env.toZhuHantoJianMiau, var bot = linebot({
channelSecret: process.env.ZhuHanchannelSecret, channelId: process.env.toZhuHantoJianMiau,
channelAccessToken: process.env.ZhuHanchannelAccessToken channelSecret: process.env.ZhuHanchannelSecret,
}); channelAccessToken: process.env.ZhuHanchannelAccessToken
var JianMiaubot = linebot({ });
channelId: process.env.toJianMiau, var JianMiaubot = linebot({
channelSecret: process.env.channelSecret, channelId: process.env.toJianMiau,
channelAccessToken: process.env.channelAccessToken channelSecret: process.env.channelSecret,
}); channelAccessToken: process.env.channelAccessToken
});
const LineBotAPI = require('./LineBotClass');
const LineBotAPI = require('./LineBotClass');
// Bot所監聽的webhook路徑與port
const path = process.env.URLPATH || "/"; // Bot所監聽的webhook路徑與port
const port = process.env.PORT || 3001; const path = process.env.URLPATH || "/";
const port = process.env.PORT || 3001;
new LineBotAPI(path, port, credentials, bot, JianMiaubot);
new LineBotAPI(path, port, credentials, bot, JianMiaubot);
// // 當有人傳送訊息給Bot時
// bot.on('event', function (event) { // // 當有人傳送訊息給Bot時
// switch (event.type) { // bot.on('event', function (event) {
// case 'message': { // switch (event.type) {
// Message.Message(event); // case 'message': {
// break; // Message.Message(event);
// } // break;
// }
// case 'postback': {
// Postback.Postback(this, event); // case 'postback': {
// break; // Postback.Postback(this, event);
// } // break;
// }
// case 'join':
// case 'leave': // case 'join':
// case 'follow': // case 'leave':
// case 'unfollow': // case 'follow':
// case 'memberJoin': // case 'unfollow':
// case 'memberLeave': // case 'memberJoin':
// case 'accountLink': // case 'memberLeave':
// case 'fallback': // case 'accountLink':
// default: // case 'fallback':
// break; // default:
// } // break;
// }); // }
// bot.listen(path, port, credentials, function () { // });
// let datetime = dateFormat(new Date(), "yyyy-mm-dd HH:MM:ss"); // bot.listen(path, port, credentials, function () {
// console.log(`${datetime} listening on ${port}`); // let datetime = dateFormat(new Date(), "yyyy-mm-dd HH:MM:ss");
// console.log(`${datetime} [BOT已準備就緒]`); // console.log(`${datetime} listening on ${port}`);
// // Tools_MYSQLDB.readData(); // console.log(`${datetime} [BOT已準備就緒]`);
// // Tools_MYSQLDB.readData();
// }); // });