钉钉自定义机器人: 官方文档
机器人群通知
通过在钉钉群里添加自定义机器人, 获得 webhook 地址和 secret 加签, 根据加密规则获得可以发送消息的地址, 实现消息的推送
可以集成到 node 脚本中, 实现特定情形的群通知
node 封装代码
bot.JS
- const request = require('request');
- const crypto = require('crypto');
- const headers= {
- "Content-Type": "application/json;charset=utf-8"
- };
- const defaultOptions = {
- msgtype: "text",
- text: {
- content: 'hello~'
- }
- }
- // https://ding-doc.dingtalk.com/document/app/custom-robot-access
- class Bot{
- _initData = {
- access_token: '',
- secret: ''
- }
- _webhookUrl: string
- constructor(_initData){
- const { access_token, secret } = _initData
- const timestamp = new Date().getTime()
- const sign = this.signFn(secret,`${timestamp}\n${secret}`)
- this._webhookUrl = `https://oapi.dingtalk.com/robot/send?access_token=${access_token}×tamp=${timestamp}&sign=${sign}`
- }
- signFn = (secret, content) =>{ // 加签
- const str = crypto.createHmac('sha256', secret).update(content)
- .digest()
- .toString('base64');
- return encodeURIComponent(str);
- }
- send (JSON = defaultOptions){
- try {
- let options = {
- headers,
- JSON
- };
- request.post(this._webhookUrl, options, function(_error, _response, body){
- console.log(`send msg, response: ${JSON.stringify(body)}`);
- });
- }
- catch(err) {
- console.error(err);
- return false;
- }
- }
- }
- module.exports = Bot
使用
- import Bot from './bot.js'
- // 初始化实例
- // Webhook 地址: https://oapi.dingtalk.com/robot/send?access_token=xxx
- const bot = new Bot({
- access_token: 'xxx', // Webhook 地址后的 access_token
- secret: 'xxx' // 安全设置: 加签的 secret
- })
- // 发送消息
- bot.send({
- msgtype: "text",
- text: {
- content: 'hello~'
- }
- })
上述已封装到 NPM 包 https://www.npmjs.com/package/ding-bot-sdk , 也可以直接安装 NPM 包来使用 NPM install ding-bot-sdk
来源: http://www.bubuko.com/infodetail-3716901.html