Compare commits

..

No commits in common. "master" and "v1" have entirely different histories.
master ... v1

8 changed files with 765 additions and 889 deletions

View File

@ -2,13 +2,11 @@ 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');
const LINENotifyClass = require('../api/LINENotifyClass');
/** CPBL */ /** CPBL */
class CPBLClass { class CPBLClass {
constructor(app) { constructor(app) {
this.app = app; this.app = app;
this.LINENotify = new LINENotifyClass();
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];
@ -35,25 +33,24 @@ class CPBLClass {
} }
async AddTime(Data, event) { async AddTime(Data, event) {
let replyMsg = ""; let game_id = Data["game_id"];
let GameSno = Data["GameSno"]; let cpbldata = Data["cpbldata"];
let LineID = Data["LineID"]; let LineID = Data["LineID"];
let access_token = Data["access_token"];
let IsHaveGameSno = false; let Isgame_id = false;
let IsHaveLineID = false; let IsLineID = false;
let Time = { let Time = {
GameSno: GameSno, game_id: game_id,
LineID: [LineID], cpbldata: cpbldata,
access_token: [access_token] LineID: [LineID]
} }
for (let i = 0; i < this.TimeList.length; i++) { for (let i = 0; i < this.TimeList.length; i++) {
if (this.TimeList[i]["GameSno"] === GameSno) { if (this.TimeList[i]["game_id"] === game_id) {
IsHaveGameSno = 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) {
IsHaveLineID = true; IsLineID = true;
break; break;
} }
} }
@ -61,46 +58,37 @@ class CPBLClass {
} }
} }
let IsRUN = true; let IsRUN = true;
let Response = await this.GetCPBL(GameSno); let Response = await this.GetCPBL(Time);
if (Response === "比賽尚未開始" || Response[Response.length - 1].indexOf("比賽結束") !== -1) { if (Response[Response.length - 1]["title"].indexOf("比賽結束") !== -1) {
IsRUN = false; IsRUN = false;
} }
if (Response === "比賽尚未開始") { let replyMsg = "";
// await this.LINENotify.Send(access_token, Response); for (let i = 0; i < Response.length; i++) {
} else { replyMsg += Response[i]["title"];
let PushMsg = ""; if (i !== Response.length - 1) {
for (let i = 0; i < Response.length; i++) { replyMsg += "\n\n";
let ThisPushMsg = Response[i];
if (PushMsg.length + ThisPushMsg.length > 1000) {
// await this.LINENotify.Send(access_token, PushMsg);
PushMsg = ThisPushMsg;
} else {
PushMsg += ThisPushMsg;
}
} }
// await this.LINENotify.Send(access_token, PushMsg);
} }
if (IsRUN) { if (IsRUN) {
if (!IsHaveGameSno) { 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 (IsHaveGameSno && !IsHaveLineID) { } else if (Isgame_id && !IsLineID) {
// 有這場賽事但沒這個帳號 // 有這場賽事但沒這個帳號
Time["LineID"].push(LineID); Time["LineID"].push(LineID);
Time["access_token"].push(access_token);
} }
let Extra = { let Extra = {
GameSno: GameSno, 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 = "已停止中職轉播功能"; replyMsg += "\n\n已停止中職轉播功能";
} }
if (event) { if (event) {
event.reply(replyMsg).then(function (data) { event.reply(replyMsg).then(function (data) {
@ -112,7 +100,7 @@ class CPBLClass {
} }
StartTime() { StartTime() {
// var rule = '2 * * * * *'; // var rule = '0 1 * * * *';
// * * * * * * // * * * * * *
// ┬ ┬ ┬ ┬ ┬ ┬ // ┬ ┬ ┬ ┬ ┬ ┬
// │ │ │ │ │ | // │ │ │ │ │ |
@ -123,12 +111,6 @@ class CPBLClass {
// │ └──────────── 分取值0 - 59 // │ └──────────── 分取值0 - 59
// └─────────────── 秒取值0 - 59可选 // └─────────────── 秒取值0 - 59可选
var rule = new schedule.RecurrenceRule(); var rule = new schedule.RecurrenceRule();
// rule.date = "*";
// rule.dayOfWeek = "*";
// rule.hour = "*";
// rule.minute = "*";
// rule.year = "*";
// rule.month = "*";
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++) {
@ -136,33 +118,28 @@ class CPBLClass {
minute_arr.push(i); minute_arr.push(i);
} }
} }
rule.minute = minute_arr;
rule.second = new schedule.Range(0, 59, 2);
// 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(`設定任務 每${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(`設定任務 每${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)); this.Timer = schedule.scheduleJob(rule, this.Update.bind(this));
this.Timer = schedule.scheduleJob(rule, () => {
console.log(`現在時間: ${dateFormat(new Date(), "yyyy-mm-dd HH:MM:ss")}`);
});
} }
CloseTime() { CloseTime() {
this.Timer.cancel(); this.Timer.cancel();
} }
async GetCPBL(GameSno) { async GetCPBL(Time) {
let Data = { let game_id = Time["game_id"];
GameSno: GameSno, let cpbldata = Time["cpbldata"];
KindCode: "A", let LineID = Time["LineID"];
Year: dateFormat(new Date(), "yyyy")
};
let url = "https://jianmiau.ml:3333/CPBL"; 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); let Response = await this.GetData(url, Data);
Response = JSON.parse(Response); 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);
@ -182,12 +159,17 @@ class CPBLClass {
} }
async RunTime(Time) { async RunTime(Time) {
let GameSno = Time["GameSno"]; let game_id = Time["game_id"];
let cpbldata = Time["cpbldata"];
let LineID = Time["LineID"]; let LineID = Time["LineID"];
let access_token = Time["access_token"]; let url = "https://jianmiau.ml:3333/CPBL";
let Response = await this.GetCPBL(GameSno); 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; let IsRUN = true;
if (Response === "比賽尚未開始" || Response[Response.length - 1].indexOf("比賽結束") !== -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++) {
@ -197,23 +179,19 @@ class CPBLClass {
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 GameSno = Extra["GameSno"]; let cpbldata = Extra["cpbldata"];
let count = Extra["count"]; let count = Extra["count"];
if (Response.length > count) { if (Response.length > count) {
let PushMsg = ""; let replyMsg = "";
for (let i = count; i < Response.length; i++) { for (let j = count; j < Response.length; j++) {
let ThisPushMsg = Response[i]; replyMsg += Response[j]["title"];
if (PushMsg.length + ThisPushMsg.length > 1000) { if (j !== Response.length - 1) {
await this.LINENotify.Send(access_token, PushMsg); replyMsg += "\n\n";
PushMsg = ThisPushMsg;
} else {
PushMsg += ThisPushMsg;
} }
} }
await this.LINENotify.Send(access_token, PushMsg);
if (IsRUN) { if (IsRUN) {
let Extra = { let Extra = {
GameSno: GameSno, 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");
@ -223,10 +201,9 @@ class CPBLClass {
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);
PushMsg = "已停止中職轉播功能"; replyMsg += "\n\n已停止中職轉播功能";
let res_Msg = this.app.bot.push(LineID[i], PushMsg);
} }
// await this.LINENotify.Send(access_token, PushMsg); let res_Msg = this.app.bot.push(LineID[i], replyMsg);
} }
} }
} }
@ -235,14 +212,13 @@ class CPBLClass {
} }
} }
async GetCPBLList(DateTime, access_token) { 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 = {
today: DateTime Date: Date
// today: "2021-09-26"
}; };
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));
@ -251,35 +227,36 @@ class CPBLClass {
let img = []; let img = [];
let team = []; let team = [];
let data = ""; let data = "";
let game = Response[i]; let href = Response[i]["href"];
let info = { for (let j = 1; j <= 2; j++) {
"樂天桃猿": { if (Response[i][`img${j}`].indexOf("AJL011_logo_01") !== -1) {
img: "https://jianmiau.ml/MyWeb/Resources/CPBL/R.png" img.push("https://jianmiau.ml/MyWeb/Resources/CPBL/R.png");
}, team.push("樂天桃猿");
"富邦悍將": { } else if (Response[i][`img${j}`].indexOf("B04_logo_01") !== -1) {
img: "https://jianmiau.ml/MyWeb/Resources/CPBL/F.png" img.push("https://jianmiau.ml/MyWeb/Resources/CPBL/F.png");
}, team.push("富邦悍將");
"味全龍": { } else if (Response[i][`img${j}`].indexOf("D01_logo_01") !== -1) {
img: "https://jianmiau.ml/MyWeb/Resources/CPBL/D.png" img.push("https://jianmiau.ml/MyWeb/Resources/CPBL/D.png");
}, team.push("味全龍");
"中信兄弟": { } else if (Response[i][`img${j}`].indexOf("E02_logo_01") !== -1) {
img: "https://jianmiau.ml/MyWeb/Resources/CPBL/B.png" img.push("https://jianmiau.ml/MyWeb/Resources/CPBL/B.png");
}, team.push("中信兄弟");
"統一7-ELEVEn獅": { } else if (Response[i][`img${j}`].indexOf("L01_logo_01") !== -1) {
img: "https://jianmiau.ml/MyWeb/Resources/CPBL/L.png" img.push("https://jianmiau.ml/MyWeb/Resources/CPBL/L.png");
}, team.push("統一獅");
}
} }
let url = `https://karolchang.github.io/cpbl-vue/#/record/${game.GameSno}/A/2021`; if (href["time"]) {
let gametime = game.PreExeDate.split("T"); 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"]}`;
// let nowUNIXtime = Date.now(); } else {
// let gameUNIXtime = new Date(`${gametime[0]} ${gametime[1]}`).getTime(); 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 IsStart = nowUNIXtime - gameUNIXtime > 0; }
data = `action=hasgame&game_date=${gametime[0]}&time=${gametime[1]}&GameSno=${game.GameSno}&access_token=${access_token}`; 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": info[game.HomeTeamName].img, "thumbnailImageUrl": img[0],
"imageBackgroundColor": "#FFFFFF", "imageBackgroundColor": "#FFFFFF",
"title": `${game.VisitingTeamName} VS ${game.HomeTeamName}`, "title": `${team[0]} VS ${team[1]}`,
"text": `比賽場地 ${game.FieldAbbe} ${gametime[0]} ${gametime[1]}`, "text": `比賽場地 ${Response[i]["address"]} ${href["game_date"]}`,
"defaultAction": { "defaultAction": {
"type": "uri", "type": "uri",
"label": "比賽網站", "label": "比賽網站",
@ -287,9 +264,6 @@ class CPBLClass {
}, },
"actions": [ "actions": [
{ {
// "type": "uri",
// "label": "比賽網站",
// "uri": url
"type": "postback", "type": "postback",
"label": "追蹤比賽", "label": "追蹤比賽",
"data": data "data": data
@ -345,37 +319,6 @@ class CPBLClass {
}); });
} }
async CPBLBind(Date) {
let url = `https://notify-bot.line.me/oauth/authorize?response_type=code&scope=notify&response_mode=form_post&client_id=Jj4K1D7XxtmDeXJGF3c0vV&redirect_uri=https://jianmiau.ml:3333/LINENotify&state=${userId}$${displayName}`;
let shorturl = await this.Tools.shorturl(url);
let Data_columns = [
{
"thumbnailImageUrl": "https://www.line-community.me/awards/uimage/5b46aedf851f74a6af8eaab8",
"imageBackgroundColor": "#FFFFFF",
"title": "點擊綁定",
"text": "點擊後將會進行綁定",
"defaultAction": {
"type": "uri",
"label": "點擊綁定",
"uri": shorturl
},
"actions": [
{
"type": "uri",
"label": "點擊綁定",
"uri": shorturl
}
]
}
];
return new Promise((resolve, reject) => {
// 傳入 resolve 與 reject表示資料成功與失敗
resolve(Data_columns);
// reject()
});
}
/** /**
* 取得表 * 取得表
* @param Url Url * @param Url Url

View File

@ -1,12 +1,10 @@
const dateFormat = require('dateformat'); const dateFormat = require('dateformat');
const { decode } = require('querystring'); const { decode } = require('querystring');
const ToolsClass = require('./ToolsClass');
/** Message */ /** Message */
class MessageClass { class MessageClass {
constructor(app) { constructor(app) {
this.app = app; this.app = app;
this.Tools = new ToolsClass();
// this.app.CPBL.AddTime({ // this.app.CPBL.AddTime({
// game_id: 64, // game_id: 64,
// cpbldata: { // cpbldata: {
@ -142,90 +140,28 @@ class MessageClass {
} }
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;
// }
// this.app.CPBL.AddTime({
// game_id: data["game_id"],
// cpbldata: data,
// LineID: userId
// }, event);
let GameSno = Msg[1];
if (!GameSno) {
return; return;
} }
let Query = `SELECT UserData.LINENotify FROM \`UserData\` WHERE \`userId\` = '${userId}' LIMIT 1;`;
let res_Query = await this.app.Tools_MYSQLDB.Query(Query);
let access_token = res_Query[0]["LINENotify"];
this.app.CPBL.AddTime({ this.app.CPBL.AddTime({
GameSno: GameSno, game_id: data["game_id"],
LineID: userId, cpbldata: data,
access_token: access_token LineID: userId
}, event); }, event);
// replyMsg = await this.app.CPBL.GetCPBL1(userId, GameSno);
// event.reply(replyMsg)
return; return;
} }
case "今日賽事": case "今日賽事":
case "我愛建喵今日賽事": { case "我愛建喵今日賽事": {
let Query = `SELECT UserData.LINENotify FROM \`UserData\` WHERE \`userId\` = '${userId}' LIMIT 1;`; let columns = await this.app.CPBL.GetCPBLList(Msg[1] ? Msg[1] : dateFormat(new Date(), "yyyymmdd"));
let res_Query = await this.app.Tools_MYSQLDB.Query(Query); let res_reply = event.replyimagemap("建喵也愛你", columns).then(function (data) {
let access_token = res_Query[0]["LINENotify"]; // 當訊息成功回傳後的處理
let columns = await this.app.CPBL.GetCPBLList(Msg[1] ? Msg[1] : dateFormat(new Date(), "yyyy-mm-dd"), access_token); }).catch(function (error) {
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;
}
case "CPBL綁定": {
let url = `https://notify-bot.line.me/oauth/authorize?response_type=code&scope=notify&response_mode=form_post&client_id=Jj4K1D7XxtmDeXJGF3c0vV&redirect_uri=https://jianmiau.ml:3333/LINENotify&state=${userId}$${displayName}`;
let shorturl = await this.Tools.shorturl(url);
let Data_columns = [
{
"thumbnailImageUrl": "https://www.line-community.me/awards/uimage/5b46aedf851f74a6af8eaab8",
"imageBackgroundColor": "#FFFFFF",
"title": "點擊綁定",
"text": "點擊後將會進行綁定",
"defaultAction": {
"type": "uri",
"label": "點擊綁定",
"uri": shorturl
},
"actions": [
{
"type": "uri",
"label": "點擊綁定",
"uri": shorturl
}
]
}
];
event.replyimagemap("點擊綁定", Data_columns)
.then(function (data) {
// 當訊息成功回傳後的處理
})
.catch(function (error) {
// 當訊息回傳失敗後的處理
});
return; return;
} }

View File

@ -11,6 +11,11 @@ class PostbackClass {
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': {
this.NoGame(event, data);
break;
}
case 'hasgame': { case 'hasgame': {
this.HasGame(event, data); this.HasGame(event, data);
break; break;
@ -21,23 +26,24 @@ class PostbackClass {
} }
} }
HasGame(event, data) { NoGame(event, data) {
let game_date = data["game_date"]; let replyMsg = `比賽還沒開始\n時間是${data["game_date"]} ${data["time"]}`;
let time = data["time"]; if (event) {
let nowUNIXtime = Date.now(); event.reply(replyMsg).then(function (data) {
let gameUNIXtime = new Date(`${game_date} ${time}`).getTime(); // 當訊息成功回傳後的處理
let IsStart = nowUNIXtime - gameUNIXtime > 0; }).catch(function (error) {
if (IsStart) { // 當訊息回傳失敗後的處理
this.app.CPBL.AddTime({ });
GameSno: data["GameSno"],
access_token: data["access_token"],
LineID: event.source.userId
}, event);
} else {
let replyMsg = `比賽還沒開始\n時間是${game_date} ${time}`;
event.reply(replyMsg);
} }
} }
HasGame(event, data) {
this.app.CPBL.AddTime({
game_id: data["game_id"],
cpbldata: data,
LineID: event.source.userId
}, event);
}
} }
module.exports = PostbackClass module.exports = PostbackClass

View File

@ -1,37 +0,0 @@
const XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
/** ToolsClass */
class ToolsClass {
// constructor() {
// }
/**
* shorturl
* @param url url
*/
shorturl(url) {
return new Promise((resolve, reject) => {
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status >= 200 && xhr.status < 400) {
var response = JSON.parse(xhr.responseText);
resolve(response.link);
}
}
};
xhr.open("POST", "https://api-ssl.bitly.com/v4/shorten");
xhr.setRequestHeader("Authorization", "Bearer 88188dfe42e71c8da237fd49ffe5979d0fc69bd6");
xhr.setRequestHeader("Content-Type", "application/json");
let encodedData = JSON.stringify({
"long_url": url,
"domain": "bit.ly"
});
xhr.send(encodedData);
});
}
}
module.exports = ToolsClass

