Skip to content

Commit 8ec1340

Browse files
author
ziye12
authored
Add files via upload
1 parent bc0b910 commit 8ec1340

File tree

1 file changed

+255
-0
lines changed

1 file changed

+255
-0
lines changed

sendNotify.js

Lines changed: 255 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,255 @@
1+
const $ = new Env();
2+
// =======================================微信server酱通知设置区域===========================================
3+
//此处填你申请的SCKEY.
4+
//注:此处设置github action用户填写到Settings-Secrets里面(Name输入PUSH_KEY)
5+
let SCKEY = '';
6+
7+
// =======================================Bark App通知设置区域===========================================
8+
//此处填你BarkAPP的信息(IP/设备码,例如:https://api.day.app/XXXXXXXX)
9+
//注:此处设置github action用户填写到Settings-Secrets里面(Name输入BARK_PUSH)
10+
let BARK_PUSH = '';
11+
//BARK app推送铃声,铃声列表去APP查看复制填写
12+
//注:此处设置github action用户填写到Settings-Secrets里面(Name输入BARK_SOUND , Value输入app提供的铃声名称,例如:birdsong)
13+
let BARK_SOUND = '';
14+
15+
16+
// =======================================telegram机器人通知设置区域===========================================
17+
//此处填你telegram bot 的Token,例如:1077xxx4424:AAFjv0FcqxxxxxxgEMGfi22B4yh15R5uw
18+
//注:此处设置github action用户填写到Settings-Secrets里面(Name输入TG_BOT_TOKEN)
19+
let TG_BOT_TOKEN = '';
20+
//此处填你接收通知消息的telegram用户的id,例如:129xxx206
21+
//注:此处设置github action用户填写到Settings-Secrets里面(Name输入TG_USER_ID)
22+
let TG_USER_ID = '';
23+
24+
// =======================================钉钉机器人通知设置区域===========================================
25+
//此处填你钉钉 bot 的webhook,例如:5a544165465465645d0f31dca676e7bd07415asdasd
26+
//注:此处设置github action用户填写到Settings-Secrets里面(Name输入DD_BOT_TOKEN)
27+
let DD_BOT_TOKEN = '';
28+
//密钥,机器人安全设置页面,加签一栏下面显示的SEC开头的字符串
29+
let DD_BOT_SECRET = '';
30+
31+
if (process.env.PUSH_KEY) {
32+
SCKEY = process.env.PUSH_KEY;
33+
}
34+
if (process.env.BARK_PUSH) {
35+
if(process.env.BARK_PUSH.indexOf('https') > -1 || process.env.BARK_PUSH.indexOf('http') > -1) {
36+
//兼容BARK自建用户
37+
BARK_PUSH = process.env.BARK_PUSH
38+
} else {
39+
BARK_PUSH = `https://api.day.app/${process.env.BARK_PUSH}`
40+
}
41+
if (process.env.BARK_SOUND) {
42+
BARK_SOUND = process.env.BARK_SOUND
43+
}
44+
} else {
45+
if(BARK_PUSH && BARK_PUSH.indexOf('https') === -1 && BARK_PUSH.indexOf('http') === -1) {
46+
//兼容BARK本地用户只填写设备码的情况
47+
BARK_PUSH = `https://api.day.app/${BARK_PUSH}`
48+
}
49+
}
50+
if (process.env.TG_BOT_TOKEN) {
51+
TG_BOT_TOKEN = process.env.TG_BOT_TOKEN;
52+
}
53+
if (process.env.TG_USER_ID) {
54+
TG_USER_ID = process.env.TG_USER_ID;
55+
}
56+
57+
if (process.env.DD_BOT_TOKEN) {
58+
DD_BOT_TOKEN = process.env.DD_BOT_TOKEN;
59+
if (process.env.DD_BOT_SECRET) {
60+
DD_BOT_SECRET = process.env.DD_BOT_SECRET;
61+
}
62+
}
63+
64+
async function sendNotify(text, desp) {
65+
//提供四种通知
66+
await serverNotify(text, desp);
67+
await BarkNotify(text, desp);
68+
await tgBotNotify(text, desp);
69+
await ddBotNotify(text, desp);
70+
}
71+
72+
function serverNotify(text, desp) {
73+
return new Promise(resolve => {
74+
if (SCKEY) {
75+
//微信server酱推送通知一个\n不会换行,需要两个\n才能换行,故做此替换
76+
desp = desp.replace(/[\n\r]/g, '\n\n');
77+
const options = {
78+
url: `https://sc.ftqq.com/${SCKEY}.send`,
79+
body: `text=${text}&desp=${desp}`,
80+
headers: {
81+
'Content-Type': 'application/x-www-form-urlencoded'
82+
}
83+
}
84+
$.post(options, (err, resp, data) => {
85+
try {
86+
if (err) {
87+
console.log('\n发送通知调用API失败!!\n')
88+
console.log(err);
89+
} else {
90+
data = JSON.parse(data);
91+
if (data.errno === 0) {
92+
console.log('\nserver酱发送通知消息成功\n')
93+
} else if (data.errno === 1024) {
94+
console.log('\nPUSH_KEY 错误\n')
95+
}
96+
}
97+
} catch (e) {
98+
$.logErr(e, resp);
99+
} finally {
100+
resolve(data);
101+
}
102+
})
103+
} else {
104+
console.log('\n您未提供server酱的SCKEY,取消微信推送消息通知\n');
105+
resolve()
106+
}
107+
})
108+
}
109+
110+
function BarkNotify(text, desp) {
111+
return new Promise(resolve => {
112+
if (BARK_PUSH) {
113+
const options = {
114+
url: `${BARK_PUSH}/${encodeURIComponent(text)}/${encodeURIComponent(desp)}?sound=${BARK_SOUND}`,
115+
}
116+
$.get(options, (err, resp, data) => {
117+
try {
118+
if (err) {
119+
console.log('\nBark APP发送通知调用API失败!!\n')
120+
console.log(err);
121+
} else {
122+
data = JSON.parse(data);
123+
if (data.code === 200) {
124+
console.log('\nBark APP发送通知消息成功\n')
125+
} else {
126+
console.log(`\n${data.message}\n`);
127+
}
128+
}
129+
} catch (e) {
130+
$.logErr(e, resp);
131+
} finally {
132+
resolve();
133+
}
134+
})
135+
} else {
136+
console.log('\n您未提供Bark的APP推送BARK_PUSH,取消Bark推送消息通知\n');
137+
resolve()
138+
}
139+
})
140+
}
141+
142+
function tgBotNotify(text, desp) {
143+
return new Promise(resolve => {
144+
if (TG_BOT_TOKEN && TG_USER_ID) {
145+
const options = {
146+
url: `https://api.telegram.org/bot${TG_BOT_TOKEN}/sendMessage`,
147+
body: `chat_id=${TG_USER_ID}&text=${text}\n\n${desp}`,
148+
headers: {
149+
'Content-Type': 'application/x-www-form-urlencoded'
150+
}
151+
}
152+
$.post(options, (err, resp, data) => {
153+
try {
154+
if (err) {
155+
console.log('\ntelegram发送通知消息失败!!\n')
156+
console.log(err);
157+
} else {
158+
data = JSON.parse(data);
159+
if (data.ok) {
160+
console.log('\nTelegram发送通知消息完成。\n')
161+
} else if (data.error_code === 400) {
162+
console.log('\n请主动给bot发送一条消息并检查接收用户ID是否正确。\n')
163+
} else if (data.error_code === 401){
164+
console.log('\nTelegram bot token 填写错误。\n')
165+
}
166+
}
167+
} catch (e) {
168+
$.logErr(e, resp);
169+
} finally {
170+
resolve(data);
171+
}
172+
})
173+
} else {
174+
console.log('\n您未提供telegram机器人推送所需的TG_BOT_TOKEN和TG_USER_ID,取消telegram推送消息通知\n');
175+
resolve()
176+
}
177+
})
178+
}
179+
function ddBotNotify(text, desp) {
180+
return new Promise(resolve => {
181+
const options = {
182+
url: `https://oapi.dingtalk.com/robot/send?access_token=${DD_BOT_TOKEN}`,
183+
json: {
184+
"msgtype": "text",
185+
"text": {
186+
"content": ` ${text}\n\n${desp}`
187+
}
188+
},
189+
headers: {
190+
'Content-Type': 'application/json'
191+
}
192+
}
193+
if (DD_BOT_TOKEN && DD_BOT_SECRET) {
194+
const crypto = require('crypto');
195+
const dateNow = Date.now();
196+
const hmac = crypto.createHmac('sha256', DD_BOT_SECRET);
197+
hmac.update(`${dateNow}\n${DD_BOT_SECRET}`);
198+
const result = encodeURIComponent(hmac.digest('base64'));
199+
options.url = `${options.url}&timestamp=${dateNow}&sign=${result}`;
200+
$.post(options, (err, resp, data) => {
201+
try {
202+
if (err) {
203+
console.log('\n钉钉发送通知消息失败!!\n')
204+
console.log(err);
205+
} else {
206+
data = JSON.parse(data);
207+
if (data.errcode === 0) {
208+
console.log('\n钉钉发送通知消息完成。\n')
209+
} else {
210+
console.log(`\n${data.errmsg}\n`)
211+
}
212+
}
213+
} catch (e) {
214+
$.logErr(e, resp);
215+
} finally {
216+
resolve(data);
217+
}
218+
})
219+
} else if (DD_BOT_TOKEN) {
220+
$.post(options, (err, resp, data) => {
221+
try {
222+
if (err) {
223+
console.log('\n钉钉发送通知消息失败!!\n')
224+
console.log(err);
225+
} else {
226+
data = JSON.parse(data);
227+
if (data.errcode === 0) {
228+
console.log('\n钉钉发送通知消息完成。\n')
229+
} else {
230+
console.log(`\n${data.errmsg}\n`)
231+
}
232+
}
233+
} catch (e) {
234+
$.logErr(e, resp);
235+
} finally {
236+
resolve(data);
237+
}
238+
})
239+
} else {
240+
console.log('\n您未提供钉钉机器人推送所需的DD_BOT_TOKEN或者DD_BOT_SECRET,取消钉钉推送消息通知\n');
241+
resolve()
242+
}
243+
})
244+
}
245+
module.exports = {
246+
sendNotify,
247+
BarkNotify,
248+
SCKEY,
249+
BARK_PUSH,
250+
TG_BOT_TOKEN,
251+
TG_USER_ID,
252+
DD_BOT_TOKEN,
253+
}//这里导出SCKEY,BARK_PUSH等通知参数是jd_bean_sign.js处需要
254+
// prettier-ignore
255+
function Env(t,s){return new class{constructor(t,s){this.name=t,this.data=null,this.dataFile="box.dat",this.logs=[],this.logSeparator="\n",this.startTime=(new Date).getTime(),Object.assign(this,s),this.log("",`\ud83d\udd14${this.name}, \u5f00\u59cb!`)}isNode(){return"undefined"!=typeof module&&!!module.exports}isQuanX(){return"undefined"!=typeof $task}isSurge(){return"undefined"!=typeof $httpClient&&"undefined"==typeof $loon}isLoon(){return"undefined"!=typeof $loon}getScript(t){return new Promise(s=>{$.get({url:t},(t,e,i)=>s(i))})}runScript(t,s){return new Promise(e=>{let i=this.getdata("@chavy_boxjs_userCfgs.httpapi");i=i?i.replace(/\n/g,"").trim():i;let o=this.getdata("@chavy_boxjs_userCfgs.httpapi_timeout");o=o?1*o:20,o=s&&s.timeout?s.timeout:o;const[h,a]=i.split("@"),r={url:`http://${a}/v1/scripting/evaluate`,body:{script_text:t,mock_type:"cron",timeout:o},headers:{"X-Key":h,Accept:"*/*"}};$.post(r,(t,s,i)=>e(i))}).catch(t=>this.logErr(t))}loaddata(){if(!this.isNode())return{};{this.fs=this.fs?this.fs:require("fs"),this.path=this.path?this.path:require("path");const t=this.path.resolve(this.dataFile),s=this.path.resolve(process.cwd(),this.dataFile),e=this.fs.existsSync(t),i=!e&&this.fs.existsSync(s);if(!e&&!i)return{};{const i=e?t:s;try{return JSON.parse(this.fs.readFileSync(i))}catch(t){return{}}}}}writedata(){if(this.isNode()){this.fs=this.fs?this.fs:require("fs"),this.path=this.path?this.path:require("path");const t=this.path.resolve(this.dataFile),s=this.path.resolve(process.cwd(),this.dataFile),e=this.fs.existsSync(t),i=!e&&this.fs.existsSync(s),o=JSON.stringify(this.data);e?this.fs.writeFileSync(t,o):i?this.fs.writeFileSync(s,o):this.fs.writeFileSync(t,o)}}lodash_get(t,s,e){const i=s.replace(/\[(\d+)\]/g,".$1").split(".");let o=t;for(const t of i)if(o=Object(o)[t],void 0===o)return e;return o}lodash_set(t,s,e){return Object(t)!==t?t:(Array.isArray(s)||(s=s.toString().match(/[^.[\]]+/g)||[]),s.slice(0,-1).reduce((t,e,i)=>Object(t[e])===t[e]?t[e]:t[e]=Math.abs(s[i+1])>>0==+s[i+1]?[]:{},t)[s[s.length-1]]=e,t)}getdata(t){let s=this.getval(t);if(/^@/.test(t)){const[,e,i]=/^@(.*?)\.(.*?)$/.exec(t),o=e?this.getval(e):"";if(o)try{const t=JSON.parse(o);s=t?this.lodash_get(t,i,""):s}catch(t){s=""}}return s}setdata(t,s){let e=!1;if(/^@/.test(s)){const[,i,o]=/^@(.*?)\.(.*?)$/.exec(s),h=this.getval(i),a=i?"null"===h?null:h||"{}":"{}";try{const s=JSON.parse(a);this.lodash_set(s,o,t),e=this.setval(JSON.stringify(s),i)}catch(s){const h={};this.lodash_set(h,o,t),e=this.setval(JSON.stringify(h),i)}}else e=$.setval(t,s);return e}getval(t){return this.isSurge()||this.isLoon()?$persistentStore.read(t):this.isQuanX()?$prefs.valueForKey(t):this.isNode()?(this.data=this.loaddata(),this.data[t]):this.data&&this.data[t]||null}setval(t,s){return this.isSurge()||this.isLoon()?$persistentStore.write(t,s):this.isQuanX()?$prefs.setValueForKey(t,s):this.isNode()?(this.data=this.loaddata(),this.data[s]=t,this.writedata(),!0):this.data&&this.data[s]||null}initGotEnv(t){this.got=this.got?this.got:require("got"),this.cktough=this.cktough?this.cktough:require("tough-cookie"),this.ckjar=this.ckjar?this.ckjar:new this.cktough.CookieJar,t&&(t.headers=t.headers?t.headers:{},void 0===t.headers.Cookie&&void 0===t.cookieJar&&(t.cookieJar=this.ckjar))}get(t,s=(()=>{})){t.headers&&(delete t.headers["Content-Type"],delete t.headers["Content-Length"]),this.isSurge()||this.isLoon()?$httpClient.get(t,(t,e,i)=>{!t&&e&&(e.body=i,e.statusCode=e.status),s(t,e,i)}):this.isQuanX()?$task.fetch(t).then(t=>{const{statusCode:e,statusCode:i,headers:o,body:h}=t;s(null,{status:e,statusCode:i,headers:o,body:h},h)},t=>s(t)):this.isNode()&&(this.initGotEnv(t),this.got(t).on("redirect",(t,s)=>{try{const e=t.headers["set-cookie"].map(this.cktough.Cookie.parse).toString();this.ckjar.setCookieSync(e,null),s.cookieJar=this.ckjar}catch(t){this.logErr(t)}}).then(t=>{const{statusCode:e,statusCode:i,headers:o,body:h}=t;s(null,{status:e,statusCode:i,headers:o,body:h},h)},t=>s(t)))}post(t,s=(()=>{})){if(t.body&&t.headers&&!t.headers["Content-Type"]&&(t.headers["Content-Type"]="application/x-www-form-urlencoded"),delete t.headers["Content-Length"],this.isSurge()||this.isLoon())$httpClient.post(t,(t,e,i)=>{!t&&e&&(e.body=i,e.statusCode=e.status),s(t,e,i)});else if(this.isQuanX())t.method="POST",$task.fetch(t).then(t=>{const{statusCode:e,statusCode:i,headers:o,body:h}=t;s(null,{status:e,statusCode:i,headers:o,body:h},h)},t=>s(t));else if(this.isNode()){this.initGotEnv(t);const{url:e,...i}=t;this.got.post(e,i).then(t=>{const{statusCode:e,statusCode:i,headers:o,body:h}=t;s(null,{status:e,statusCode:i,headers:o,body:h},h)},t=>s(t))}}time(t){let s={"M+":(new Date).getMonth()+1,"d+":(new Date).getDate(),"H+":(new Date).getHours(),"m+":(new Date).getMinutes(),"s+":(new Date).getSeconds(),"q+":Math.floor(((new Date).getMonth()+3)/3),S:(new Date).getMilliseconds()};/(y+)/.test(t)&&(t=t.replace(RegExp.$1,((new Date).getFullYear()+"").substr(4-RegExp.$1.length)));for(let e in s)new RegExp("("+e+")").test(t)&&(t=t.replace(RegExp.$1,1==RegExp.$1.length?s[e]:("00"+s[e]).substr((""+s[e]).length)));return t}msg(s=t,e="",i="",o){const h=t=>!t||!this.isLoon()&&this.isSurge()?t:"string"==typeof t?this.isLoon()?t:this.isQuanX()?{"open-url":t}:void 0:"object"==typeof t&&(t["open-url"]||t["media-url"])?this.isLoon()?t["open-url"]:this.isQuanX()?t:void 0:void 0;$.isMute||(this.isSurge()||this.isLoon()?$notification.post(s,e,i,h(o)):this.isQuanX()&&$notify(s,e,i,h(o))),this.logs.push("","==============\ud83d\udce3\u7cfb\u7edf\u901a\u77e5\ud83d\udce3=============="),this.logs.push(s),e&&this.logs.push(e),i&&this.logs.push(i)}log(...t){t.length>0?this.logs=[...this.logs,...t]:console.log(this.logs.join(this.logSeparator))}logErr(t,s){const e=!this.isSurge()&&!this.isQuanX()&&!this.isLoon();e?$.log("",`\u2757\ufe0f${this.name}, \u9519\u8bef!`,t.stack):$.log("",`\u2757\ufe0f${this.name}, \u9519\u8bef!`,t)}wait(t){return new Promise(s=>setTimeout(s,t))}done(t={}){const s=(new Date).getTime(),e=(s-this.startTime)/1e3;this.log("",`\ud83d\udd14${this.name}, \u7ed3\u675f! \ud83d\udd5b ${e} \u79d2`),this.log(),(this.isSurge()||this.isQuanX()||this.isLoon())&&$done(t)}}(t,s)}

0 commit comments

Comments
 (0)