使用Java给钉钉群发消息
目录
目录
1.安装依赖
2.编写工具类
3.测试
安全设置
Webhook
代码编写
运行测试
4.艾特全部功能
1.安装依赖
<dependency>
<groupId>com.taobao.dingding</groupId>
<artifactId>taobao-sdk</artifactId>
<version>1.0.0</version>
</dependency>
2.编写工具类
DingDingUtils
@Slf4j
public class DingDingUtils {
private static String ROBOT_SEND_MESSAGE_URL = "https://oapi.dingtalk.com/robot/send?access_token=";
/**
* 发送钉钉群消息
* @param content
*/
public static void sendDingDingGroupMsg(String accessToken, String content) {
String textMsg = "{ \"msgtype\": \"text\", \"text\": {\"content\": \"" + content + "\"}}";
dealDingDingMsgSend(accessToken, textMsg);
}
/**
* 处理发送的钉钉消息
*
* @param textMsg
*/
private static void dealDingDingMsgSend(String accessToken, String textMsg) {
HttpClient httpclient = HttpClients.createDefault();
String robotSendMessageUrl = ROBOT_SEND_MESSAGE_URL + accessToken;
HttpPost httppost = new HttpPost(robotSendMessageUrl);
httppost.addHeader("Content-Type", "application/json; charset=utf-8");
StringEntity se = new StringEntity(textMsg, "utf-8");
httppost.setEntity(se);
try {
HttpResponse response = httpclient.execute(httppost);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
String result = EntityUtils.toString(response.getEntity(), "utf-8");
log.info("Send DingDing Message Success! Response Content: " + JSON.toJSONString(result));
}
} catch (Exception e) {
log.error("Send DingDing Message Error! Error Message:" + e.getMessage(), e);
}
}
}
3.测试
首先在钉钉新建一个群,并且添加机器人
安全设置
我设置了关键字,消息里面有这个hello关键字才能成功发送消息
Webhook
记录自己的Webhook,是进行发消息的途径
代码编写
public static void main(String[] args) {
String str = "hello,钉钉";
String token = "这里填写你自己的钉钉token";
DingDingUtils.sendDingDingGroupMsg(token,str);
}
运行测试
4.艾特全部功能
钉钉提供了艾特全部功能
{
"at": {
"atMobiles":[
"180xxxxxx"
],
"atUserIds":[
"user123"
],
"isAtAll": false
},
"text": {
"content":"我就是我, @XXX 是不一样的烟火"
},
"msgtype":"text"
}
修改sendDingDingGroupMsg方法,第三个参数表示是否艾特全部
/**
* 发送钉钉群消息
* @param content
*/
public static void sendDingDingGroupMsg(String accessToken, String content,Boolean atAll) {
String textMsg = "{ \"msgtype\": \"text\", \"text\": {\"content\": \"" + content + "\"},\"at\": {\"isAtAll\": \"" + atAll + "\"}}";
dealDingDingMsgSend(accessToken, textMsg);
}
觉得有用点个赞叭