Skip to content

Instantly share code, notes, and snippets.

@zhengkai
Last active July 16, 2020 02:48
Show Gist options
  • Save zhengkai/2d58268f711ff4cecffa021b263ea6b7 to your computer and use it in GitHub Desktop.
Save zhengkai/2d58268f711ff4cecffa021b263ea6b7 to your computer and use it in GitHub Desktop.
以加签方式发送钉钉 bot 消息,独立文件不需要 npm i
'use strict';
/*
// usage:
const dingbot = require('./dingbot');
const token = '50cb6e954c89afa14fb97754eafd886d658fcda27d05015a26b474e7bd2f0a59';
const secret = 'SEC5a3ecf88f2b3eb50db30ecfc00f53033ac909c99bf7f88fd612bda89d7f3a9dc';
const content = 'foo bar ' + Date.now()
dingbot(content, token, secret);
*/
const crypto = require('crypto');
const https = require('https');
const dingbot = (content, token, secret) => {
const body = {
msgtype: 'text',
text: {
content,
}
};
const ts = Date.now();
const signature= `${ts}\n${secret}`;
const crypt = crypto.createHmac('sha256', secret).update(signature);
const hash = encodeURIComponent(crypt.digest('base64'));
const query = `?access_token=${token}&timestamp=${ts}&sign=${hash}`;
const s = JSON.stringify(body);
const option = {
hostname: 'oapi.dingtalk.com',
path: `/robot/send${query}`,
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(s),
},
};
const req = https.request(option);
req.write(s);
req.end();
}
module.exports = dingbot;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment