87 lines
2.3 KiB
JavaScript
87 lines
2.3 KiB
JavaScript
'use strict';
|
|
|
|
class WecomWebhookDriver {
|
|
constructor(ctx, options = {}) {
|
|
this.ctx = ctx;
|
|
this.options = options;
|
|
}
|
|
|
|
buildTextContent(payload = {}) {
|
|
const message = payload.message || {};
|
|
const lines = [
|
|
String(message.title || '').trim(),
|
|
String(message.content || message.body || '').trim(),
|
|
].filter(Boolean);
|
|
|
|
if (message.url) {
|
|
lines.push(`链接:${String(message.url).trim()}`);
|
|
}
|
|
|
|
return lines.join('\n') || '您有一条新的业务通知';
|
|
}
|
|
|
|
buildMarkdownContent(payload = {}) {
|
|
const message = payload.message || {};
|
|
const title = String(message.title || '业务通知').trim();
|
|
const content = String(message.content || message.body || '').trim();
|
|
const url = String(message.url || '').trim();
|
|
const lines = [
|
|
`**${title}**`,
|
|
content ? `>${content}` : '',
|
|
url ? `[点击查看](${url})` : '',
|
|
].filter(Boolean);
|
|
|
|
return lines.join('\n');
|
|
}
|
|
|
|
buildRequestData(payload = {}) {
|
|
const messageType = String(payload.message && payload.message.type || 'text').trim().toLowerCase();
|
|
|
|
if ([ 'image', 'file' ].includes(messageType)) {
|
|
return {
|
|
msgtype: 'markdown',
|
|
markdown: {
|
|
content: this.buildMarkdownContent(payload),
|
|
},
|
|
};
|
|
}
|
|
|
|
return {
|
|
msgtype: 'text',
|
|
text: {
|
|
content: this.buildTextContent(payload),
|
|
},
|
|
};
|
|
}
|
|
|
|
async send({ hook, payload }) {
|
|
const requestData = this.buildRequestData(payload);
|
|
this.ctx.logger.info('[WecomWebhookDriver.send] 发送内容', {
|
|
hookUrl: String(hook && hook.hook_url || '').substring(0, 80),
|
|
requestData,
|
|
});
|
|
const requestOptions = {
|
|
method: 'POST',
|
|
headers: {
|
|
'content-type': 'application/json',
|
|
},
|
|
timeout: 5000,
|
|
dataType: 'json',
|
|
contentType: 'json',
|
|
data: requestData,
|
|
};
|
|
|
|
const response = await this.ctx.curl(String(hook && hook.hook_url || ''), requestOptions);
|
|
|
|
return {
|
|
hookId: Number(hook && hook.id) || 0,
|
|
hookType: 'wecom',
|
|
hookUrl: String(hook && hook.hook_url || ''),
|
|
status: Number(response && response.status) || 200,
|
|
response: response && response.data !== undefined ? response.data : null,
|
|
};
|
|
}
|
|
}
|
|
|
|
module.exports = WecomWebhookDriver;
|