欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

自定义钉钉机器人报警

程序员文章站 2024-01-27 17:06:04
...

为了埋点实时监控业务,简单的实现了钉钉机器人报警,钉钉开发官方文档点击

public interface AlarmService {

    Response<Boolean> orderSuccessAlarm(CompanyAppIdEnum companyAppIdEnum, String orderNo, OrderStatusEnum orderStatusEnum);

    Response<Boolean> orderFilterAlarm(CompanyAppIdEnum companyAppIdEnum,Long userId);

}

public class AlarmServcieImpl implements AlarmService {
    @Autowired
    RedisClient RedisClient;

    @Autowired
    ConfigUtil configUtil;

    private static final Log logger = LogFactory.getLog(AlarmServcieImpl.class);

    private static final Long expireTime = 24 * 60 * 60L;

    //创建机器人可获取
    private static final String requestUrl = "https://oapi.dingtalk.com/robot/send?access_token=xxxx";

    @Override
    public Response<Boolean> orderSuccessAlarm(CompanyAppIdEnum companyAppIdEnum, String orderNo, OrderStatusEnum orderStatusEnum) {
        try {
            if (configUtil.isServerTest()) {
                return new Response<>(Boolean.FALSE);
            }
            String count = RedisClient.getString(SystemConstants.ORDER_STATUS_ALARM_ROBOT, companyAppIdEnum.getCompanyId().toString(), DateUtils.getDateStr(new Date()));
            if (Objects.isNull(count)) {
                RedisClient.setString(SystemConstants.ORDER_STATUS_ALARM_ROBOT, "0", expireTime, companyAppIdEnum.getCompanyId().toString(), DateUtils.getDateStr(new Date()));
            }
            dispatcher(companyAppIdEnum, Number.getNumber(Long.valueOf(RedisClient.getString(SystemConstants.ORDER_STATUS_ALARM_ROBOT, companyAppIdEnum.getCompanyId().toString(), DateUtils.getDateStr(new Date())))), AlarmTypeEnum.ORDER_ALARM);
            RedisClient.incrBy(SystemConstants.ORDER_STATUS_ALARM_ROBOT, 1L, companyAppIdEnum.getCompanyId().toString(), DateUtils.getDateStr(new Date()));
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage(), e);
        }
        return new Response<>(Boolean.TRUE);
    }

    @Override
    public Response<Boolean> orderFilterAlarm(CompanyAppIdEnum companyAppIdEnum,Long userId) {
        try {
            if (configUtil.isServerTest()) {
                return new Response<>(Boolean.FALSE);
            }
            String count = RedisClient.getString(SystemConstants.ORDER_FILTER_USER_ALARM_ROBOT, companyAppIdEnum.getCompanyId().toString(), DateUtils.getDateStr(new Date()));
            if (Objects.isNull(count)) {
                RedisClient.setString(SystemConstants.ORDER_FILTER_USER_ALARM_ROBOT, "0", expireTime, companyAppIdEnum.getCompanyId().toString(), DateUtils.getDateStr(new Date()));
            }
            dispatcher(companyAppIdEnum, Number.getNumber(Long.valueOf(RedisClient.getString(SystemConstants.ORDER_STATUS_ALARM_ROBOT, companyAppIdEnum.getCompanyId().toString(), DateUtils.getDateStr(new Date())))), AlarmTypeEnum.ORDER_USER_FILTER);
            RedisClient.incrBy(SystemConstants.ORDER_STATUS_ALARM_ROBOT, 1L, companyAppIdEnum.getCompanyId().toString(), DateUtils.getDateStr(new Date()));
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage(), e);
        }
        return new Response<>(Boolean.TRUE);
    }

    protected void dispatcher(CompanyAppIdEnum companyAppIdEnum, Number number, AlarmTypeEnum alarmTypeEnum) {
        Arrays.asList(Number.values()).forEach(
                p -> {
                    if (p.equals(number) && !Number.INIT_NUMBER.equals(number)) {
                        try {
                            sendNotice(companyAppIdEnum, number, alarmTypeEnum);
                        } catch (IOException e) {
                            e.printStackTrace();
                            logger.error(e.getMessage(), e);
                        }
                        return;
                    }
                }
        );
    }

    public static void main(String[] args) throws IOException {
        sendNotice(CompanyAppIdEnum.WAN_KA, Number.PRELIMINARY_WARNING, AlarmTypeEnum.ORDER_ALARM);
    }

    private static void sendNotice(CompanyAppIdEnum companyAppIdEnum, Number number, AlarmTypeEnum alarmTypeEnum) throws IOException {
        HttpClient httpclient = HttpClients.createDefault();
        HttpPost httppost = new HttpPost(requestUrl);
        httppost.addHeader("Content-Type", "application/json; charset=utf-8");
        String textMsg = getNotice(number, companyAppIdEnum, alarmTypeEnum);
        StringEntity se = new StringEntity(textMsg, "utf-8");
        httppost.setEntity(se);
        HttpResponse response = httpclient.execute(httppost);
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            String result = EntityUtils.toString(response.getEntity(), "utf-8");
            logger.info("报警已经成功发送,机构为:{},响应消息为:{}", companyAppIdEnum.getDesc(), result);
        }
    }

    private static String getNotice(Number number, CompanyAppIdEnum companyAppIdEnum, AlarmTypeEnum alarmTypeEnum) {
        switch (alarmTypeEnum) {
            case ORDER_ALARM:
                return "{\n" +
                        "     \"msgtype\": \"markdown\",\n" +
                        "     \"markdown\": {\"title\":\"推单失败报警\",\n" +
                        "\"text\":\"#### 推单失败报警  \\n " + companyAppIdEnum.getDesc() + "推单失败已超过" + number.getCount() + "单" + "\\n > ![screenshot](https://note.youdao.com/yws/api/personal/file/WEB77f35c865dbd286c3baed15670e8892f?method=download&shareKey=dfdd0302d114373146480ae3d4330af1)\\n  > ######" + new Date() + "发布 [警告]() \"\n" +
                        "     },\n" +
                        "    \"at\": {\n" +
                        "        \"atMobiles\": [\n" +
                        "            \"15168426462\"" +
                        "        ], \n" +
                        "        \"isAtAll\": false\n" +
                        "    }\n" +
                        " }";
            case ORDER_USER_FILTER:
                return "{\n" +
                        "     \"msgtype\": \"markdown\",\n" +
                        "     \"markdown\": {\"title\":\"机构过滤报警\",\n" +
                        "\"text\":\"#### 机构过滤报警  \\n " + companyAppIdEnum.getDesc() + "过滤失败已超过" + number.getCount() + "单" + "\\n > ![screenshot](https://note.youdao.com/yws/api/personal/file/WEB77f35c865dbd286c3baed15670e8892f?method=download&shareKey=dfdd0302d114373146480ae3d4330af1)\\n  > ######" + new Date() + "发布 [警告]() \"\n" +
                        "     },\n" +
                        "    \"at\": {\n" +
                        "        \"atMobiles\": [\n" +
                        "            \"15168426462\"" +
                        "        ], \n" +
                        "        \"isAtAll\": false\n" +
                        "    }\n" +
                        " }";
            default:
                break;
        }
        return "";
    }

    public enum Number {

        INIT_NUMBER(0L, "初始"),

        PRELIMINARY_WARNING(50L, "初步警告"),

        PRELIMINARY_WARNING_PLUS(55L, "初步警告"),

        INTERMEDIATE_WARNING(100L, "中级警告"),

        INTERMEDIATE_WARNING_PLUS(105L, "中级警告"),

        INTERMEDIATE_WARNING_PLUS_PLUS(200L, "中级++警告"),

        INTERMEDIATE_WARNING_PLUS_PLUS_PLUS(205L, "中级++警告"),

        SERIOUS_WARNING(300L, "严重警告"),

        SERIOUS_WARNING_PLUS(305L, "严重警告"),

        SERIOUS_WARNING_PLUS_PLUS(350L, "严重警告"),

        SERIOUS_WARNING_PLUS_PLUS_PLUS(400L, "严重警告"),

        SERIOUS_WARNING_PLUS_PLUS_PLUS_PLUS(500L, "严重警告");

        private Long count;

        private String desc;

        Number(Long count, String desc) {
            this.count = count;
            this.desc = desc;
        }

        public Long getCount() {
            return count;
        }

        public Number setCount(Long count) {
            this.count = count;
            return this;
        }

        public String getDesc() {
            return desc;
        }

        public Number setDesc(String desc) {
            this.desc = desc;
            return this;
        }

        public static Number getNumber(Long count) {
            Number[] number = {INIT_NUMBER};
            Arrays.asList(Number.values()).forEach(
                    p -> {
                        if (p.getCount().equals(count)) {
                            number[0] = p;
                            return;
                        }
                    }
            );
            return number[0];
        }
    }

    public enum AlarmTypeEnum {
        ORDER_ALARM,
        ORDER_USER_FILTER;
    }
}

按照钉钉的文档来开发,创建机器人后,即可获取Webhook地址,整个过程还是很简单的,以上只是提供了一个思路.

更多文章请关注微信公众号:
自定义钉钉机器人报警

相关标签: 钉钉 监控