以前有一段时间普通群聊不支持创建自定义机器人,最近好像又可以了,遂发一篇文章讲解一下流程
创建机器人
首先在需要添加机器人的群里添加机器人,选择自定义机器人,创建成功之后记录webhook地址,安全策略可自行选择,此处介绍的是加签策略下的实现
代码
java
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.URLEncoder;
import org.apache.commons.codec.binary.Base64;
import java.util.*;
/**
* 推送钉钉告警消息
*/
public class AutoSendDingtalkMessage {
private static final Logger logger = LoggerFactory.getLogger(AutoSendDingtalkMessage.class);
/**
* 发送超时时间10s
*/
private static final int TIME_OUT = 10000;
private static String webhook = "填入自己机器人的地址";
static {
Long timestamp = System.currentTimeMillis();
String secret = "填入相应内容";
String stringToSign = timestamp + "\n" + secret;
Mac mac = null;
String sign = null;
try {
mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(secret.getBytes("UTF-8"), "HmacSHA256"));
byte[] signData = mac.doFinal(stringToSign.getBytes("UTF-8"));
sign = URLEncoder.encode(new String(Base64.encodeBase64(signData)), "UTF-8");
} catch (Exception e) {
logger.error("消息推送到钉钉的签名密钥处理失败,请检查告警有无正常发送", e);
}
webhook += "×tamp=" + timestamp + "&sign=" + sign;
}
public static String sendMsg(String content, List<String> mobileList) {
try {
//是否通知所有人
boolean isAtAll = false;
//组装请求内容
String dataString = buildReqStr(content, isAtAll, mobileList);
//推送消息(http请求)
String result = sendMsg(webhook, dataString);
return result;
} catch (Exception e) {
logger.error("发送群通知异常 异常原因:" + e);
return null;
}
}
/**
* 组装请求报文
*/
private static String buildReqStr(String content, boolean isAtAll, List<String> mobileList) {
// Markdown 格式的消息内容
JSONObject markdownContent = new JSONObject();
markdownContent.put("title", "毕设异常通知");
// 在消息内容中添加换行符
content = "## 警告:\n" +
"### 毕设运行出现异常,内容如下:\n\n```\n" + content + "\n```";
markdownContent.put("text", content);
// 通知人
JSONObject atObject = new JSONObject();
atObject.put("isAtAll", isAtAll);
if (mobileList != null && !mobileList.isEmpty()) {
atObject.put("atMobiles", mobileList);
}
// 构建请求的 JSON
JSONObject reqObject = new JSONObject();
reqObject.put("msgtype", "markdown");
reqObject.put("markdown", markdownContent);
reqObject.put("at", atObject);
return reqObject.toJSONString();
}
private static String sendMsg(String url, String dataString) {
String body = null;
try {
body = HttpRequest.post(url).body(dataString).timeout(TIME_OUT).execute().body();
} catch (Exception e) {
logger.error("发送失败", e);
}
return body;
}
}