本青龙面板脚本代码可以实现定时推送51la统计数据到手机

一,配置环境变量(青龙面板->环境变量)

  1. 新建环境变量 LA_ACCESS_KEY,值设为51啦统计V6API 的AccessKey
  2. 新建环境变量 LA_SECRET_KEY,值设为51啦统计V6API SecretKey
  3. 新建环境变量 LA_SITE,配置要获取的站点,值格式为 站点名称|统计ID(即掩码ID),例如:我的blog|MyW9Eh5EAYHyoO8hPV。多个站点的话用逗号隔开,例如:我的blog|MyW9Eh5EAYHyoO8hPV,我的网站|YHyoO8hPVMyW9Eh5EA

备注:AccessKey、SecretKey获取地址:https://v6.51.la/user/application/openapi ,统计ID(即掩码ID)获取地址:https://v6.51.la/user/application。配置多个站点,每次推送会消耗对应数量额度,51啦每月免费额度为100次。

二、安装依赖(青龙面板->依赖管理)

  1. 新建nodejs依赖 51la-v6-openapi-nodejs-sdk

三、创建脚本(青龙面板->脚本管理)

  1. 新建空脚本,文件名写 51la.js
  2. 复制下面代码粘贴保存:
const LaApi = require('51la-v6-openapi-nodejs-sdk');

async function getLaData(maskId) {
  // 初始化函数
  const getLaApiData = new LaApi.init();
  // 设置参数
  getLaApiData.setOptions({
    ak: process.env.LA_ACCESS_KEY,
    sk: process.env.LA_SECRET_KEY,
    type: 2, // 加密方式(非必传,默认为中等) 1为低安全性 2为中等 3为高安全性(双向加密,插件会帮助你完成解密操作)
  });

  const options = {
    url: `https://v6-open.51.la/open/overview/get`,
    json: {maskId, ...getLaApiData.getSign()},
    headers: {
      'Content-Type': 'application/json',
    }
  };

  return new Promise((resolve) => {
    $.post(options, (err, resp, data) => {
      try {
        if (err) {
          console.log(err);
        } else {
          data = JSON.parse(data);
          if (data.success) {
            const d = data.bean;
            const content = `||今日|预计|昨日\n-|-|-|-\nIP|${d.curIp}|${d.predictIp}|${d.beforeIp}\nPV|${d.curPv}|${d.predictPv}|${d.beforePv}\nUV|${d.curUv}|${d.predictUv}|${d.beforeUv}`;
            resolve(content);
          } else {
            console.log(`${data.message}\n`);
          }
        }
      } catch (e) {
          $.logErr(e, resp);
          resolve('');
      }
    });
  });
}


$ = new Env('51LA概况数据');
if(process.env.LA_SITE) {
  const task = [];
  const site_names = [];
  const la_site = process.env.LA_SITE.split(',');
  la_site.forEach(site => {
    if(site) {
      site = site.split('|');
      task.push(new Promise((resolve) => {
        getLaData(site[1] || site[0]).then(content => resolve(content));
      }));
      site_names.push(site[0]);
    }
  });
  Promise.all(task).then(site_datas => {
    const title = '51LA概况数据';
    let content = '';
    for(let i=0; i<site_datas.length; i++) {
      content += `#### ${site_names[i]}\n${site_datas[i]}\n`;
    }

    PushMeNotify(title, content, {type: 'markdown'});
  });
} else {
  $.logErr('请配置环境变量LA_SITE');
}






function PushMeNotify(text, desp, params={}) {
  PUSHME_KEY = process.env.PUSHME_KEY;

  if(!PUSHME_KEY) {
    return require('./sendNotify').sendNotify(text, desp);
  }

  const options = {
    url: `https://push.i-i.me?push_key=${PUSHME_KEY}`,
    json: { title: text, content: desp, ...params },
    headers: {
      'Content-Type': 'application/json',
    },
  };

  $.post(options, (err, resp, data) => {
    try {
      if (err) {
        console.log('PushMeNotify发送通知调用API失败!!\n');
        console.log(err);
      } else {
        if (data === 'success') {
          console.log('PushMe发送通知消息成功!\n');
        } else {
          console.log(`${data}\n`);
        }
      }
    } catch (e) {
      $.logErr(e, resp);
    }
  });
}
// 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) }

四、新建定时任务(青龙面板->定时任务)

  1. 新建任务,名称填写 51la概况数据,命令/脚本填写 node 51la.js,定时规则填写 0 20 * * *,其中 20 代表每天20点推送,你也可以改为其他时间推送。

总结

因为推送数据是 markdown 格式的,所以建议配合android客户端 PushMe 来使用,会后更好显示效果:

IMG_20230801_160155

关键词:青龙面板51啦51la
所属分类:代码片段
本文地址:https://me.i-i.me/article/65.html




评论提示: 点击头像可以回复评论

提交取消回复
[face]@
[uname]  [add_time]
[content]
[reply]
加载更多评论