[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 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));
});
}
}
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

View File

@ -1,58 +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();
});
}
}
// 背景執行 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,238 +1,249 @@
const dateFormat = require('dateformat');
const { decode } = require('querystring');
/** Message */
class MessageClass {
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) {
switch (event.message.type) {
case 'text': {
this.Text(event);
break;
}
case 'sticker': {
this.Sticker(event);
break;
}
default:
break;
}
}
Text(event) {
switch (event.source.type) {
case "user": {
this.User(event);
break;
}
case "group":
break;
default:
break;
}
}
async Sticker(event) {
switch (event.source.type) {
case "user": {
let userId = event.source.userId;
let displayName = "";
let profile = await this.app.bot.getUserProfile(userId);
if (profile) {
displayName = profile.displayName;
}
let replyMsg = `line://app/1602687308-GXq4Vvk9?type=sticker&stk=noanim&sid=${event.message.stickerId}&pkg=${event.message.packageId}`;
//ToJianMiau------------------------------------------------------------------------------------------------------
if (userId !== process.env.toZhuHantoJianMiau) {
let ToJM_message = "已接收訊息:";
ToJM_message += `\ndisplayName: ${displayName}`;
ToJM_message += `\nuserId: ${userId}`;
ToJM_message += "\n" + replyMsg;
let res_toJianMiau = this.app.JianMiaubot.push(process.env.toJianMiau, ToJM_message);
}
let res_reply = event.reply(replyMsg).then(function (data) {
// 當訊息成功回傳後的處理
}).catch(function (error) {
// 當訊息回傳失敗後的處理
});
break;
}
case "group":
break;
default:
break;
}
}
async User(event) {
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.app.bot.getUserProfile(userId);
if (profile) {
displayName = profile.displayName;
}
//ToJianMiau------------------------------------------------------------------------------------------------------
if (userId !== process.env.toZhuHantoJianMiau) {
let ToJM_message = `已接收訊息:`;
ToJM_message += `\ndisplayName: ${displayName}`;
ToJM_message += `\nuserId: ${userId}`;
ToJM_message += `\nmessage: ${replyMsg}`;
let res_toJianMiau = this.app.JianMiaubot.push(process.env.toJianMiau, ToJM_message);
}
// JianMiau特別功能
if (userId === process.env.toZhuHantoJianMiau || userId === process.env.toZhuHantoZhuHan) {
/** 訊息 */
let Msg = event.message.text.split(" ");
/** 指令 */
let Instruction = Msg[0];
switch (Instruction) {
case "msg":
case "Msg":
case "MSG": {
if (userId == process.env.toZhuHantoJianMiau) {
if (Msg[1] === "豬涵") {
Msg[1] = process.env.toZhuHantoZhuHan;
} else if (Msg[1] === "建喵") {
Msg[1] = process.env.toZhuHantoJianMiau;
}
replyMsg = "";
for (let i = 2; i < Msg.length; i++) {
replyMsg += Msg[i] + (i === Msg.length - 1 ? "" : " ");
}
let res_Msg = this.app.bot.push(Msg[1], replyMsg);
let ToJM_message = "已發送訊息:";
ToJM_message += `\nuserId: ${Msg[1]}`;
ToJM_message += `\nmessage: ${replyMsg}`;
let res_reply = event.reply(ToJM_message).then(function (data) {
// 當訊息成功回傳後的處理
}).catch(function (error) {
// 當訊息回傳失敗後的處理
});
}
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.app.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.app.Tools_MYSQLDB.Query(Query);
event.reply(replyMsg).then(function (data) {
// 當訊息成功回傳後的處理
}).catch(function (error) {
// 當訊息回傳失敗後的處理
});
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) {
// 當訊息回傳失敗後的處理
});
}
}
}
const dateFormat = require('dateformat');
const { decode } = require('querystring');
/** Message */
class MessageClass {
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) {
switch (event.message.type) {
case 'text': {
this.Text(event);
break;
}
case 'sticker': {
this.Sticker(event);
break;
}
default:
break;
}
}
Text(event) {
switch (event.source.type) {
case "user": {
this.User(event);
break;
}
case "group":
break;
default:
break;
}
}
async Sticker(event) {
switch (event.source.type) {
case "user": {
let userId = event.source.userId;
let displayName = "";
let profile = await this.app.bot.getUserProfile(userId);
if (profile) {
displayName = profile.displayName;
}
let replyMsg = `line://app/1602687308-GXq4Vvk9?type=sticker&stk=noanim&sid=${event.message.stickerId}&pkg=${event.message.packageId}`;
//ToJianMiau------------------------------------------------------------------------------------------------------
if (userId !== process.env.toZhuHantoJianMiau) {
let ToJM_message = "已接收訊息:";
ToJM_message += `\ndisplayName: ${displayName}`;
ToJM_message += `\nuserId: ${userId}`;
ToJM_message += "\n" + replyMsg;
let res_toJianMiau = this.app.JianMiaubot.push(process.env.toJianMiau, ToJM_message);
}
let res_reply = event.reply(replyMsg).then(function (data) {
// 當訊息成功回傳後的處理
}).catch(function (error) {
// 當訊息回傳失敗後的處理
});
break;
}
case "group":
break;
default:
break;
}
}
async User(event) {
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.app.bot.getUserProfile(userId);
if (profile) {
displayName = profile.displayName;
}
//ToJianMiau------------------------------------------------------------------------------------------------------
if (userId !== process.env.toZhuHantoJianMiau) {
let ToJM_message = `已接收訊息:`;
ToJM_message += `\ndisplayName: ${displayName}`;
ToJM_message += `\nuserId: ${userId}`;
ToJM_message += `\nmessage: ${replyMsg}`;
let res_toJianMiau = this.app.JianMiaubot.push(process.env.toJianMiau, ToJM_message);
}
// JianMiau特別功能
if (userId === process.env.toZhuHantoJianMiau || userId === process.env.toZhuHantoZhuHan) {
/** 訊息 */
let Msg = event.message.text.split(" ");
/** 指令 */
let Instruction = Msg[0];
switch (Instruction) {
case "msg":
case "Msg":
case "MSG": {
if (userId == process.env.toZhuHantoJianMiau) {
if (Msg[1] === "豬涵") {
Msg[1] = process.env.toZhuHantoZhuHan;
} else if (Msg[1] === "建喵") {
Msg[1] = process.env.toZhuHantoJianMiau;
}
replyMsg = "";
for (let i = 2; i < Msg.length; i++) {
replyMsg += Msg[i] + (i === Msg.length - 1 ? "" : " ");
}
let res_Msg = this.app.bot.push(Msg[1], replyMsg);
let ToJM_message = "已發送訊息:";
ToJM_message += `\nuserId: ${Msg[1]}`;
ToJM_message += `\nmessage: ${replyMsg}`;
let res_reply = event.reply(ToJM_message).then(function (data) {
// 當訊息成功回傳後的處理
}).catch(function (error) {
// 當訊息回傳失敗後的處理
});
}
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"));
if (columns.length > 0) {
let res_reply = event.replyimagemap("建喵也愛你", columns).then(function (data) {
// 當訊息成功回傳後的處理
}).catch(function (error) {
// 當訊息回傳失敗後的處理
});
} else {
replyMsg = "今天沒有比賽";
event.reply(replyMsg)
.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.app.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.app.Tools_MYSQLDB.Query(Query);
event.reply(replyMsg).then(function (data) {
// 當訊息成功回傳後的處理
}).catch(function (error) {
// 當訊息回傳失敗後的處理
});
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) {
// 當訊息回傳失敗後的處理
});
}
}
}
module.exports = MessageClass

