首页 > 其他 > 详细

钉钉自定义机器人 node 加签

时间:2021-01-17 11:44:52      阅读:138      评论:0      收藏:0      [点我收藏+]

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

机器人群通知

通过在钉钉群里添加自定义机器人,获得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}&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

钉钉自定义机器人 node 加签

原文:https://www.cnblogs.com/leiting/p/14288356.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!