等风起

如果当誓时

All at vows.


必应每日壁纸获取脚本编写实例


今日壁纸


背景


  必应主页上每天都会更新一张来自世界各地的精美图片,作为网站背景或桌面壁纸都十分美轮美奂。笔者通过反代官方API解决跨域问题,在setBackGround.js里面处理API返回的JSON数据将本站背景图随机轮替为必应近7日壁纸,这里不再赘述。本文主要记录一次适合Quantumult X, Loon, Surge, 和Node.js运行的必应每日壁纸自动获取脚本的编写过程。

接口

必应壁纸官方API:

https://global.bing.com/HPImageArchive.aspx

附加参数 说明
format 返回的数据格式。hp为html格式;js为json格式;其他值为xml格式
idx 获取特定时间点的数据。如idx=1表示前一天(昨天),依此类推。经过测试最大值为7
n 获取数据的条数。经测试,配合上idx最大可以获取到13天前的数据,即idx=7&n=7
pid 未知。pid为hp时,copyrightlink返回的是相对地址。pid不为hp时,没有看到og信息
ensearch 指定获取必应【国际版/国内版】的每日一图。当ensearch=1时,获取到的是必应国际版的每日一图数据。默认情况和其他值情况下,获取到的是必应国内版的每日一图数据
quiz 当quiz=1时,返回必应小测验所需的相关数据。
og 水印图相关的信息。包含了title、img、desc和hash等信息
uhd 当uhd=1时,可以自定义图片的宽高。当uhd=0时,返回的是固定宽高(1920x1080)的图片数据
uhdwidth 图片宽度。当uhd=1时生效。最大值为3840,超过这个值当作3840处理
uhdheight 图片高度。当uhd=1时生效。最大值为2592,超过这个值当作2592处理
setmkt 指定图片相关的区域信息。如图片名中包含的EN-CN、EN-US或者ZH-CN等。参考值:en-us、zh-cn等
setlang 指定返回数据所使用的语言。参考值:en-us、zh-cn等

API返回数据示例:

➜  ~ curl "https://global.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1&pid=hp&uhd=1&uhdwidth=1920&uhdheight=1080&setmkt=zh-cn&setlang=zh-cn"
{
    "images": [
        {
            "startdate": "20211206", 
            "fullstartdate": "202112061600", 
            "enddate": "20211207", 
            "url": "/th?id=OHR.Koenigsbourg_ZH-CN7675452866_UHD.jpg&rf=LaDigue_UHD.jpg&pid=hp&w=1920&h=1080&rs=1&c=4", 
            "urlbase": "/th?id=OHR.Koenigsbourg_ZH-CN7675452866", 
            "copyright": "孚日山脉上的国王城堡,法国阿尔萨斯 (© Leonid Andronov/Shutterstock)", 
            "copyrightlink": "/search?q=%e5%ad%9a%e6%97%a5%e5%b1%b1%e8%84%89&form=hpcapt&mkt=zh-cn", 
            "title": "", 
            "quiz": "/search?q=Bing+homepage+quiz&filters=WQOskey:%22HPQuiz_20211206_Koenigsbourg%22&FORM=HPQUIZ", 
            "wp": true, 
            "hsh": "f558874adb647d120f2abaf5670dd57f", 
            "drk": 1, 
            "top": 1, 
            "bot": 1, 
            "hs": [ ]
        }
    ], 
    "tooltips": {
        "loading": "正在加载...", 
        "previous": "上一个图像", 
        "next": "下一个图像", 
        "walle": "此图片不能下载用作壁纸。", 
        "walls": "下载今日美图。仅限用作桌面壁纸。"
    }
}

url为壁纸相对路径,拼接后:

https://www.bing.com/th?id=OHR.Koenigsbourg_ZH-CN7675452866_UHD.jpg&rf=LaDigue_UHD.jpg&pid=hp&w=1920&h=1080&rs=1&c=4

尝试插入文中:

