Intro
最近在用 nodejs 寫爬蟲,之前的 nodejs 爬蟲代碼用 js 寫的,感覺可維護(hù)性太差,也沒有智能提示,于是把js改用ts(typescript)重寫一下,提升代碼質(zhì)量。
爬蟲啟動(dòng)之后不定期會(huì)出現(xiàn)驗(yàn)證碼反爬蟲,需要輸入驗(yàn)證碼才能繼續(xù),于是想在需要輸入驗(yàn)證碼時(shí)推送一個(gè)消息給用戶,讓用戶輸入驗(yàn)證碼以繼續(xù)爬蟲的整個(gè)流程。我們平時(shí)用釘釘辦公,釘釘群有個(gè)機(jī)器人,很方便于是就實(shí)現(xiàn)了一個(gè)通過釘釘?shù)娜簷C(jī)器人實(shí)現(xiàn)消息推送。
實(shí)現(xiàn)
代碼是 ts 實(shí)現(xiàn)的,用了 request 發(fā)起http請(qǐng)求,具體參數(shù)參考釘釘官方文檔,只實(shí)現(xiàn)了文本消息的推送,其它消息類似,再進(jìn)行一層封裝,實(shí)現(xiàn)代碼如下:
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 為對(duì)應(yīng)釘釘機(jī)器人的 webhook 地址let bot = new DingdingBot(botWebhookUrl);;// 直接推送消息bot.pushMsg("測(cè)試消息");// 推送消息并 @ 某些人var mobiles = new Array<string>();mobiles.push("13255573334");bot.pushMsg("測(cè)試消息并@", mobiles);
總結(jié)
以上所述是小編給大家介紹的nodejs通過釘釘群機(jī)器人推送消息的實(shí)現(xiàn)代碼,希望對(duì)大家有所幫助,如果大家有任何疑問請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)VeVb武林網(wǎng)網(wǎng)站的支持!
如果你覺得本文對(duì)你有幫助,歡迎轉(zhuǎn)載,煩請(qǐng)注明出處,謝謝!
新聞熱點(diǎn)
疑難解答