nodejs pushes messages through a group of nails robot

Keywords: Javascript JSON TypeScript

nodejs pushes messages through a group of nails robot

Intro

Recently, nodejs has been used for writing. The previous nodejs crawler code was written in js. It feels that the maintainability is too poor, and there is no intelligent prompt. Therefore, js is rewritten with ts(typescript) to improve the code quality.

After the start of the crawler, the verification code anti crawler will appear from time to time. It needs to enter the verification code to continue. So I want to push a message to the user when the verification code needs to be entered, so that the user can enter the verification code to continue the whole process of the crawler. We usually use nails to work. There is a robot in nails group, so it is very convenient to implement a group robot to push messages through nails.

Realization

The code is implemented by ts, which uses request to initiate http request. For specific parameters, refer to Nail official documents , only push text message is implemented, other messages are similar, and then a layer of encapsulation is carried out. The implementation code is as follows:

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;
        }        
    }
}

Usage:

// Botwebhook URL is the webhook address of the corresponding nail robot
let bot = new DingdingBot(botWebhookUrl);;
// Push message directly
bot.pushMsg("Test message");
// Push message and @ some people
var mobiles = new Array<string>();
mobiles.push("13255573334");
bot.pushMsg("Test messages and@", mobiles);

Posted by daniel-g on Mon, 18 Nov 2019 06:58:44 -0800