![今日壁纸](https://www.bing.com/th?id=OHR.Koenigsbourg_ZH-CN7675452866_UHD.jpg&rf=LaDigue_UHD.jpg&pid=hp&w=1920&h=1080&rs=1&c=4) 

展示:

孚日山脉上的国王城堡,法国阿尔萨斯 (© Leonid Andronov/Shutterstock) 今日壁纸

编写脚本

  该API不存在鉴权,脚本编写时可忽略此问题。这里使用了前文提及的OpenAPI来适配多平台。

开始

const $ = API("bing"); // 创建一个名字为bing的脚本
  • 构建请求 & 处理数据
const bing = "https://www.bing.com"
const bing_api = "https://global.bing.com"
const url =  bing_api + "/HPImageArchive.aspx?format=js&idx=0&n=1&pid=hp&FORM=BEHPTB&uhd=1&uhdwidth=384&uhdheight=216&setmkt=zh-cn&setlang=zh-cn";
const headers = {
    "Origin": bing_api,
    "Host": bing_api.replace("https://",""),
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36 Edge/14.16299",
    "Referer": bing_api
};
const request = {
    url: url,
    headers: headers
};
$.http.get(request)
  .then((resp) => {
    $.data = $.toObj(resp.body).images[0];
    $.urltiny = bing + $.data.url
    $.url = $.urltiny.replace(/&.*/, "");
    $.enddate = $.data.enddate;
    $.date = $.enddate.slice(0,4) + "-" + $.enddate.slice(4,6) + "-" + $.enddate.slice(6);
    $.copyright = $.data.copyright;
    $.copyrightlink = bing + $.data.copyrightlink;
  })
  .catch((err) => {
    $.error("error‼️" + "\n" + err);
  })
  • 日志 & 通知
    Node.js环境需要根据前文设置额外参数
$.param = {"open-url": $.url,"media-url": $.urltiny};
$.info(`\n必应每日壁纸\n${$.enddate}🎉\n${$.copyright}\n${$.url}`);
$.notify("必应每日壁纸", "", $.enddate + "🎉\n" + $.copyright, $.param);
  • 完整的代码
const $ = API("bing"); 
const bing = "https://www.bing.com"
const bing_api = "https://global.bing.com"
const url =  bing_api + "/HPImageArchive.aspx?format=js&idx=0&n=1&pid=hp&FORM=BEHPTB&uhd=1&uhdwidth=384&uhdheight=216&setmkt=zh-cn&setlang=zh-cn";
const headers = {
    "Origin": bing_api,
    "Host": bing_api.replace("https://",""),
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36 Edge/14.16299",
    "Referer": bing_api
};
const request = {
    url: url,
    headers: headers
};
$.http.get(request)
  .then((resp) => {
    $.data = $.toObj(resp.body).images[0];
    $.urltiny = bing + $.data.url
    $.url = $.urltiny.replace(/&.*/, "");
    $.enddate = $.data.enddate;
    $.date = $.enddate.slice(0,4) + "-" + $.enddate.slice(4,6) + "-" + $.enddate.slice(6);
    $.copyright = $.data.copyright;
    $.copyrightlink = bing + $.data.copyrightlink;
  })
  .catch((err) => {
    $.error("error‼️" + "\n" + err);
  })
  .finally(() => {
    $.param = {"open-url": $.url,"media-url": $.urltiny};
    $.info(`\n必应每日壁纸\n${$.enddate}🎉\n${$.copyright}\n${$.url}`);
    $.notify("必应每日壁纸", "", $.enddate + "🎉\n" + $.copyright, $.param);
    $.done();
  });
// prettier-ignore
/*********************************** API *************************************/
function ENV(){const t="undefined"!=typeof $task,e="undefined"!=typeof $loon,s="undefined"!=typeof $httpClient&&!e,o="function"==typeof require&&"undefined"!=typeof $jsbox;return{isQX:t,isLoon:e,isSurge:s,isNode:"function"==typeof require&&!o,isJSBox:o,isRequest:"undefined"!=typeof $request,isScriptable:"undefined"!=typeof importModule}}function HTTP(t={baseURL:""}){const{isQX:e,isLoon:s,isSurge:o,isScriptable:i,isNode:n}=ENV(),r=/https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)/;const h={};return["GET","POST","PUT","DELETE","HEAD","OPTIONS","PATCH"].forEach(c=>h[c.toLowerCase()]=(h=>(function(h,c){c="string"==typeof c?{url:c}:c;const l=t.baseURL;l&&!r.test(c.url||"")&&(c.url=l?l+c.url:c.url),c&&c.body&&c.headers&&!c.headers["Content-Type"]&&(c.headers["Content-Type"]="application/x-www-form-urlencoded");const a=(c={...t,...c}).timeout,_={...{onRequest:()=>{},onResponse:t=>t,onTimeout:()=>{}},...c.events};let p,u;if(_.onRequest(h,c),e)p=$task.fetch({method:h,...c});else if(s||o||n)p=new Promise((t,e)=>{(n?require("request"):$httpClient)[h.toLowerCase()](c,(s,o,i)=>{s?e(s):t({statusCode:o.status||o.statusCode,headers:o.headers,body:i})})});else if(i){const t=new Request(c.url);t.method=h,t.headers=c.headers,t.body=c.body,p=new Promise((e,s)=>{t.loadString().then(s=>{e({statusCode:t.response.statusCode,headers:t.response.headers,body:s})}).catch(t=>s(t))})}const d=a?new Promise((t,e)=>{u=setTimeout(()=>(_.onTimeout(),e(`${h} URL: ${c.url} exceeds the timeout ${a} ms`)),a)}):null;return(d?Promise.race([d,p]).then(t=>(clearTimeout(u),t)):p).then(t=>_.onResponse(t))})(c,h))),h}function API(t="untitled",e=!1){const{isQX:s,isLoon:o,isSurge:i,isNode:n,isJSBox:r,isScriptable:h}=ENV();return new class{constructor(t,e){this.name=t,this.debug=e,this.http=HTTP(),this.env=ENV(),this.node=(()=>{if(n){return{fs:require("fs")}}return null})(),this.initCache();Promise.prototype.delay=function(t){return this.then(function(e){return((t,e)=>new Promise(function(s){setTimeout(s.bind(null,e),t)}))(t,e)})}}initCache(){if(s&&(this.cache=JSON.parse($prefs.valueForKey(this.name)||"{}")),(o||i)&&(this.cache=JSON.parse($persistentStore.read(this.name)||"{}")),n){let t="root.json";this.node.fs.existsSync(t)||this.node.fs.writeFileSync(t,JSON.stringify({}),{flag:"wx"},t=>console.log(t)),this.root={},t=`${this.name}.json`,this.node.fs.existsSync(t)?this.cache=JSON.parse(this.node.fs.readFileSync(`${this.name}.json`)):(this.node.fs.writeFileSync(t,JSON.stringify({}),{flag:"wx"},t=>console.log(t)),this.cache={})}}persistCache(){const t=JSON.stringify(this.cache,null,2);s&&$prefs.setValueForKey(t,this.name),(o||i)&&$persistentStore.write(t,this.name),n&&(this.node.fs.writeFileSync(`${this.name}.json`,t,{flag:"w"},t=>console.log(t)),this.node.fs.writeFileSync("root.json",JSON.stringify(this.root,null,2),{flag:"w"},t=>console.log(t)))}write(t,e){if(this.log(`SET ${e}`),-1!==e.indexOf("#")){if(e=e.substr(1),i||o)return $persistentStore.write(t,e);if(s)return $prefs.setValueForKey(t,e);n&&(this.root[e]=t)}else this.cache[e]=t;this.persistCache()}read(t){return this.log(`READ ${t}`),-1===t.indexOf("#")?this.cache[t]:(t=t.substr(1),i||o?$persistentStore.read(t):s?$prefs.valueForKey(t):n?this.root[t]:void 0)}delete(t){if(this.log(`DELETE ${t}`),-1!==t.indexOf("#")){if(t=t.substr(1),i||o)return $persistentStore.write(null,t);if(s)return $prefs.removeValueForKey(t);n&&delete this.root[t]}else delete this.cache[t];this.persistCache()}notify(t,e="",c="",l={}){const a=l["open-url"],_=l["media-url"];if(s&&$notify(t,e,c,l),i&&$notification.post(t,e,c+`${_?"\n多媒体:"+_:""}`,{url:a}),o){let s={};a&&(s.openUrl=a),_&&(s.mediaUrl=_),"{}"===JSON.stringify(s)?$notification.post(t,e,c):$notification.post(t,e,c,s)}if(n)return new Promise(async s=>{const o=(e?`${e}\n`:"")+c+(a?`\n点击跳转: ${a}`:"")+(_?"\n多媒体: "+_:"");await this.sendNotify(t,o,{url:a}),s()});if(h){const s=c+(a?`\n点击跳转: ${a}`:"")+(_?`\n多媒体: ${_}`:"");if(r){require("push").schedule({title:t,body:(e?e+"\n":"")+s})}else console.log(`${t}\n${e}\n${s}\n\n`)}}sendNotify(t,e,s={},o="\n\n仅供用于学习 https://ooxx.be/js"){return new Promise(async i=>{this.querystring=require("querystring"),this.timeout=this.timeout||"15000",e+=o,this.setParam(),await Promise.all([this.serverNotify(t,e),this.pushPlusNotify(t,e)]),t=t.match(/.*?(?=\s?-)/g)?t.match(/.*?(?=\s?-)/g)[0]:t,await Promise.all([this.BarkNotify(t,e,s),this.tgBotNotify(t,e),this.ddBotNotify(t,e),this.qywxBotNotify(t,e),this.qywxamNotify(t,e),this.iGotNotify(t,e,s),this.gobotNotify(t,e)])})}setParam(){this.SCKEY=process.env.SCKEY||this.SCKEY,this.PUSH_PLUS_TOKEN=process.env.PUSH_PLUS_TOKEN||this.PUSH_PLUS_TOKEN,this.PUSH_PLUS_USER=process.env.PUSH_PLUS_USER||this.PUSH_PLUS_USER,this.BARK_PUSH=process.env.BARK_PUSH||this.BARK_PUSH,this.BARK_SOUND=process.env.BARK_SOUND||this.BARK_SOUND,this.BARK_GROUP=process.env.BARK_GROUP||"AsVow",this.BARK_PUSH&&!this.BARK_PUSH.includes("http")&&(this.BARK_PUSH=`https://api.day.app/${this.BARK_PUSH}`),this.TG_BOT_TOKEN=process.env.TG_BOT_TOKEN||this.TG_BOT_TOKEN,this.TG_USER_ID=process.env.TG_USER_ID||this.TG_USER_ID,this.TG_PROXY_AUTH=process.env.TG_PROXY_AUTH||this.TG_PROXY_AUTH,this.TG_PROXY_HOST=process.env.TG_PROXY_HOST||this.TG_PROXY_HOST,this.TG_PROXY_PORT=process.env.TG_PROXY_PORT||this.TG_PROXY_PORT,this.TG_API_HOST=process.env.TG_API_HOST||"api.telegram.org",this.DD_BOT_TOKEN=process.env.DD_BOT_TOKEN||this.DD_BOT_TOKEN,this.DD_BOT_SECRET=process.env.DD_BOT_SECRET||this.DD_BOT_SECRET,this.QYWX_KEY=process.env.QYWX_KEY||this.QYWX_KEY,this.QYWX_AM=process.env.QYWX_AM||this.QYWX_AM,this.IGOT_PUSH_KEY=process.env.IGOT_PUSH_KEY||this.IGOT_PUSH_KEY,this.GOBOT_URL=process.env.GOBOT_URL||this.GOBOT_URL,this.GOBOT_TOKEN=process.env.GOBOT_TOKEN||this.GOBOT_TOKEN,this.GOBOT_QQ=process.env.GOBOT_QQ||this.GOBOT_QQ}serverNotify(t,e,s=2100){return new Promise(o=>{if(this.SCKEY){e=e.replace(/[\n\r]/g,"\n\n");const i={url:this.SCKEY.includes("SCT")?`https://sctapi.ftqq.com/${this.SCKEY}.send`:`https://sc.ftqq.com/${this.SCKEY}.send`,body:`text=${t}&desp=${e}`,headers:{"Content-Type":"application/x-www-form-urlencoded"},timeout:this.timeout};setTimeout(()=>{this.http.post(i).then(t=>{const e=this.toObj(t.body);0===e.errno||0===e.data.errno?console.log("server酱发送通知消息成功🎉\n"):1024===e.errno?console.log(`server酱发送通知消息异常: ${e.errmsg}\n`):console.log(`server酱发送通知消息异常\n${this.toStr(e)}`)}).catch(t=>{console.log("server酱发送通知调用API失败!!\n"),this.error(t)}).finally(()=>{o()})},s)}else o()})}pushPlusNotify(t,e){return new Promise(s=>{if(this.PUSH_PLUS_TOKEN){e=e.replace(/[\n\r]/g,"<br>");const o={token:`${this.PUSH_PLUS_TOKEN}`,title:`${t}`,content:`${e}`,topic:`${this.PUSH_PLUS_USER}`},i={url:"https://www.pushplus.plus/send",body:this.toStr(o),headers:{"Content-Type":" application/json"},timeout:this.timeout};this.http.post(i).then(t=>{const e=this.toObj(t.body);200===e.code?console.log(`push+发送${this.PUSH_PLUS_USER?"一对多":"一对一"}通知消息完成。\n`):console.log(`push+发送${this.PUSH_PLUS_USER?"一对多":"一对一"}通知消息失败:${e.msg}\n`)}).catch(t=>{console.log(`push+发送${this.PUSH_PLUS_USER?"一对多":"一对一"}通知消息失败!!\n`),this.error(t)}).finally(()=>{s()})}else s()})}BarkNotify(t,e,s={}){return new Promise(o=>{if(this.BARK_PUSH){const i={url:`${this.BARK_PUSH}/${encodeURIComponent(t)}/${encodeURIComponent(e)}?sound=${this.BARK_SOUND}&group=${this.BARK_GROUP}&${this.querystring.stringify(s)}`,headers:{"Content-Type":"application/x-www-form-urlencoded"},timeout:this.timeout};this.http.get(i).then(t=>{const e=this.toObj(t.body);200===e.code?console.log("Bark APP发送通知消息成功🎉\n"):console.log(`${e.message}\n`)}).catch(t=>{console.log("Bark APP发送通知调用API失败!!\n"),this.error(t)}).finally(()=>{o()})}else o()})}tgBotNotify(t,e){return new Promise(s=>{if(this.TG_BOT_TOKEN&&this.TG_USER_ID){const o={url:`https://${this.TG_API_HOST}/bot${this.TG_BOT_TOKEN}/sendMessage`,body:`chat_id=${this.TG_USER_ID}&text=${t}\n\n${e}&disable_web_page_preview=true`,headers:{"Content-Type":"application/x-www-form-urlencoded"},timeout:this.timeout};if(this.TG_PROXY_HOST&&this.TG_PROXY_PORT){const t={host:this.TG_PROXY_HOST,port:1*this.TG_PROXY_PORT,proxyAuth:this.TG_PROXY_AUTH};Object.assign(o,{proxy:t})}this.http.post(o).then(t=>{const e=this.toObj(t.body);e.ok?console.log("Telegram发送通知消息成功🎉。\n"):400===e.error_code?console.log("请主动给bot发送一条消息并检查接收用户ID是否正确。\n"):401===e.error_code&&console.log("Telegram bot token 填写错误。\n")}).catch(t=>{console.log("Telegram发送通知消息失败!!\n"),this.error(t)}).finally(()=>{s()})}else s()})}ddBotNotify(t,e){return new Promise(s=>{const o={url:`https://oapi.dingtalk.com/robot/send?access_token=${this.DD_BOT_TOKEN}`,json:{msgtype:"text",text:{content:` ${t}\n\n${e}`}},headers:{"Content-Type":"application/json"},timeout:this.timeout};if(this.DD_BOT_TOKEN&&this.DD_BOT_SECRET){const t=require("crypto"),e=Date.now(),i=t.createHmac("sha256",this.DD_BOT_SECRET);i.update(`${e}\n${this.DD_BOT_SECRET}`);const n=encodeURIComponent(i.digest("base64"));o.url=`${o.url}&timestamp=${e}&sign=${n}`,this.http.post(o).then(t=>{const e=this.toObj(t.body);0===e.errcode?console.log("钉钉发送通知消息成功🎉。\n"):console.log(`${e.errmsg}\n`)}).catch(t=>{console.log("钉钉发送通知消息失败!!\n"),this.error(t)}).finally(()=>{s()})}else this.DD_BOT_TOKEN?this.http.post(o).then(t=>{const e=this.toObj(t.body);0===e.errcode?console.log("钉钉发送通知消息完成。\n"):console.log(`${e.errmsg}\n`)}).catch(t=>{console.log("钉钉发送通知消息失败!!\n"),this.error(t)}).finally(()=>{s()}):s()})}qywxBotNotify(t,e){return new Promise(s=>{const o={url:`https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=${this.QYWX_KEY}`,json:{msgtype:"text",text:{content:` ${t}\n\n${e}`}},headers:{"Content-Type":"application/json"},timeout:this.timeout};this.QYWX_KEY?this.http.post(o).then(t=>{const e=this.toObj(t.body);0===e.errcode?console.log("企业微信发送通知消息成功🎉。\n"):console.log(`${e.errmsg}\n`)}).catch(t=>{console.log("企业微信发送通知消息失败!!\n"),this.error(t)}).finally(()=>{s()}):s()})}ChangeUserId(t){if(this.QYWX_AM_AY=this.QYWX_AM.split(","),this.QYWX_AM_AY[2]){const e=this.QYWX_AM_AY[2].split("|");let s="";for(let o=0;o<e.length;o++){const i="签到号 "+(o+1);t.match(i)&&(s=e[o])}return s||(s=this.QYWX_AM_AY[2]),s}return"@all"}qywxamNotify(t,e){return new Promise(s=>{if(this.QYWX_AM){this.QYWX_AM_AY=this.QYWX_AM.split(",");const o={url:"https://qyapi.weixin.qq.com/cgi-bin/gettoken",json:{corpid:`${this.QYWX_AM_AY[0]}`,corpsecret:`${this.QYWX_AM_AY[1]}`},headers:{"Content-Type":"application/json"},timeout:this.timeout};let i;this.http.post(o).then(s=>{const o=e.replace(/\n/g,"<br/>"),n=this.toObj(s.body).access_token;switch(this.QYWX_AM_AY[4]){case"0":i={msgtype:"textcard",textcard:{title:`${t}`,description:`${e}`,url:"https://ooxx.be/js",btntxt:"更多"}};break;case"1":i={msgtype:"text",text:{content:`${t}\n\n${e}`}};break;default:i={msgtype:"mpnews",mpnews:{articles:[{title:`${t}`,thumb_media_id:`${this.QYWX_AM_AY[4]}`,author:"智能助手",content_source_url:"",content:`${o}`,digest:`${e}`}]}}}this.QYWX_AM_AY[4]||(i={msgtype:"text",text:{content:`${t}\n\n${e}`}}),i={url:`https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=${n}`,json:{touser:`${this.ChangeUserId(e)}`,agentid:`${this.QYWX_AM_AY[3]}`,safe:"0",...i},headers:{"Content-Type":"application/json"}}}),this.http.post(i).then(t=>{const s=this.toObj(s);0===s.errcode?console.log("成员ID:"+this.ChangeUserId(e)+"企业微信应用消息发送通知消息成功🎉。\n"):console.log(`${s.errmsg}\n`)}).catch(t=>{console.log("成员ID:"+this.ChangeUserId(e)+"企业微信应用消息发送通知消息失败!!\n"),this.error(t)}).finally(()=>{s()})}else s()})}iGotNotify(t,e,s={}){return new Promise(o=>{if(this.IGOT_PUSH_KEY){if(this.IGOT_PUSH_KEY_REGX=new RegExp("^[a-zA-Z0-9]{24}$"),!this.IGOT_PUSH_KEY_REGX.test(this.IGOT_PUSH_KEY))return console.log("您所提供的IGOT_PUSH_KEY无效\n"),void o();const i={url:`https://push.hellyw.com/${this.IGOT_PUSH_KEY.toLowerCase()}`,body:`title=${t}&content=${e}&${this.querystring.stringify(s)}`,headers:{"Content-Type":"application/x-www-form-urlencoded"},timeout:this.timeout};this.http.post(i).then(t=>{const e=this.toObj(t.body);0===e.ret?console.log("iGot发送通知消息成功🎉\n"):console.log(`iGot发送通知消息失败:${e.errMsg}\n`)}).catch(t=>{console.log("iGot发送通知调用API失败!!\n"),this.error(t)}).finally(()=>{o()})}else o()})}gobotNotify(t,e,s=2100){return new Promise(o=>{if(this.GOBOT_URL){const i={url:`${this.GOBOT_URL}?access_token=${this.GOBOT_TOKEN}&${this.GOBOT_QQ}`,body:`message=${t}\n${e}`,headers:{"Content-Type":"application/x-www-form-urlencoded"},timeout:this.timeout};setTimeout(()=>{this.http.post(i).then(t=>{const e=this.toObj(t.body);0===e.retcode?console.log("go-cqhttp发送通知消息成功🎉\n"):100===e.retcode?console.log(`go-cqhttp发送通知消息异常: ${e.errmsg}\n`):console.log(`go-cqhttp发送通知消息异常\n${this.toStr(e)}`)}).catch(t=>{console.log("发送go-cqhttp通知调用API失败!!\n"),this.error(t)}).finally(()=>{o()})},s)}else o()})}log(t){this.debug&&console.log(`[${this.name}] LOG: ${this.toStr(t)}`)}info(t){console.log(`[${this.name}] INFO: ${this.toStr(t)}`)}error(t){console.log(`[${this.name}] ERROR: ${this.toStr(t)}`)}wait(t){return new Promise(e=>setTimeout(e,t))}done(t={}){s||o||i?$done(t):n&&!r&&"undefined"!=typeof $context&&($context.headers=t.headers,$context.statusCode=t.statusCode,$context.body=t.body)}toObj(t){if("object"==typeof t||t instanceof Object)return t;try{return JSON.parse(t)}catch(e){return t}}toStr(t){if("string"==typeof t||t instanceof String)return t;try{return JSON.stringify(t)}catch(e){return t}}}(t,e)}
/*****************************************************************************/

