Authored by zhangwenxue

feature(alipay): add dingtalk robot alert

const _ = require('lodash');
const ddAlert = require('./dingding-alert');
const MIN_SEND_INTERVAL = 10 * 1000;
const moment = require('moment');
const AlertManager = {
isAtAll: false,
pendingAgents: {},
post(agent) {
if (!this.pendingAgents[agent.name]) {
this.pendingAgents[agent.name] = agent;
}
this.report();
},
report: _.throttle(() => AlertManager._report(), MIN_SEND_INTERVAL, {leading: true, trailing: true}),
_report() {
const now = Date.now();
let ats = [];
let text = [];
text.push(`**本次告警**: ${moment(now).format('YYYY-MM-DD HH:mm:ss')}\n`);
text.push(`**上次告警**: ${moment(this.lastSendTime).format('YYYY-MM-DD HH:mm:ss')}\n`);
text = text.concat(Object.keys(this.pendingAgents).map(agentName => {
const agent = this.pendingAgents[agentName];
ats = ats.concat(agent.ats);
return agent.getMarkdownReport();
}));
ddAlert(text.join('\n'), _.uniq(ats), this.isAtAll);
this.lastSendTime = now;
this.pendingAgents = {};
}
};
class AlertAgent {
constructor(name, subjectMap, ats = [], isAtAll = false) {
this.name = name;
this.subjectMap = subjectMap;
this.ats = ats;
if (isAtAll) {
AlertManager.isAtAll = true;
}
this.msgs = {};
}
send(subjectId, text = '') {
let msg = _.get(this.msgs, subjectId, {text, count: 0});
this.msgs[subjectId] = msg;
msg.count++;
AlertManager.post(this);
}
getMarkdownReport() {
let report = [`## ${this.name} `];
report.push(this.ats.map(at => `@${at}`).join(' '));
const msgs = Object.keys(this.msgs).map(id => {
const msg = this.msgs[id];
return `- ${this.subjectMap[id]} ${msg.text} ${msg.count}次`;
});
report = report.concat(msgs);
return report.join('\n');
}
}
module.exports = AlertAgent;
... ...
const rp = require('request-promise');
module.exports = (text, atMobiles, isAtAll) => {
const data = {
msgtype: 'markdown',
markdown: {
title: 'ufo-app-web',
text
},
at: {
atMobiles,
isAtAll,
}
};
return rp({
uri: 'https://oapi.dingtalk.com/robot/send?access_token=499f845e894e0aebb6d29ec9f3b186cbb99bfa89cd4347fa4c0e8efd4081ecd5',
method: 'POST',
headers: {
'Content-Type': 'application/json; charset=utf-8'
},
body: JSON.stringify(data)
});
};
... ...