文章目录
一、钉钉机器人配置
1)添加机器人
2)添加自定义机器人
3)设置机器人参数
4)添加机器人完成
注意:完成后,复制出链接,方便后续测试使用;
Webhook链接组成 = https:// + baseUrl + access_token;
例如:https://oapi.dingtalk.com/robot/send?access_token=82995******45d84
;
二、依赖导入
xml
<!--dingding-sdk-->
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>alibaba-dingtalk-service-sdk</artifactId>
<version>2.0.0</version>
</dependency>
三、工具类封装
java
@Slf4j
public class DingDingUtils {
public static void send(String url, String msg) {
try {
//创建钉钉客户端
DingTalkClient client = new DefaultDingTalkClient(url);
//构建自定义机器人请求
OapiRobotSendRequest request = new OapiRobotSendRequest();
//设置固定为文字版信息类型
request.setMsgtype("text");
//构建自定义机器人文字类型请求
OapiRobotSendRequest.Text text = new OapiRobotSendRequest.Text();
//调用封装文本信息。
text.setContent(msg);
request.setText(text);
//构建自定义机器人@人范围请求
OapiRobotSendRequest.At at = new OapiRobotSendRequest.At();
//明确为 true。通知时@所有人
at.setIsAtAll(true);
request.setAt(at);
OapiRobotSendResponse response = client.execute(request);
log.info("发送完成,返回值:{}", response.getBody());
} catch (ApiException e) {
log.error("钉钉接口调用异常:", e);
}
}
}
四、关键字推送消息测试类
1)测试类
java
@Test
void sendTextTest() {
// 钉钉群机器人id号
String url = "https://oapi.dingtalk.com/robot/send?access_token=8299504a4255a****************ae4aae697441995f45d84";
// hello,为关键字
String msg = "hello, 大家好";
DingDingUtils.send(url, msg);
}
2)程序输出结果:
3)通知结果:
五、加签推送消息测试类
1)修改机器人配置为加签
2)测试类
java
@Test
void sendTextTest2() throws Exception {
Long timestamp = System.currentTimeMillis();
String secret = "SECb2f83dd75fdc0b2***********c50f33ebd36102327e44a8";
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");
System.out.println(sign);
// 钉钉群机器人id号
String baseUrl = "https://oapi.dingtalk.com/robot/send?access_token=8299504a4255a****************ae4aae697441995f45d84";
String msg = "这是一条加签测试的消息!";
String fullUrl =
String.format(baseUrl + "×tamp=%s&sign=%s", timestamp, sign);
DingDingUtils.send(fullUrl, msg);
}