后续

  该API最早可获取到13天前的数据,为了储存历史壁纸信息。笔者决定接着给脚本增加Node.js环境下的数据存储功能。

  • 将图文信息写入README.md,链接列表写入list.md,json数据写入bing.json
const readme = "README.md";
const list = "list.md";
const today = `\n![](${$.url}&w=1000)Today: [${$.copyright}](${$.url})`;
const addReadme = `![](${$.urltiny})${$.date} [Download UHD](${$.url})`
const addList = `${$.date} | [${$.copyright}](${$.url}) \n`
const addJson = {url:$.url,copyright:$.copyright,copyrightlink:$.copyrightlink}
const fs = require("fs");
// 写入 README
fs.existsSync(readme) || fs.writeFileSync(readme,"");
fs.readFile(readme, 'utf8', (err, content) => {
  if (err) {
    $.error(err);
    return
  }
  if (!content.includes($.date)) {
    fs.writeFileSync(readme,"## Bing Wallpaper\n");
    fs.appendFileSync(readme,today);
    fs.appendFileSync(readme,"\n|      |      |      |");
    fs.appendFileSync(readme,"\n| :----: | :----: | :----: |");
    content = content.replace("## Bing Wallpaper","").replace(/^.*Today.*$/mg, "").replace("|      |      |      |","").replace("| :----: | :----: | :----: |","").replace(/\|/g,"\n").replace(/\n\n/g,"");
    content = addReadme + content;
    content.trim().split('\n').forEach(function(v, i) {
      (i+1)%3==0|(i+2)%3==0 ? fs.appendFileSync(readme,v+"|") : fs.appendFileSync(readme,"\n|"+v+"|");
    })
  }
})
// 写入 list
fs.existsSync(list) || fs.writeFileSync(list,"");
fs.readFile(list, 'utf8', (err, content) => {
  if (err) {
    $.error(err);
    return
  }
  if (!content.includes($.date)) {
    fs.writeFileSync(list,"## Bing Wallpaper\n");
    content = content.replace("## Bing Wallpaper","");
    content = addList + content;
    content.trim().split('\n').forEach(function(v, i) {
      fs.appendFileSync(list,v + "\n");
    })
  }
})
// 写入 json
$.write(addJson,$.enddate);
  • 完整的代码
