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通過釘釘群機器人推送消息的實現代碼,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對錯新站長站網站的支持!
如果你覺得本文對你有幫助,歡迎轉載,煩請注明出處,謝謝!
新聞熱點
疑難解答
圖片精選