View File

@ -1,49 +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);
}
}
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

149
app.js
View File

@ -1,75 +1,76 @@
// 背景執行 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()
// require("./plug/DateFormat");
// 引用linebot SDK
var linebot = require('linebot');
const fs = require('fs');
//讀取憑證及金鑰
const prikey = fs.readFileSync('privkey.pem', 'utf8');
const cert = fs.readFileSync('cert.pem', 'utf8');
const cafile = fs.readFileSync('chain.pem', 'utf-8');
//建立憑證及金鑰
const credentials = {
key: prikey,
cert: cert,
ca: cafile
};
// 用於辨識Line Channel的資訊
var bot = linebot({
channelId: process.env.toZhuHantoJianMiau,
channelSecret: process.env.ZhuHanchannelSecret,
channelAccessToken: process.env.ZhuHanchannelAccessToken
});
var JianMiaubot = linebot({
channelId: process.env.toJianMiau,
channelSecret: process.env.channelSecret,
channelAccessToken: process.env.channelAccessToken
});
const LineBotAPI = require('./LineBotClass');
// Bot所監聽的webhook路徑與port
const path = process.env.URLPATH || "/";
const port = process.env.PORT || 3001;
new LineBotAPI(path, port, credentials, bot, JianMiaubot);
// // 當有人傳送訊息給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();
// 背景執行 forever start -a -l line-cost-js.log app.js
// 重新背景執行 forever restart -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()
// require("./plug/DateFormat");
// 引用linebot SDK
var linebot = require('linebot');
const fs = require('fs');
//讀取憑證及金鑰
const prikey = fs.readFileSync('privkey.pem', 'utf8');
const cert = fs.readFileSync('cert.pem', 'utf8');
const cafile = fs.readFileSync('chain.pem', 'utf-8');
//建立憑證及金鑰
const credentials = {
key: prikey,
cert: cert,
ca: cafile
};
// 用於辨識Line Channel的資訊
var bot = linebot({
channelId: process.env.toZhuHantoJianMiau,
channelSecret: process.env.ZhuHanchannelSecret,
channelAccessToken: process.env.ZhuHanchannelAccessToken
});
var JianMiaubot = linebot({
channelId: process.env.toJianMiau,
channelSecret: process.env.channelSecret,
channelAccessToken: process.env.channelAccessToken
});
const LineBotAPI = require('./LineBotClass');
// Bot所監聽的webhook路徑與port
const path = process.env.URLPATH || "/";
const port = process.env.PORT || 3001;
new LineBotAPI(path, port, credentials, bot, JianMiaubot);
// // 當有人傳送訊息給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();
// });