const $ = API("bing"); 
const bing = "https://www.bing.com"
const bing_api = "https://global.bing.com"
const url =  bing_api + "/HPImageArchive.aspx?format=js&idx=0&n=1&pid=hp&FORM=BEHPTB&uhd=1&uhdwidth=384&uhdheight=216&setmkt=zh-cn&setlang=zh-cn";
const headers = {
    "Origin": bing_api,
    "Host": bing_api.replace("https://",""),
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36 Edge/14.16299",
    "Referer": bing_api
};
const request = {
    url: url,
    headers: headers
};
$.http.get(request)
  .then((resp) => {
    $.data = $.toObj(resp.body).images[0];
    $.urltiny = bing + $.data.url
    $.url = $.urltiny.replace(/&.*/, "");
    $.enddate = $.data.enddate;
    $.date = $.enddate.slice(0,4) + "-" + $.enddate.slice(4,6) + "-" + $.enddate.slice(6);
    $.copyright = $.data.copyright;
    $.copyrightlink = bing + $.data.copyrightlink;
    if ($.env.isNode) {
      const readme = "README.md";
      const list = "list.md";
      const today = `\n![](${$.url}&w=1000)Today: [${$.copyright}](${$.url})`;
      const addReadme = `![](${$.urltiny})${$.date} [Download UHD](${$.url})`
      const addList = `${$.date} | [${$.copyright}](${$.url}) \n`
      const addJson = {url:$.url,copyright:$.copyright,copyrightlink:$.copyrightlink}
      const fs = require("fs");
      // 写入 README
      fs.existsSync(readme) || fs.writeFileSync(readme,"");
      fs.readFile(readme, 'utf8', (err, content) => {
        if (err) {
          $.error(err);
          return
        }
        if (!content.includes($.date)) {
          fs.writeFileSync(readme,"## Bing Wallpaper\n");
          fs.appendFileSync(readme,today);
          fs.appendFileSync(readme,"\n|      |      |      |");
          fs.appendFileSync(readme,"\n| :----: | :----: | :----: |");
          content = content.replace("## Bing Wallpaper","").replace(/^.*Today.*$/mg, "").replace("|      |      |      |","").replace("| :----: | :----: | :----: |","").replace(/\|/g,"\n").replace(/\n\n/g,"");
          content = addReadme + content;
          content.trim().split('\n').forEach(function(v, i) {
            (i+1)%3==0|(i+2)%3==0 ? fs.appendFileSync(readme,v+"|") : fs.appendFileSync(readme,"\n|"+v+"|");
          })
        }
      })
      // 写入 list
      fs.existsSync(list) || fs.writeFileSync(list,"");
      fs.readFile(list, 'utf8', (err, content) => {
        if (err) {
          $.error(err);
          return
        }
        if (!content.includes($.date)) {
          fs.writeFileSync(list,"## Bing Wallpaper\n");
          content = content.replace("## Bing Wallpaper","");
          content = addList + content;
          content.trim().split('\n').forEach(function(v, i) {
            fs.appendFileSync(list,v + "\n");
          })
        }
      })
      // 写入 json
      $.write(addJson,$.enddate);
    }
  })
  .catch((err) => {
    $.error("error‼️" + "\n" + err);
  })
  .finally(() => {
    $.param = {"open-url": $.url,"media-url": $.urltiny};
    $.info(`\n必应每日壁纸\n${$.enddate}🎉\n${$.copyright}\n${$.url}`);
    $.notify("必应每日壁纸", "", $.enddate + "🎉\n" + $.copyright, $.param);
    $.done();
  });
