钉钉自定义机器人 node 加签

钉钉自定义机器人:官方文档

机器人群通知

通过在钉钉群里添加自定义机器人,获得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 = {
      base_url:'',
      access_token: '',
      secret: ''
    }
    constructor(_initData){
      const { access_token, secret, base_url = 'https://oapi.dingtalk.com/robot/send' } = _initData
      const timestamp = new Date().getTime()
      const sign = this.signFn(secret,`${timestamp}\n${secret}`) 
      this._webhookUrl = `${base_url}?access_token=${access_token}&timestamp=${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 包 ding-bot-sdk,也可以直接安装 npm 包来使用 npm install ding-bot-sdk

posted @ 2021-01-17 10:41  c-137Summer  阅读(1583)  评论(2编辑  收藏  举报