钉钉机器人接入中,你应该知道的一些坑

常见错误问题

图片不展示

  • 图片必须是网络路径,本地路径的图片,base64好像是不行的

@指定的人不成功

以markdown格式举例,常用的@指定人的方式,一种是手机号,一种是通过userId来指定的

手机号@指定的人

手机号@指定的人,在atMobiles中填入手机号后,一定要在text字段中拼接手机号信息

  {
    "msgtype": "markdown",
    "markdown": {
      "title": `打包发布通知`,
      "text": `#### 应用发布成功 @150xxxxxxxx 
 > ...`,
    },
    "at": {
      "atMobiles": ['150xxxxxxxx'],
      "atDingtalkIds": [],
      "isAtAll": false
    }
  }

userId@指定的人

userId@指定的人,官方文档好像没及时更新,使用atUserIds字段一直不会成功通知,换为atDingtalkIds就可以了。同时,userId的信息也需要拼接再text字段中

  {
    "msgtype": "markdown",
    "markdown": {
      "title": `打包发布通知`,
      "text": `#### 应用发布成功 @userId1,@userId2 
 > ...`,
    },
    "at": {
      "atMobiles": [],
      "atDingtalkIds": ['userId1', 'userId2'],
      "isAtAll": false
    }
  }

text字段中文本换行错误

对于多行文本换行,应该通过 来换行

  const msgs = ['commit记录1', 'commit记录2', 'commit记录3']
  const desc = msgs.join('

')
  {
    "msgtype": "markdown",
    "markdown": {
      "title": `打包发布通知`,
      "text": `#### 应用发布成功 ${desc}`,
    },
    "at": {
      "atMobiles": [],
      "atDingtalkIds": [],
      "isAtAll": false
    }
  }

使用方式

我这边是在node中做的钉钉机器人发送通知

  // robot.js
  #!/usr/bin/env node
  const https = require('https');

  module.exports = function(token) {
    return {
      send: function(message, callback) {
        const postData = JSON.stringify(message);
        const options = {
          hostname: 'api.dingtalk.com',
          port: 443,
          path: '/robot/send?access_token=' + token,
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          }
        };
        const request = https.request(options, function(response) {
          const data = [];
          let count = 0;
          response.setEncoding('utf8');

          response.on('data', function(chunk) {
            data.push(chunk);
            count += chunk.length;
          });

          response.on('end', function() {
            let buffer;
            const length = data.length;

            if (length == 0) {
              buffer = new Buffer(0);
            } else if (length == 1) {
              buffer = data[0];
            } else {
              buffer = new Buffer(count);
              for (let index = 0, position = 0; index < length; index++) {
                let chunk = data[index];
                chunk.copy(buffer, position);
                position += chunk.length;
              }
            }

            const datastring = buffer.toString();
            const result = JSON.parse(datastring);
            if (result.errcode) {
              return callback(new Error(result.errmsg));
            }

            return callback(null, result);
          });
        });
        request.on('error', callback);

        request.write(postData);
        request.end();
      }
    };
  };
  // index.js
  #!/usr/bin/env node
  const robot = require('./robot')

  const robotConfig = {
    token: '',
    // 需要@人员手机号
    atMobiles: [],
    // 被@人的用户ID
    atUserIds: [],
    // 是否需要@所有人
    isAtAll: false,
    // 指定打包机器人
    robot: 1,
    // 打包编译开启进程数
    threads: 8,
    // 钉钉群通知关键字
    keyword: ['发布'],
  };

  const dingdingMessage = () => {
  const { token, atMobiles = [], atUserIds = [], isAtAll = false, keyword = [] } = robotConfig || {}
  const msgs = ['commit记录1', 'commit记录2', 'commit记录3'].join('

')
  if (!token) {
    console.log('------钉钉机器人token不存在------')
    return false
  }
  if (!keyword.length) {
    console.log('------请填写钉钉机器人关键字------')
    return false
  }
  // 手机号列表
  const notify = atMobiles.length ? atMobiles.map(item => `@${item}`) : ''
  // userId列表
  const userIdList = atUserIds.length ? atUserIds.map(item => `@${item}`) : ''
  // 关键字列表
  const keywordList = keyword.join('')
  robot(token).send(
  {
    "msgtype": "markdown",
    "markdown": {
      "title": `打包发布通知${keywordList}`,
      "text": `#### 应用${projectConfig.projectname}发布${type ? '成功' : '失败'} ${notify} ${userIdList} 
 > ${config.desc} 

 最近三条提交: 

 ${msgs}`,
    },
    "at": {
      "atMobiles": atMobiles,
      "atDingtalkIds": atUserIds,
      "isAtAll": isAtAll
    }
    }, (err, data) => {
      if (err) {
        if (err.toString().indexOf('keywords not in content') !== -1) {
          console.log('------机器人关键词不匹配,请修改------')
        } else {
          console.error(err);
        }
        return
      }
      console.log(data);
      if (data.errcode === 0) {
        process.exit()
      }
    })
  }
原文地址:https://www.cnblogs.com/sk-3/p/15411669.html