// prettier-ignore
/*********************************** API *************************************/
function ENV(){const t="undefined"!=typeof $task,e="undefined"!=typeof $loon,s="undefined"!=typeof $httpClient&&!e,o="function"==typeof require&&"undefined"!=typeof $jsbox;return{isQX:t,isLoon:e,isSurge:s,isNode:"function"==typeof require&&!o,isJSBox:o,isRequest:"undefined"!=typeof $request,isScriptable:"undefined"!=typeof importModule}}function HTTP(t={baseURL:""}){const{isQX:e,isLoon:s,isSurge:o,isScriptable:i,isNode:n}=ENV(),r=/https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)/;const h={};return["GET","POST","PUT","DELETE","HEAD","OPTIONS","PATCH"].forEach(c=>h[c.toLowerCase()]=(h=>(function(h,c){c="string"==typeof c?{url:c}:c;const l=t.baseURL;l&&!r.test(c.url||"")&&(c.url=l?l+c.url:c.url),c&&c.body&&c.headers&&!c.headers["Content-Type"]&&(c.headers["Content-Type"]="application/x-www-form-urlencoded");const a=(c={...t,...c}).timeout,_={...{onRequest:()=>{},onResponse:t=>t,onTimeout:()=>{}},...c.events};let p,u;if(_.onRequest(h,c),e)p=$task.fetch({method:h,...c});else if(s||o||n)p=new Promise((t,e)=>{(n?require("request"):$httpClient)[h.toLowerCase()](c,(s,o,i)=>{s?e(s):t({statusCode:o.status||o.statusCode,headers:o.headers,body:i})})});else if(i){const t=new Request(c.url);t.method=h,t.headers=c.headers,t.body=c.body,p=new Promise((e,s)=>{t.loadString().then(s=>{e({statusCode:t.response.statusCode,headers:t.response.headers,body:s})}).catch(t=>s(t))})}const d=a?new Promise((t,e)=>{u=setTimeout(()=>(_.onTimeout(),e(`${h} URL: ${c.url} exceeds the timeout ${a} ms`)),a)}):null;return(d?Promise.race([d,p]).then(t=>(clearTimeout(u),t)):p).then(t=>_.onResponse(t))})(c,h))),h}function API(t="untitled",e=!1){const{isQX:s,isLoon:o,isSurge:i,isNode:n,isJSBox:r,isScriptable:h}=ENV();return new class{constructor(t,e){this.name=t,this.debug=e,this.http=HTTP(),this.env=ENV(),this.node=(()=>{if(n){return{fs:require("fs")}}return null})(),this.initCache();Promise.prototype.delay=function(t){return this.then(function(e){return((t,e)=>new Promise(function(s){setTimeout(s.bind(null,e),t)}))(t,e)})}}initCache(){if(s&&(this.cache=JSON.parse($prefs.valueForKey(this.name)||"{}")),(o||i)&&(this.cache=JSON.parse($persistentStore.read(this.name)||"{}")),n){let t="root.json";this.node.fs.existsSync(t)||this.node.fs.writeFileSync(t,JSON.stringify({}),{flag:"wx"},t=>console.log(t)),this.root={},t=`${this.name}.json`,this.node.fs.existsSync(t)?this.cache=JSON.parse(this.node.fs.readFileSync(`${this.name}.json`)):(this.node.fs.writeFileSync(t,JSON.stringify({}),{flag:"wx"},t=>console.log(t)),this.cache={})}}persistCache(){const t=JSON.stringify(this.cache,null,2);s&&$prefs.setValueForKey(t,this.name),(o||i)&&$persistentStore.write(t,this.name),n&&(this.node.fs.writeFileSync(`${this.name}.json`,t,{flag:"w"},t=>console.log(t)),this.node.fs.writeFileSync("root.json",JSON.stringify(this.root,null,2),{flag:"w"},t=>console.log(t)))}write(t,e){if(this.log(`SET ${e}`),-1!==e.indexOf("#")){if(e=e.substr(1),i||o)return $persistentStore.write(t,e);if(s)return $prefs.setValueForKey(t,e);n&&(this.root[e]=t)}else this.cache[e]=t;this.persistCache()}read(t){return this.log(`READ ${t}`),-1===t.indexOf("#")?this.cache[t]:(t=t.substr(1),i||o?$persistentStore.read(t):s?$prefs.valueForKey(t):n?this.root[t]:void 0)}delete(t){if(this.log(`DELETE ${t}`),-1!==t.indexOf("#")){if(t=t.substr(1),i||o)return $persistentStore.write(null,t);if(s)return $prefs.removeValueForKey(t);n&&delete this.root[t]}else delete this.cache[t];this.persistCache()}notify(t,e="",c="",l={}){const a=l["open-url"],_=l["media-url"];if(s&&$notify(t,e,c,l),i&&$notification.post(t,e,c+`${_?"\n多媒体:"+_:""}`,{url:a}),o){let s={};a&&(s.openUrl=a),_&&(s.mediaUrl=_),"{}"===JSON.stringify(s)?$notification.post(t,e,c):$notification.post(t,e,c,s)}if(n)return new Promise(async s=>{const o=(e?`${e}\n`:"")+c+(a?`\n点击跳转: ${a}`:"")+(_?"\n多媒体: "+_:"");await this.sendNotify(t,o,{url:a}),s()});if(h){const s=c+(a?`\n点击跳转: ${a}`:"")+(_?`\n多媒体: ${_}`:"");if(r){require("push").schedule({title:t,body:(e?e+"\n":"")+s})}else console.log(`${t}\n${e}\n${s}\n\n`)}}sendNotify(t,e,s={},o="\n\n仅供用于学习 https://ooxx.be/js"){return new Promise(async i=>{this.querystring=require("querystring"),this.timeout=this.timeout||"15000",e+=o,this.setParam(),await Promise.all([this.serverNotify(t,e),this.pushPlusNotify(t,e)]),t=t.match(/.*?(?=\s?-)/g)?t.match(/.*?(?=\s?-)/g)[0]:t,await Promise.all([this.BarkNotify(t,e,s),this.tgBotNotify(t,e),this.ddBotNotify(t,e),this.qywxBotNotify(t,e),this.qywxamNotify(t,e),this.iGotNotify(t,e,s),this.gobotNotify(t,e)])})}setParam(){this.SCKEY=process.env.SCKEY||this.SCKEY,this.PUSH_PLUS_TOKEN=process.env.PUSH_PLUS_TOKEN||this.PUSH_PLUS_TOKEN,this.PUSH_PLUS_USER=process.env.PUSH_PLUS_USER||this.PUSH_PLUS_USER,this.BARK_PUSH=process.env.BARK_PUSH||this.BARK_PUSH,this.BARK_SOUND=process.env.BARK_SOUND||this.BARK_SOUND,this.BARK_GROUP=process.env.BARK_GROUP||"AsVow",this.BARK_PUSH&&!this.BARK_PUSH.includes("http")&&(this.BARK_PUSH=`https://api.day.app/${this.BARK_PUSH}`),this.TG_BOT_TOKEN=process.env.TG_BOT_TOKEN||this.TG_BOT_TOKEN,this.TG_USER_ID=process.env.TG_USER_ID||this.TG_USER_ID,this.TG_PROXY_AUTH=process.env.TG_PROXY_AUTH||this.TG_PROXY_AUTH,this.TG_PROXY_HOST=process.env.TG_PROXY_HOST||this.TG_PROXY_HOST,this.TG_PROXY_PORT=process.env.TG_PROXY_PORT||this.TG_PROXY_PORT,this.TG_API_HOST=process.env.TG_API_HOST||"api.telegram.org",this.DD_BOT_TOKEN=process.env.DD_BOT_TOKEN||this.DD_BOT_TOKEN,this.DD_BOT_SECRET=process.env.DD_BOT_SECRET||this.DD_BOT_SECRET,this.QYWX_KEY=process.env.QYWX_KEY||this.QYWX_KEY,this.QYWX_AM=process.env.QYWX_AM||this.QYWX_AM,this.IGOT_PUSH_KEY=process.env.IGOT_PUSH_KEY||this.IGOT_PUSH_KEY,this.GOBOT_URL=process.env.GOBOT_URL||this.GOBOT_URL,this.GOBOT_TOKEN=process.env.GOBOT_TOKEN||this.GOBOT_TOKEN,this.GOBOT_QQ=process.env.GOBOT_QQ||this.GOBOT_QQ}serverNotify(t,e,s=2100){return new Promise(o=>{if(this.SCKEY){e=e.replace(/[\n\r]/g,"\n\n");const i={url:this.SCKEY.includes("SCT")?`https://sctapi.ftqq.com/${this.SCKEY}.send`:`https://sc.ftqq.com/${this.SCKEY}.send`,body:`text=${t}&desp=${e}`,headers:{"Content-Type":"application/x-www-form-urlencoded"},timeout:this.timeout};setTimeout(()=>{this.http.post(i).then(t=>{const e=this.toObj(t.body);0===e.errno||0===e.data.errno?console.log("server酱发送通知消息成功🎉\n"):1024===e.errno?console.log(`server酱发送通知消息异常: ${e.errmsg}\n`):console.log(`server酱发送通知消息异常\n${this.toStr(e)}`)}).catch(t=>{console.log("server酱发送通知调用API失败!!\n"),this.error(t)}).finally(()=>{o()})},s)}else o()})}pushPlusNotify(t,e){return new Promise(s=>{if(this.PUSH_PLUS_TOKEN){e=e.replace(/[\n\r]/g,"<br>");const o={token:`${this.PUSH_PLUS_TOKEN}`,title:`${t}`,content:`${e}`,topic:`${this.PUSH_PLUS_USER}`},i={url:"https://www.pushplus.plus/send",body:this.toStr(o),headers:{"Content-Type":" application/json"},timeout:this.timeout};this.http.post(i).then(t=>{const e=this.toObj(t.body);200===e.code?console.log(`push+发送${this.PUSH_PLUS_USER?"一对多":"一对一"}通知消息完成。\n`):console.log(`push+发送${this.PUSH_PLUS_USER?"一对多":"一对一"}通知消息失败:${e.msg}\n`)}).catch(t=>{console.log(`push+发送${this.PUSH_PLUS_USER?"一对多":"一对一"}通知消息失败!!\n`),this.error(t)}).finally(()=>{s()})}else s()})}BarkNotify(t,e,s={}){return new Promise(o=>{if(this.BARK_PUSH){const i={url:`${this.BARK_PUSH}/${encodeURIComponent(t)}/${encodeURIComponent(e)}?sound=${this.BARK_SOUND}&group=${this.BARK_GROUP}&${this.querystring.stringify(s)}`,headers:{"Content-Type":"application/x-www-form-urlencoded"},timeout:this.timeout};this.http.get(i).then(t=>{const e=this.toObj(t.body);200===e.code?console.log("Bark APP发送通知消息成功🎉\n"):console.log(`${e.message}\n`)}).catch(t=>{console.log("Bark APP发送通知调用API失败!!\n"),this.error(t)}).finally(()=>{o()})}else o()})}tgBotNotify(t,e){return new Promise(s=>{if(this.TG_BOT_TOKEN&&this.TG_USER_ID){const o={url:`https://${this.TG_API_HOST}/bot${this.TG_BOT_TOKEN}/sendMessage`,body:`chat_id=${this.TG_USER_ID}&text=${t}\n\n${e}&disable_web_page_preview=true`,headers:{"Content-Type":"application/x-www-form-urlencoded"},timeout:this.timeout};if(this.TG_PROXY_HOST&&this.TG_PROXY_PORT){const t={host:this.TG_PROXY_HOST,port:1*this.TG_PROXY_PORT,proxyAuth:this.TG_PROXY_AUTH};Object.assign(o,{proxy:t})}this.http.post(o).then(t=>{const e=this.toObj(t.body);e.ok?console.log("Telegram发送通知消息成功🎉。\n"):400===e.error_code?console.log("请主动给bot发送一条消息并检查接收用户ID是否正确。\n"):401===e.error_code&&console.log("Telegram bot token 填写错误。\n")}).catch(t=>{console.log("Telegram发送通知消息失败!!\n"),this.error(t)}).finally(()=>{s()})}else s()})}ddBotNotify(t,e){return new Promise(s=>{const o={url:`https://oapi.dingtalk.com/robot/send?access_token=${this.DD_BOT_TOKEN}`,json:{msgtype:"text",text:{content:` ${t}\n\n${e}`}},headers:{"Content-Type":"application/json"},timeout:this.timeout};if(this.DD_BOT_TOKEN&&this.DD_BOT_SECRET){const t=require("crypto"),e=Date.now(),i=t.createHmac("sha256",this.DD_BOT_SECRET);i.update(`${e}\n${this.DD_BOT_SECRET}`);const n=encodeURIComponent(i.digest("base64"));o.url=`${o.url}&timestamp=${e}&sign=${n}`,this.http.post(o).then(t=>{const e=this.toObj(t.body);0===e.errcode?console.log("钉钉发送通知消息成功🎉。\n"):console.log(`${e.errmsg}\n`)}).catch(t=>{console.log("钉钉发送通知消息失败!!\n"),this.error(t)}).finally(()=>{s()})}else this.DD_BOT_TOKEN?this.http.post(o).then(t=>{const e=this.toObj(t.body);0===e.errcode?console.log("钉钉发送通知消息完成。\n"):console.log(`${e.errmsg}\n`)}).catch(t=>{console.log("钉钉发送通知消息失败!!\n"),this.error(t)}).finally(()=>{s()}):s()})}qywxBotNotify(t,e){return new Promise(s=>{const o={url:`https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=${this.QYWX_KEY}`,json:{msgtype:"text",text:{content:` ${t}\n\n${e}`}},headers:{"Content-Type":"application/json"},timeout:this.timeout};this.QYWX_KEY?this.http.post(o).then(t=>{const e=this.toObj(t.body);0===e.errcode?console.log("企业微信发送通知消息成功🎉。\n"):console.log(`${e.errmsg}\n`)}).catch(t=>{console.log("企业微信发送通知消息失败!!\n"),this.error(t)}).finally(()=>{s()}):s()})}ChangeUserId(t){if(this.QYWX_AM_AY=this.QYWX_AM.split(","),this.QYWX_AM_AY[2]){const e=this.QYWX_AM_AY[2].split("|");let s="";for(let o=0;o<e.length;o++){const i="签到号 "+(o+1);t.match(i)&&(s=e[o])}return s||(s=this.QYWX_AM_AY[2]),s}return"@all"}qywxamNotify(t,e){return new Promise(s=>{if(this.QYWX_AM){this.QYWX_AM_AY=this.QYWX_AM.split(",");const o={url:"https://qyapi.weixin.qq.com/cgi-bin/gettoken",json:{corpid:`${this.QYWX_AM_AY[0]}`,corpsecret:`${this.QYWX_AM_AY[1]}`},headers:{"Content-Type":"application/json"},timeout:this.timeout};let i;this.http.post(o).then(s=>{const o=e.replace(/\n/g,"<br/>"),n=this.toObj(s.body).access_token;switch(this.QYWX_AM_AY[4]){case"0":i={msgtype:"textcard",textcard:{title:`${t}`,description:`${e}`,url:"https://ooxx.be/js",btntxt:"更多"}};break;case"1":i={msgtype:"text",text:{content:`${t}\n\n${e}`}};break;default:i={msgtype:"mpnews",mpnews:{articles:[{title:`${t}`,thumb_media_id:`${this.QYWX_AM_AY[4]}`,author:"智能助手",content_source_url:"",content:`${o}`,digest:`${e}`}]}}}this.QYWX_AM_AY[4]||(i={msgtype:"text",text:{content:`${t}\n\n${e}`}}),i={url:`https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=${n}`,json:{touser:`${this.ChangeUserId(e)}`,agentid:`${this.QYWX_AM_AY[3]}`,safe:"0",...i},headers:{"Content-Type":"application/json"}}}),this.http.post(i).then(t=>{const s=this.toObj(s);0===s.errcode?console.log("成员ID:"+this.ChangeUserId(e)+"企业微信应用消息发送通知消息成功🎉。\n"):console.log(`${s.errmsg}\n`)}).catch(t=>{console.log("成员ID:"+this.ChangeUserId(e)+"企业微信应用消息发送通知消息失败!!\n"),this.error(t)}).finally(()=>{s()})}else s()})}iGotNotify(t,e,s={}){return new Promise(o=>{if(this.IGOT_PUSH_KEY){if(this.IGOT_PUSH_KEY_REGX=new RegExp("^[a-zA-Z0-9]{24}$"),!this.IGOT_PUSH_KEY_REGX.test(this.IGOT_PUSH_KEY))return console.log("您所提供的IGOT_PUSH_KEY无效\n"),void o();const i={url:`https://push.hellyw.com/${this.IGOT_PUSH_KEY.toLowerCase()}`,body:`title=${t}&content=${e}&${this.querystring.stringify(s)}`,headers:{"Content-Type":"application/x-www-form-urlencoded"},timeout:this.timeout};this.http.post(i).then(t=>{const e=this.toObj(t.body);0===e.ret?console.log("iGot发送通知消息成功🎉\n"):console.log(`iGot发送通知消息失败:${e.errMsg}\n`)}).catch(t=>{console.log("iGot发送通知调用API失败!!\n"),this.error(t)}).finally(()=>{o()})}else o()})}gobotNotify(t,e,s=2100){return new Promise(o=>{if(this.GOBOT_URL){const i={url:`${this.GOBOT_URL}?access_token=${this.GOBOT_TOKEN}&${this.GOBOT_QQ}`,body:`message=${t}\n${e}`,headers:{"Content-Type":"application/x-www-form-urlencoded"},timeout:this.timeout};setTimeout(()=>{this.http.post(i).then(t=>{const e=this.toObj(t.body);0===e.retcode?console.log("go-cqhttp发送通知消息成功🎉\n"):100===e.retcode?console.log(`go-cqhttp发送通知消息异常: ${e.errmsg}\n`):console.log(`go-cqhttp发送通知消息异常\n${this.toStr(e)}`)}).catch(t=>{console.log("发送go-cqhttp通知调用API失败!!\n"),this.error(t)}).finally(()=>{o()})},s)}else o()})}log(t){this.debug&&console.log(`[${this.name}] LOG: ${this.toStr(t)}`)}info(t){console.log(`[${this.name}] INFO: ${this.toStr(t)}`)}error(t){console.log(`[${this.name}] ERROR: ${this.toStr(t)}`)}wait(t){return new Promise(e=>setTimeout(e,t))}done(t={}){s||o||i?$done(t):n&&!r&&"undefined"!=typeof $context&&($context.headers=t.headers,$context.statusCode=t.statusCode,$context.body=t.body)}toObj(t){if("object"==typeof t||t instanceof Object)return t;try{return JSON.parse(t)}catch(e){return t}}toStr(t){if("string"==typeof t||t instanceof String)return t;try{return JSON.stringify(t)}catch(e){return t}}}(t,e)}
/*****************************************************************************/

