首先在钉钉软件里创建一个群聊,这个比较简单就不多说啥了,主要注意的地方是一个群聊至少三个人,但是如何做到 1 个人创建一个群呢?也很简单,只要一开始拉 2 个人进来,然后创建成功后把他们踢出去就行,这样就实现 1 个人在一个群里,就可以和机器人愉快地玩耍啦~
因为我们这篇主要讲解的是自定义机器人,其他机器人也半斤八两的操作,所以我们还是拿自定义机器人来举例说明,如图所是,完全傻瓜式操作
Ps1:这一步安全设置有三种安全设置可供选择,这里只演示加签安全设置(推荐)
Ps2:记得先复制来这串密钥,下文会用到
Ps1:这一步也一样,提前复制好 Webhook 信息,下文需要用到
Ps2:当然如果以上密钥和Webhook都忘记了的话,可以重新打开上面的机器人那边可以重新查看的噢
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>alibaba-dingtalk-service-sdk</artifactId>
<version>2.0.0</version>
</dependency>
Ps:添加依赖
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiRobotSendRequest;
import com.dingtalk.api.response.OapiRobotSendResponse;
import com.taobao.api.ApiException;
import org.apache.commons.codec.binary.Base64;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
/**
* @author Y
* @date 2022/7/6
*/
public class DingUtil {
//钉钉上添加机器人的时候会有密钥
private static final String secret= "xxxxxxxxxxxxxx";
//注册机器人的时候会有webhook
private static final String webhook = "xxxxxxxxxxxxx";
public static void send(String content) throws ApiException, NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeyException {
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");
String signResult = "×tamp=" + timestamp + "&sign=" + sign;
// 得到拼接后的 URL
String url = URL + signResult;
DingTalkClient client = new DefaultDingTalkClient(url);
OapiRobotSendRequest request = new OapiRobotSendRequest();
request.setMsgtype("text");
OapiRobotSendRequest.Text text = new OapiRobotSendRequest.Text();
text.setContent(content);
request.setText(text);
OapiRobotSendResponse response = client.execute(request);
}
}
PS:此处只使用了Text方式发送消息,一般只需要这个就可以了。
package com.hjy.mall.common.consts;
import com.alibaba.fastjson.JSONObject;
import com.hjy.mall.common.util.Builder;
//消息类型
public enum MsgTypeEnum {
TXT(Builder.of(JSONObject::new)
.with(JSONObject::put,"msgtype","text")
.build()),
MARKDOWN(Builder.of(JSONObject::new)
.with(JSONObject::put,"msgtype","markdown")
.build());
MsgTypeEnum(JSONObject result) {
this.result = result;
}
private JSONObject result;
public JSONObject getResult() {
return result;
}
public void setResult(JSONObject result) {
this.result = result;
}
}
PS:钉钉消息发送
package com.hjy.mall.common.util;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hjy.mall.common.consts.MsgTypeEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.URLEncoder;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
@Slf4j
public class DingDingUtil {
/**
** 生成时间戳和验证信息
*/
private static String encode(String secret) throws Exception {
//获取时间戳
Long timestamp = System.currentTimeMillis();
//把时间戳和密钥拼接成字符串,中间加入一个换行符
String stringToSign = timestamp + "\n" + secret;
//声明一个Mac对象,用来操作字符串
Mac mac = Mac.getInstance("HmacSHA256");
//初始化,设置Mac对象操作的字符串是UTF-8类型,加密方式是SHA256
mac.init(new SecretKeySpec(secret.getBytes("UTF-8"), "HmacSHA256"));
//把字符串转化成字节形式
byte[] signData = mac.doFinal(stringToSign.getBytes("UTF-8"));
//新建一个Base64编码对象
Base64.Encoder encoder = Base64.getEncoder();
//把上面的字符串进行Base64加密后再进行URL编码
String sign = URLEncoder.encode(new String(encoder.encodeToString(signData)),"UTF-8");
//System.out.println(timestamp);
//System.out.println(sign);
String result = "×tamp=" + timestamp + "&sign=" + sign;
return result;
};
/** param: message 要发送的信息
** return: void 无返回值
** 作用:把传入的message发送给钉钉机器人
*
* */
public static void dingRequest(String title, String message, String webhook, String secret, MsgTypeEnum type){
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
String url = null;
try {
url = webhook + encode(secret);
} catch (Exception e) {
e.printStackTrace();
}
HttpPost httpPost = new HttpPost(url);
//设置http的请求头,发送json字符串,编码UTF-8
httpPost.setHeader("Content-Type", "application/json;charset=utf8");
//生成json对象传入字符
JSONObject result = null;
switch(type){
case TXT:
result = type.getResult();
JSONObject text = new JSONObject();
Map<String, Boolean> at = new HashMap<>();
text.put("content", message);
result.put("text", text);
//result.put("msgtype", "text");
at.put("isAtAll", true);
result.put("at", at);
break;
case MARKDOWN:
result = type.getResult();
JSONObject markdown = new JSONObject();
Map<String, Boolean> markdownAt = new HashMap<>();
markdown.put("title", title);
markdown.put("text", message);
result.put("markdown", markdown);
//result.put("msgtype", "markdown");
markdownAt.put("isAtAll", true);
result.put("at", markdownAt);
break;
default:
break;
}
//JSONObject result = new JSONObject();
String jsonString = JSON.toJSONString(result);
StringEntity entity = new StringEntity(jsonString, "UTF-8");
//设置http请求的内容
httpPost.setEntity(entity);
// 响应模型
CloseableHttpResponse response = null;
try {
// 由客户端执行(发送)Post请求
response = httpClient.execute(httpPost);
// 从响应模型中获取响应实体
HttpEntity responseEntity = response.getEntity();
//System.out.println("响应状态为:" + response.getStatusLine());
if (responseEntity != null) {
log.info("钉钉响应内容长度为:{}",responseEntity.getContentLength());
log.info("钉钉响应内容为:{}", EntityUtils.toString(responseEntity));
//System.out.println("响应内容长度为:" + responseEntity.getContentLength());
//System.out.println("响应内容为:" + EntityUtils.toString(responseEntity));
}
} catch (Exception e) {
log.error(e.getMessage(),e);
//e.printStackTrace();
} finally {
try {
// 释放资源
if (httpClient != null) {
httpClient.close();
}
if (response != null) {
response.close();
}
} catch (Exception e) {
log.error(e.getMessage(),e);
//e.printStackTrace();
}
}
}
}
感谢大家的支持!!!