nodejs通過釘釘群機器人推送消息


nodejs 通過釘釘群機器人推送消息

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/qf2nxq
export 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);


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM