钉钉机器人node封装

228 阅读1分钟

使用钉钉机器人的推送服务,比邮箱推送舒服多了

const request = require("request");

// 钉钉机器人类
class DingdingRoBot {
  _webhookUrl;
  constructor(webhookUrl) {
    this._webhookUrl = webhookUrl;
  }
  
  // 推送消息
  pushMsg(msg, atMobiles) {
    try {
      const options = {
        headers: {
          "Content-Type": "application/json;charset=utf-8",
        },
        json: {
          msgtype: "text",
          text: {
            content: msg,
          },
          at: {
            atMobiles: atMobiles == null ? [] : atMobiles,
            isAtAll: false,
          },
        },
      };
      request.post(this._webhookUrl, options, (error, response, body) => {
        console.log(`push msg ${msg}, response: ${JSON.stringify(body)}`);
      });
    } catch (error) {
      console.error(error);
      return false;
    }
  }
}

/* 调用端 */
// robotWebhookUrl 对应钉钉机器人的 webhook 地址
const robotWebhookUrl =
  "https://oapi.dingtalk.com/robot/send?access_token=xxx";
const robot = new DingdingRoBot(robotWebhookUrl);
// 直接推送消息
robot.pushMsg("测试消息");
// 推送消息并 @ 某些人
const mobiles = ["178xxxxxxxx"];
robot.pushMsg("测试消息并@", mobiles);