View File

@ -6,8 +6,7 @@ class Tools_MYSQLDBClass {
constructor() { constructor() {
let datetime = dateFormat(new Date(), "yyyy-mm-dd HH:MM:ss"); let datetime = dateFormat(new Date(), "yyyy-mm-dd HH:MM:ss");
let config = { let config = {
// host: 'jianmiau.tk', host: 'jianmiau.tk',
host: '192.168.168.15',
user: 'jianmiau', user: 'jianmiau',
password: 'VQ*ZetC7xcc9%dTW', password: 'VQ*ZetC7xcc9%dTW',
database: 'line-cost-php', database: 'line-cost-php',

41
app.js
View File

@ -1,11 +1,8 @@
// 背景執行 forever start -a -l line-cost-js.log app.js // 背景執行 forever start -a -l line-cost-js.log app.js
// 重新背景執行 forever restart -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
// git clone ssh://JianMiau@192.168.168.15:1922/volume1/github/line-cost-js
const dateFormat = require('dateformat'); const dateFormat = require('dateformat');
require('dotenv').config() require('dotenv').config()
// require("./plug/DateFormat"); // require("./plug/DateFormat");
@ -14,9 +11,9 @@ var linebot = require('linebot');
const fs = require('fs'); const fs = require('fs');
//讀取憑證及金鑰 //讀取憑證及金鑰
const prikey = fs.readFileSync('../certificate/privkey.pem', 'utf8'); const prikey = fs.readFileSync('privkey.pem', 'utf8');
const cert = fs.readFileSync('../certificate/cert.pem', 'utf8'); const cert = fs.readFileSync('cert.pem', 'utf8');
const cafile = fs.readFileSync('../certificate/chain.pem', 'utf-8'); const cafile = fs.readFileSync('chain.pem', 'utf-8');
//建立憑證及金鑰 //建立憑證及金鑰
const credentials = { const credentials = {
@ -44,3 +41,35 @@ const path = process.env.URLPATH || "/";
const port = process.env.PORT || 3001; 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) {
// 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();
// });