扩展

基于上述资料,自建壁纸服务 https://asvow.com/bing

参数代码 参数含义 可用参数
rand 是否随机显示最近8天内的图片 true or false
day 显示指定的最近图片 -1,0,1,2,3,4,5,6,7(0为今天,-1为昨天)
size 指定获取图片大小 宽x高(数字)
info 获取图片基础信息(json格式) true or false
  • 以上所有参数均非必要,默认参数为rand=false,day=0,size=3840x2160,info=false
  • 参考分辨率:3840x2160、1920x1080、1366x768、1280x768、1024x768、800x600、800x480、640x480、480x320、320x240

例:分辨率1920x1080、图片随机显示
https://asvow.com/bing?size=1920x1080&rand=true

参考

[1] liyonghuan/daily-bing-wallpaper
[2] 如何使用 Github Actions 自动抓取每日必应壁纸?
[3] 随机显示必应每日一图,API代码及调用方法









除另有声明外,本博客文章均采用 知识共享许可协议 - 署名标示 4.0(CC BY 4.0)进行授权许可。 Made with by AsVow

最近的文章

luci-app-tailscale插件编写的爬坑记录

背景 一直以来笔者都用OpenWrt的ZeroTier服务进行组网,最近网络环境不太稳定,经常出现内网无法连接的情况。于是笔者打算使用Tailscale作为替代方案。现有的LuCI插件不能完全满足如 ……

js笔记 继续阅读
更早的文章

Node.js多平台通知推送

说明 OpenAPI是@Peng-YM编写的跨平台脚本API,同时支持Quantumult X, Loon, Surge, JSBox 和Node.js。最近笔者将其与@lxk0301的多平台通知进行 ……

js笔记 继续阅读