首页 > 开发 > JS > 正文

nodejs通过钉钉群机器人推送消息的实现代码

2024-05-06 16:50:31
字体:
来源:转载
供稿:网友

Intro

最近在用 nodejs 写爬虫,之前的 nodejs 爬虫代码用 js 写的,感觉可维护性太差,也没有智能提示,于是把js改用ts(typescript)重写一下,提升代码质量。

爬虫启动之后不定期会出现验证码反爬虫,需要输入验证码才能继续,于是想在需要输入验证码时推送一个消息给用户,让用户输入验证码以继续爬虫的整个流程。我们平时用钉钉办公,钉钉群有个机器人,很方便于是就实现了一个通过钉钉的群机器人实现消息推送。

实现

代码是 ts 实现的,用了 request 发起http请求,具体参数参考钉钉官方文档,只实现了文本消息的推送,其它消息类似,再进行一层封装,实现代码如下:

import * as request from "request";import * as log4js from "log4js";const logger = log4js.getLogger("DingdingBot");const ApplicationTypeHeader:string = "application/json;charset=utf-8";// DingdingBot// https://open-doc.dingtalk.com/microapp/serverapi2/qf2nxqexport class DingdingBot{  private readonly _webhookUrl:string;  constructor(webhookUrl:string){    this._webhookUrl = webhookUrl;  }  public pushMsg (msg: string, atMobiles?: Array<string>): boolean{    try {      let options: request.CoreOptions = {        headers: {         "Content-Type": ApplicationTypeHeader        },        json: {          "msgtype": "text",           "text": {            "content": msg          },           "at": {            "atMobiles": atMobiles == null ? [] : atMobiles,            "isAtAll": false          }        }       };      request.post(this._webhookUrl, options, function(error, response, body){        logger.debug(`push msg ${msg}, response: ${JSON.stringify(body)}`);      });    }    catch(err) {      console.error(err);      return false;    }      }}

使用方式:

// botWebhookUrl 为对应钉钉机器人的 webhook 地址let bot = new DingdingBot(botWebhookUrl);;// 直接推送消息bot.pushMsg("测试消息");// 推送消息并 @ 某些人var mobiles = new Array<string>();mobiles.push("13255573334");bot.pushMsg("测试消息并@", mobiles);

总结

以上所述是小编给大家介绍的nodejs通过钉钉群机器人推送消息的实现代码,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对VeVb武林网网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!


注:相关教程知识阅读请移步到JavaScript/Ajax教程频道。
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表