在钉钉群通过机器人发送信息

在第三方API接口对接中,需要及时获取第三方接口请求结果情况,所以在代码中融合钉钉机器人,对请求的异常结果及时发送通知。

  1. 自定义机器人参考链接
  2. 通用响应参数-封装API的错误码
public interface IErrorCode {

    long getCode();

    String getMessage();
}
  1. 通用响应参数-状态码
/**
 * 〈 通用响应参数-状态码 〉
 *
 * @since JDK1.8
 * 版本 @version 1.0
 */
public enum ResultCode implements IErrorCode {

    SUCCESS(2000, "操作成功"),

    FAILED(5000, "操作失败"),

    VALIDATE_FAILED(4040, "参数检验失败"),

    UNAUTHORIZED(4010, "暂未登录或token已经过期"),

    FORBIDDEN(4030, "没有相关权限");

    private long code;
    private String message;

    ResultCode(long code, String message) {
        this.code = code;
        this.message = message;
    }

    public long getCode() {
        return code;
    }

    public String getMessage() {
        return message;
    }
}

  1. 通过返回类定义
@Data
@ApiModel(description = "通用响应参数")
@Accessors(chain = true)
@NoArgsConstructor
@AllArgsConstructor
public class CommonResult {

    @ApiModelProperty(value = "返回码")
    private long resultCode;

    @ApiModelProperty(value = "返回信息")
    private String message;

    @ApiModelProperty(value = "返回结果集")
    private Object data;

    private CommonResult(long resultCode, String message) {
        this.resultCode = resultCode;
        this.message = message;
    }

    /**
     * 成功返回结果
     */
    public static CommonResult success() {
        return new CommonResult(ResultCode.SUCCESS.getCode(), ResultCode.SUCCESS.getMessage());
    }

    /**
     * 失败返回结果
     */
    public static CommonResult failed() {
        return new CommonResult(ResultCode.FAILED.getCode(), ResultCode.FAILED.getMessage());
    }

    /**
     * 未授权访问返回结果
     * @return
     */
    public static CommonResult unauthorized(){
        return new CommonResult(ResultCode.UNAUTHORIZED.getCode(),ResultCode.UNAUTHORIZED.getMessage());
    }

    /**
     * 参数校验失败返回结果
     * @return
     */
    public static CommonResult validateFailed(){
        return new CommonResult(ResultCode.VALIDATE_FAILED.getCode(),ResultCode.VALIDATE_FAILED.getMessage());
    }

    /**
     * 没有授权返回结果
     * @return
     */
    public static CommonResult forbidden(){
        return new CommonResult(ResultCode.FORBIDDEN.getCode(),ResultCode.FORBIDDEN.getMessage());
    }
    /**
     * 失败返回结果
     *
     * @param errorCode 错误码
     */
    public static CommonResult common(IErrorCode errorCode) {
        return new CommonResult(errorCode.getCode(), errorCode.getMessage());
    }
}
  1. 在钉钉群可以通过手机号码@指定人员
/**
     * 日志接受者,需要在text中包含才可以@
     * @param mobiles 手机号码集合
     * @return
     */
    private String phone(List mobiles){
        StringBuffer stringBuffer = new StringBuffer();
        for (String mobile : mobiles) {
            stringBuffer.append(" @"+mobile);
        }
        return stringBuffer.toString();
    }
  1. 关于钉钉群机器人配置的通用参数
@Data
@Component
@ConfigurationProperties(prefix = "dingtalk")
public class DingTalkProperties {

    /**
     * 数据请求url
     */
    private String url;

    /**
     * token
     */
    private String token;

    /**
     * 密钥,机器人安全设置页面,加签一栏下面显示的SEC开头的字符串。
     */
    private String secret;

    /**
     * 项目民称,用于钉钉机器人发送信息的请求头
     */
    private String projectName;

    private List atMobiles;
}
  1. 发送数据URL
    private String sendUrl() throws NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeyException {
        Long timestamp = System.currentTimeMillis();
        String stringToSign = timestamp + "\n" + dingTalkConfig.getSecret();
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(new SecretKeySpec(dingTalkConfig.getSecret().getBytes("UTF-8"), "HmacSHA256"));
        byte[] signData = mac.doFinal(stringToSign.getBytes("UTF-8"));
        String sign = URLEncoder.encode(new String(Base64.encodeBase64(signData)), "UTF-8");

        return dingTalkConfig.getUrl() + "?access_token=" + dingTalkConfig.getToken() + "&sign=" + sign + "×tamp=" + timestamp;

    }
  1. 发送数据service层
    @Override
    public void sendMessage(CommonResult data) {
        try {
            DingTalkClient client = new DefaultDingTalkClient(sendUrl());
            OapiRobotSendRequest request = new OapiRobotSendRequest();
            request.setMsgtype("markdown");
            OapiRobotSendRequest.Markdown markdown = new OapiRobotSendRequest.Markdown();
            markdown.setTitle("接口异常通知");

            markdown.setText("#### " + dingTalkConfig.getProjectName() + " \n" +
                    "> 日志处理人:" + phone(dingTalkConfig.getAtMobiles()) + "\n\n" +
                    "> 异常原因:" + data.getMessage() + "\n\n" +
                    "> ###### " + DateUtils.getThisTime() + "发布\n");
            request.setMarkdown(markdown);

            OapiRobotSendRequest.At at = new OapiRobotSendRequest.At();
            at.setAtMobiles(dingTalkConfig.getAtMobiles());
            // isAtAll类型如果不为Boolean,请升级至最新SDK
            at.setIsAtAll(false);
            request.setAt(at);

            OapiRobotSendResponse response = client.execute(request);
        } catch (Exception e) {
            log.error("发送信息错误,失败信息:{}", e.getMessage());
        }
    }

你可能感兴趣的:(java,后端)