钉钉文档:https://open.dingtalk.com/document/robots/custom-robot-access
package com.windlight.utils;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiRobotSendRequest;
import org.apache.commons.codec.binary.Base64;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Set;
public class DdErrMsg {
private static final String URL = "xxx";
private static final String SECRET = "xxx";
private static final HashMap<String, String> ERRS = new HashMap<>();
public static void add(String key, String value) {
ERRS.put(DateUtil.now() + key + IdUtil.simpleUUID(), value);
}
public static void dem() {
Set<String> keySet = ERRS.keySet();
if (ObjectUtil.isEmpty(keySet)) {
return;
}
String template = "#### {}\n > {} \n\n";
StringBuilder text = new StringBuilder();
for (String key : keySet) {
String value = ERRS.get(key);
if (ObjectUtil.isNotEmpty(value)) {
String str = StrUtil.format(template, key, value);
text.append(str);
}
}
for (String key : keySet) {
ERRS.remove(key);
}
String tx = text.toString();
if (ObjectUtil.isEmpty(tx)) {
return;
}
try {
Long timestamp = System.currentTimeMillis();
String stringToSign = timestamp + "\n" + SECRET;
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(SECRET.getBytes("UTF-8"), "HmacSHA256"));
byte[] signData = mac.doFinal(stringToSign.getBytes("UTF-8"));
String sign = URLEncoder.encode(new String(Base64.encodeBase64(signData)), "UTF-8");
DingTalkClient client = new DefaultDingTalkClient(URL + "×tamp=" + timestamp + "&sign=" + sign);
OapiRobotSendRequest request = new OapiRobotSendRequest();
request.setMsgtype("markdown");
OapiRobotSendRequest.Markdown markdown = new OapiRobotSendRequest.Markdown();
markdown.setTitle("报错日志");
markdown.setText(tx);
request.setMarkdown(markdown);
client.execute(request);
} catch (Exception ignored) {
}
}
}
|