From 6481a933eac95206481e67c1be6badf7656b3604 Mon Sep 17 00:00:00 2001 From: kyle208 <847163260@qq.com> Date: Mon, 29 May 2023 08:12:11 +0800 Subject: [PATCH] =?UTF-8?q?=E9=80=82=E9=85=8D=E8=87=AA=E5=AE=9A=E4=B9=89we?= =?UTF-8?q?bhook=E6=8E=A8=E9=80=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- sample/notify.js | 60 +++++++++++++++++++++++++++++++--- sample/notify.py | 84 ++++++++++++++++++++++++++---------------------- 2 files changed, 100 insertions(+), 44 deletions(-) diff --git a/sample/notify.js b/sample/notify.js index a6fb4d06..1a68406d 100644 --- a/sample/notify.js +++ b/sample/notify.js @@ -137,7 +137,14 @@ let SMTP_EMAIL = ''; let SMTP_PASSWORD = ''; let SMTP_NAME = ''; +// =======================================webhook设置区域======================================= +let WEBHOOK_URL = ''; + //==========================云端环境变量的判断与接收========================= +if (process.env.WEBHOOK_URL) { + WEBHOOK_URL = process.env.WEBHOOK_URL; +} + if (process.env.GOTIFY_URL) { GOTIFY_URL = process.env.GOTIFY_URL; } @@ -288,6 +295,7 @@ if (process.env.SMTP_NAME) { * @param author 作者仓库等信息 例:`本通知 By:https://github.com/whyour/qinglong` * @returns {Promise} */ + async function sendNotify( text, desp, @@ -308,8 +316,8 @@ async function sendNotify( await Promise.all([ serverNotify(text, desp), //微信server酱 - pushPlusNotify(text, desp), //pushplus(推送加) - ]); + pushPlusNotify(text, desp), //pushplus(推送加) + ]); //由于上述两种微信通知需点击进去才能查看到详情,故text(标题内容)携带了账号序号以及昵称信息,方便不点击也可知道是哪个京东哪个活动 text = text.match(/.*?(?=\s?-)/g) ? text.match(/.*?(?=\s?-)/g)[0] : text; await Promise.all([ @@ -326,7 +334,9 @@ async function sendNotify( aibotkNotify(text, desp), //智能微秘书 fsBotNotify(text, desp), //飞书机器人 smtpNotify(text, desp), //SMTP 邮件 + webhookNotify(text, desp), //webhook ]); + } function gotifyNotify(text, desp) { @@ -344,12 +354,12 @@ function gotifyNotify(text, desp) { $.post(options, (err, resp, data) => { try { if (err) { - console.log('gotify发送通知调用API失败!!\n'); + console.log('gotify发送通知调用API失败55555!!\n'); console.log(err); } else { data = JSON.parse(data); if (data.id) { - console.log('gotify发送通知消息成功🎉\n'); + console.log('gotify发送通知消息成功66666🎉\n'); } else { console.log(`${data.message}\n`); } @@ -1107,10 +1117,50 @@ function smtpNotify(text, desp) { }); } +function webhookNotify(text, desp) { + console.log(text); + return new Promise((resolve) => { + console.log(WEBHOOK_URL); + if (WEBHOOK_URL) { + const options = { + url: `${WEBHOOK_URL}`, + body: `title=${encodeURIComponent(text)}&message=${encodeURIComponent( + desp, + )}&priority=${''}`, + headers: { + 'Content-Type': 'application/x-www-form-urlencoded', + }, + }; + $.post(options, (err, resp, data) => { + console.log(options); + try { + if (err) { + console.log('webhook发送通知调用API失败!!\n'); + console.log(err); + } else { + data = JSON.parse(data); + if (data.id) { + console.log('webhook发送通知消息成功🎉\n'); + } else { + console.log(`${data.message}\n`); + } + } + } catch (e) { + $.logErr(e, resp); + } finally { + resolve(); + } + }); + } else { + resolve(); + } + }); +} + module.exports = { sendNotify, BARK_PUSH, }; // prettier-ignore -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)} +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)} \ No newline at end of file diff --git a/sample/notify.py b/sample/notify.py index 9b1bd802..9f59a9f2 100644 --- a/sample/notify.py +++ b/sample/notify.py @@ -31,7 +31,7 @@ def print(text, *args, **kw): # 通知服务 -# fmt: off +#fmt: on push_config = { 'HITOKOTO': False, # 启用一言(随机句子) @@ -41,7 +41,7 @@ push_config = { 'BARK_SOUND': '', # bark 推送声音 'BARK_ICON': '', # bark 推送图标 - 'CONSOLE': True, # 控制台输出 + 'CONSOLE': False, # 控制台输出 'DD_BOT_SECRET': '', # 钉钉机器人的 DD_BOT_SECRET 'DD_BOT_TOKEN': '', # 钉钉机器人的 DD_BOT_TOKEN @@ -96,9 +96,11 @@ push_config = { 'SMTP_EMAIL': '', # SMTP 收发件邮箱,通知将会由自己发给自己 'SMTP_PASSWORD': '', # SMTP 登录密码,也可能为特殊口令,视具体邮件服务商说明而定 'SMTP_NAME': '', # SMTP 收发件人姓名,可随意填写 + + 'WEBHOOK_URL': '', # webhook自定义通知 接收回调的URL } notify_function = [] -# fmt: on +#fmt: on # 首先读取 面板变量 或者 github action 运行变量 for k in push_config: @@ -164,8 +166,7 @@ def dingding_bot(title: str, content: str) -> None: timestamp = str(round(time.time() * 1000)) secret_enc = push_config.get("DD_BOT_SECRET").encode("utf-8") - string_to_sign = "{}\n{}".format( - timestamp, push_config.get("DD_BOT_SECRET")) + string_to_sign = "{}\n{}".format(timestamp, push_config.get("DD_BOT_SECRET")) string_to_sign_enc = string_to_sign.encode("utf-8") hmac_code = hmac.new( secret_enc, string_to_sign_enc, digestmod=hashlib.sha256 @@ -221,7 +222,7 @@ def go_cqhttp(title: str, content: str) -> None: print("go-cqhttp 推送失败!") -def gotify(title: str, content: str) -> None: +def gotify(title:str,content:str) -> None: """ 使用 gotify 推送消息。 """ @@ -231,9 +232,8 @@ def gotify(title: str, content: str) -> None: print("gotify 服务启动") url = f'{push_config.get("GOTIFY_URL")}/message?token={push_config.get("GOTIFY_TOKEN")}' - data = {"title": title, "message": content, - "priority": push_config.get("GOTIFY_PRIORITY")} - response = requests.post(url, data=data).json() + data = {"title": title,"message": content,"priority": push_config.get("GOTIFY_PRIORITY")} + response = requests.post(url,data=data).json() if response.get("id"): print("gotify 推送成功!") @@ -271,10 +271,10 @@ def serverJ(title: str, content: str) -> None: print("serverJ 服务启动") data = {"text": title, "desp": content.replace("\n", "\n\n")} - if push_config.get("PUSH_KEY").find("SCT") != -1: + if push_config.get("PUSH_KEY").index("SCT") != -1: url = f'https://sctapi.ftqq.com/{push_config.get("PUSH_KEY")}.send' else: - url = f'https://sc.ftqq.com/{push_config.get("PUSH_KEY")}.send' + url = f'https://sc.ftqq.com/${push_config.get("PUSH_KEY")}.send' response = requests.post(url, data=data).json() if response.get("errno") == 0 or response.get("code") == 0: @@ -291,8 +291,7 @@ def pushdeer(title: str, content: str) -> None: print("PushDeer 服务的 DEER_KEY 未设置!!\n取消推送") return print("PushDeer 服务启动") - data = {"text": title, "desp": content, "type": "markdown", - "pushkey": push_config.get("DEER_KEY")} + data = {"text": title, "desp": content, "type": "markdown", "pushkey": push_config.get("DEER_KEY")} url = 'https://api2.pushdeer.com/message/push' if push_config.get("DEER_URL"): url = push_config.get("DEER_URL") @@ -323,6 +322,7 @@ def chat(title: str, content: str) -> None: print("Chat 推送失败!错误信息:", response) + def pushplus_bot(title: str, content: str) -> None: """ 通过 push+ 推送消息。 @@ -350,8 +350,7 @@ def pushplus_bot(title: str, content: str) -> None: url_old = "http://pushplus.hxtrip.com/send" headers["Accept"] = "application/json" - response = requests.post( - url=url_old, data=body, headers=headers).json() + response = requests.post(url=url_old, data=body, headers=headers).json() if response["code"] == 200: print("PUSHPLUS(hxtrip) 推送成功!") @@ -370,8 +369,7 @@ def qmsg_bot(title: str, content: str) -> None: print("qmsg 服务启动") url = f'https://qmsg.zendee.cn/{push_config.get("QMSG_TYPE")}/{push_config.get("QMSG_KEY")}' - payload = { - "msg": f'{title}\n\n{content.replace("----", "-")}'.encode("utf-8")} + payload = {"msg": f'{title}\n\n{content.replace("----", "-")}'.encode("utf-8")} response = requests.post(url=url, params=payload).json() if response["code"] == 0: @@ -557,14 +555,14 @@ def aibotk(title: str, content: str) -> None: data = { "apiKey": push_config.get("AIBOTK_KEY"), "roomName": push_config.get("AIBOTK_NAME"), - "message": {"type": 1, "content": f'【青龙快讯】\n\n{title}\n{content}'} + "message": {"type": 1, "content": f'【青龙快讯】\n\n${title}\n${content}' } } else: url = "https://api-bot.aibotk.com/openapi/v1/chat/contact" data = { "apiKey": push_config.get("AIBOTK_KEY"), "name": push_config.get("AIBOTK_NAME"), - "message": {"type": 1, "content": f'【青龙快讯】\n\n{title}\n{content}'} + "message": {"type": 1, "content": f'【青龙快讯】\n\n${title}\n${content}' } } body = json.dumps(data).encode(encoding="utf-8") headers = {"Content-Type": "application/json"} @@ -586,24 +584,38 @@ def smtp(title: str, content: str) -> None: print("SMTP 邮件 服务启动") message = MIMEText(content, 'plain', 'utf-8') - message['From'] = formataddr((Header(push_config.get( - "SMTP_NAME"), 'utf-8').encode(), push_config.get("SMTP_EMAIL"))) - message['To'] = formataddr((Header(push_config.get( - "SMTP_NAME"), 'utf-8').encode(), push_config.get("SMTP_EMAIL"))) + message['From'] = formataddr((Header(push_config.get("SMTP_NAME"), 'utf-8').encode(), push_config.get("SMTP_EMAIL"))) + message['To'] = formataddr((Header(push_config.get("SMTP_NAME"), 'utf-8').encode(), push_config.get("SMTP_EMAIL"))) message['Subject'] = Header(title, 'utf-8') try: - smtp_server = smtplib.SMTP_SSL(push_config.get("SMTP_SERVER")) if push_config.get( - "SMTP_SSL") == 'true' else smtplib.SMTP(push_config.get("SMTP_SERVER")) - smtp_server.login(push_config.get("SMTP_EMAIL"), - push_config.get("SMTP_PASSWORD")) - smtp_server.sendmail(push_config.get("SMTP_EMAIL"), - push_config.get("SMTP_EMAIL"), message.as_bytes()) + smtp_server = smtplib.SMTP_SSL(push_config.get("SMTP_SERVER")) if push_config.get("SMTP_SSL") == 'true' else smtplib.SMTP(push_config.get("SMTP_SERVER")) + smtp_server.login(push_config.get("SMTP_EMAIL"), push_config.get("SMTP_PASSWORD")) + smtp_server.sendmail(push_config.get("SMTP_EMAIL"), push_config.get("SMTP_EMAIL"), message.as_bytes()) smtp_server.close() print("SMTP 邮件 推送成功!") except Exception as e: print(f'SMTP 邮件 推送失败!{e}') +def webhook_notify(title: str, content: str) -> None: + """ + 通过 WEBHOOK 推送消息。 + """ + if not push_config.get("WEBHOOK_URL"): + print("WEBHOOK 服务的 WEBHOOK_URL 未设置!!\n取消推送") + return + print("WEBHOOK服务启动") + + url = f"{push_config.get('WEBHOOK_URL')}" + headers = {"Content-Type": "application/json;charset=utf-8"} + data = {"title": f"{title}", "content": f"{content}"} + response = requests.post( + url=url, data=json.dumps(data), headers=headers, timeout=15 + ).json() + + print("WEBHOOK 推送成功!") + + def one() -> str: """ @@ -649,6 +661,8 @@ if push_config.get("AIBOTK_KEY") and push_config.get("AIBOTK_TYPE") and push_con notify_function.append(aibotk) if push_config.get("SMTP_SERVER") and push_config.get("SMTP_SSL") and push_config.get("SMTP_EMAIL") and push_config.get("SMTP_PASSWORD") and push_config.get("SMTP_NAME"): notify_function.append(smtp) +if push_config.get("WEBHOOK_URL"): + notify_function.append(webhook_notify) def send(title: str, content: str) -> None: @@ -656,21 +670,13 @@ def send(title: str, content: str) -> None: print(f"{title} 推送内容为空!") return - # 根据标题跳过一些消息推送,环境变量:SKIP_PUSH_TITLE 用回车分隔 - skipTitle = os.getenv("SKIP_PUSH_TITLE") - if skipTitle: - if (title in re.split("\n", skipTitle)): - print(f"{title} 在SKIP_PUSH_TITLE环境变量内,跳过推送!") - return - hitokoto = push_config.get("HITOKOTO") text = one() if hitokoto else "" content += "\n\n" + text ts = [ - threading.Thread(target=mode, args=( - title, content), name=mode.__name__) + threading.Thread(target=mode, args=(title, content), name=mode.__name__) for mode in notify_function ] [t.start() for t in ts] @@ -682,4 +688,4 @@ def main(): if __name__ == "__main__": - main() + main() \ No newline at end of file