-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathplugin.js
95 lines (87 loc) · 2.28 KB
/
plugin.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
const process = require('process');
const render = require('drone-render');
const request = require('request-promise-native');
function log(...args) {
const debug = process.env.PLUGIN_DEBUG;
if (!debug) {
return;
}
// eslint-disable-next-line
console.log(...args);
}
function configParser(configs) {
const ret = {};
for (const configName in configs) {
const { env, def } = configs[configName];
if (def !== undefined) {
ret[configName] = typeof def === 'function' ? def() : def;
}
env.split(/\s*,\s*/).some(envar => {
if (process.env.hasOwnProperty(envar)) {
ret[configName] = process.env[envar];
return true;
}
return false;
});
}
return fn => fn(ret);
}
function getAccessToken(corpid, corpsecret) {
return request({
url: 'https://qyapi.weixin.qq.com/cgi-bin/gettoken',
qs: { corpid, corpsecret },
json: true
}).then(resp => {
if (!resp.access_token) {
throw new Error(resp);
}
return resp.access_token;
});
}
function sendMsgFromWork({
access_token,
to_user: touser,
to_party: toparty,
to_tag: totag,
msg_type: msgtype,
agent_id: agentid,
msg_url: url,
btn_text: btntext,
message,
safe,
title
}) {
title = title && render(title);
totag = totag && render(totag);
btntext = btntext && render(btntext);
const description = message && render(message);
const textcard = { title, url, btntext, description };
return request({
method: 'POST',
url: 'https://qyapi.weixin.qq.com/cgi-bin/message/send',
qs: { access_token },
body: { touser, toparty, totag, msgtype, agentid, safe, textcard },
json: true
});
}
async function exec({ corpid, corp_secret, ...config }) {
try {
log('config parse end, config except corpid and corp_secret:', config);
const access_token = await getAccessToken(corpid, corp_secret);
log('access_token request success!');
log('http request data:', config);
const resp = await sendMsgFromWork({ ...config, access_token });
log('send msg success, and http response content is:');
log(resp);
// eslint-disable-next-line
console.log('==Send notification to Wechat success!==');
} catch (e) {
console.error(e);
}
}
module.exports = {
configParser,
getAccessToken,
sendMsgFromWork,
exec
};