如果要在项目里使用钉钉机器人推送消息,首先要在pom.xml里引入钉钉的sdk,如果需要指定版本使用<version></version>标签指定。
<dependency>
<groupId>com.dingtalk.open</groupId>
<artifactId>taobao-sdk-java-auto</artifactId>
</dependency>
接下来就是要进行登录,这里首先要获取登录的秘钥,钉钉采用的是HmacSHA256加密,secret 密钥是机器人安全设置页面加签一栏下面显示的SEC开头的字符。
private String appendSign(){
try{
Long timestamp = System.currentTimeMillis();
String secret="";
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");
return "×tamp="+timestamp+"&sign="+sign;
}catch (Exception e){
throw new RuntimeException(e.getMessage());
}
}
编写钉钉消息发送工具类
public void pushDingDingTalk(String accessToken){
try {
String sign=appendSign();
String dingdingUrl="https://oapi.dingtalk.com/robot/send?access_token="+accessToken;
String url=dingdingUrl+sign;
DingTalkClient client = new DefaultDingTalkClient(url);
OapiRobotSendRequest request = new OapiRobotSendRequest();
request.setMsgtype("text");
OapiRobotSendRequest.Text text = new OapiRobotSendRequest.Text();
text.setContent("输入内容");
request.setText(text);
OapiRobotSendRequest.At at = new OapiRobotSendRequest.At();
at.setAtMobiles(Arrays.asList("132xxxxxxxx"));
request.setAt(at);
request.setMsgtype("link");
OapiRobotSendRequest.Link link = new OapiRobotSendRequest.Link();
link.setMessageUrl("https://www.dingtalk.com/");
link.setPicUrl("");
link.setTitle("输入标题");
link.setText("");
request.setLink(link);
// 设置信息类型
request.setMsgtype("markdown");
OapiRobotSendRequest.Markdown markdown = new OapiRobotSendRequest.Markdown();
markdown.setTitle("天气超市");
markdown.setText("【天气超市】报表推送\n" +
"> 9度,西北风1级,空气良89,相对温度73%\n\n" +
"> 9度,西北风2级,空气良89,相对温度73%\n\n" +
"> 9度,西北风3级,空气良89,相对温度73%\n\n" +
"> 9度,西北风4级,空气良89,相对温度73%\n\n" +
"> 9度,西北风4级,空气良89,相对温度73%\n\n" +
"> 9度,西北风4级,空气良89,相对温度73%\n\n" +
"> 9度,西北风4级,空气良89,相对温度73%\n\n" +
"> 9度,西北风4级,空气良89,相对温度73%\n\n" +
"> 9度,西北风4级,空气良89,相对温度73%\n\n" +
"> 9度,西北风4级,空气良89,相对温度73%\n\n" +
"> 9度,西北风4级,空气良89,相对温度73%\n\n" +
"> 9度,西北风4级,空气良89,相对温度73%\n\n" +
"> 9度,西北风4级,空气良89,相对温度73%\n\n" +
"> 9度,西北风4级,空气良89,相对温度73%\n\n" +
"> ###### 10点20分发布 [天气](http://www.thinkpage.cn/) \n");
request.setMarkdown(markdown);
OapiRobotSendResponse response = client.execute(request);
}catch (Exception e){
throw new RuntimeException(e.getMessage());
}
}

本文介绍如何在项目中使用钉钉机器人推送消息。主要内容包括引入SDK依赖、获取登录秘钥并通过HmacSHA256加密,以及编写消息发送工具类实现文本、链接和Markdown等多种类型的消息推送。
2827

被折叠的 条评论
为什么被折叠?



