SpringBoot項(xiàng)目發(fā)送釘釘消息功能實(shí)現(xiàn)
背景:在工作中的一些告警需要發(fā)送釘釘通知,有的是發(fā)給個(gè)人,有的要發(fā)到群里,這時(shí)項(xiàng)目就需要接入釘釘,實(shí)現(xiàn)發(fā)消息的功能
1. 添加釘釘依賴(lài)
<dependency> <groupId>com.aliyun</groupId> <artifactId>dingtalk</artifactId> <version>2.0.14</version> </dependency> <dependency> <groupId>com.aliyun</groupId> <artifactId>alibaba-dingtalk-service-sdk</artifactId> <version>2.0.0</version> </dependency>
2. 發(fā)送工作通知
發(fā)送通知需要使用access_token,獲取token需要根據(jù)AppKey、AppSecret,所以需要在釘釘后臺(tái)建一個(gè)應(yīng)用,獲許AppKey和AppSecret
2.1. 后臺(tái)建一個(gè)應(yīng)用

獲取token文檔:
https://open.dingtalk.com/document/orgapp/obtain-the-access_token-of-an-internal-app
發(fā)消息文檔:
https://open.dingtalk.com/document/orgapp/asynchronous-sending-of-enterprise-session-messages
2.2. 詳細(xì)代碼如下
替換相應(yīng)的配置就可以直接發(fā)送了
import com.aliyun.dingtalkoauth2_1_0.models.GetAccessTokenResponse;
import com.aliyun.tea.TeaException;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiMessageCorpconversationAsyncsendV2Request;
import com.dingtalk.api.response.OapiMessageCorpconversationAsyncsendV2Response;
/**
* @author csn
* @date 2024/1/26
* @description 發(fā)送個(gè)人消息
*/
public class SimpleExample {
// 釘釘官方文檔 - 獲取 AccessToken
// https://open.dingtalk.com/document/orgapp/obtain-the-access_token-of-an-internal-app
// 釘釘官方文檔 - 發(fā)送工作通知消息
// https://open.dingtalk.com/document/orgapp/asynchronous-sending-of-enterprise-session-messages
/**
* 應(yīng)用的 AgentId
*/
private static Long AGENT_ID = 2883514974L;
/**
* 應(yīng)用的 AppKey
*/
private static String APP_KEY = "dingiektffikbgglasadcs";
/**
* 應(yīng)用的 AppSecret
*/
private static String APP_SECRET = "_Ha8VQMwM_Hht3jWrPR8502O3BIQ_Lzf-G7DsK4c-u2hz6y2hzFZ7WinumIy6X7khg";
/**
* 使用 Token 初始化賬號(hào)Client
*
* @return Client
* @throws Exception
*/
public static com.aliyun.dingtalkoauth2_1_0.Client createClient() throws Exception {
com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config();
config.protocol = "https";
config.regionId = "central";
return new com.aliyun.dingtalkoauth2_1_0.Client(config);
}
/**
* 獲取 AccessToken
*
* @return AccessToken
* @throws Exception
*/
public static String getAccessToken() throws Exception {
com.aliyun.dingtalkoauth2_1_0.Client client = createClient();
com.aliyun.dingtalkoauth2_1_0.models.GetAccessTokenRequest getAccessTokenRequest = new com.aliyun.dingtalkoauth2_1_0.models.GetAccessTokenRequest()
.setAppKey(APP_KEY)
.setAppSecret(APP_SECRET);
try {
GetAccessTokenResponse accessToken = client.getAccessToken(getAccessTokenRequest);
return accessToken.body.getAccessToken();
} catch (TeaException err) {
if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
// err 中含有 code 和 message 屬性,可幫助開(kāi)發(fā)定位問(wèn)題
}
} catch (Exception exception) {
TeaException err = new TeaException(exception.getMessage(), exception);
if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
// err 中含有 code 和 message 屬性,可幫助開(kāi)發(fā)定位問(wèn)題
}
}
return null;
}
/**
* 發(fā)送消息
*/
public static void sendMessage() throws Exception {
DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/message/corpconversation/asyncsend_v2");
OapiMessageCorpconversationAsyncsendV2Request request = new OapiMessageCorpconversationAsyncsendV2Request();
// 應(yīng)用上可以看到
request.setAgentId(AGENT_ID);
// 發(fā)送給誰(shuí) (接收人的釘釘 userid)
request.setUseridList("0168333232323702649");
request.setToAllUser(false);
OapiMessageCorpconversationAsyncsendV2Request.Msg msg = new OapiMessageCorpconversationAsyncsendV2Request.Msg();
// 消息類(lèi)型 - markdown
msg.setMsgtype("markdown");
msg.setMarkdown(new OapiMessageCorpconversationAsyncsendV2Request.Markdown());
msg.getMarkdown().setText("##### text");
msg.getMarkdown().setTitle("### Title");
request.setMsg(msg);
// token
OapiMessageCorpconversationAsyncsendV2Response rsp = client.execute(request, getAccessToken());
System.out.println(rsp.getBody());
}
/**
* 測(cè)試發(fā)送個(gè)人消息
*/
public static void main(String[] args) throws Exception {
sendMessage();
}
}3. 發(fā)送群消息
3.1. 群內(nèi)建立機(jī)器人
獲取secret和Webhook就可以發(fā)送了
文檔:
https://open.dingtalk.com/document/orgapp/custom-bot-to-send-group-chat-messages
建立機(jī)器人步驟如下:



給機(jī)器人取個(gè)名字
安全設(shè)置必選選一個(gè),這里選擇加簽,后面要用到,具體原因可以看文檔

完成后又個(gè)Webhook,這個(gè)是發(fā)送消息用的url

3.2. 詳細(xì)代碼如下
替換相應(yīng)的配置就可以直接發(fā)送了
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 lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.codec.binary.Base64;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Collections;
/**
* @author csn
* @date 2024/1/26
* @description 機(jī)器人發(fā)送群消息
*/
@Slf4j
public class BotExample {
// 釘釘官方文檔
// https://open.dingtalk.com/document/orgapp/custom-bot-to-send-group-chat-messages
/**
* 機(jī)器人的加簽秘鑰 (替換成自己的)
*/
private static final String SECRET = "SEC9a6b2202a0b92847fd7098630d20b4da9c02862d3696968a27b96d1e5fa073400o23412";
/**
* 機(jī)器人的webhook (替換成自己的)
*/
private static final String URL = "https://oapi.dingtalk.com/robot/send?access_token=3c3628a434166b0b9180ddba360asd06b9999270e1655a031c74b362b069ef2f328";
/**
* 組裝簽名url
*
* @return url
*/
public static String getUrl() throws NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeyException {
Long timestamp = System.currentTimeMillis();
String stringToSign = timestamp + "\n" + SECRET;
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(SECRET.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
byte[] signData = mac.doFinal(stringToSign.getBytes(StandardCharsets.UTF_8));
String sign = URLEncoder.encode(new String(Base64.encodeBase64(signData)), "UTF-8");
String signResult = "×tamp=" + timestamp + "&sign=" + sign;
// 得到拼接后的 URL
return URL + signResult;
}
/**
* 獲取客戶端
*
* @return
*/
public static DingTalkClient getClient() throws NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeyException {
return new DefaultDingTalkClient(getUrl());
}
/**
* 發(fā)送消息
*
* @param content
* @throws ApiException
* @throws NoSuchAlgorithmException
* @throws UnsupportedEncodingException
* @throws InvalidKeyException
*/
public static void sendText(String content) throws ApiException, NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeyException {
DingTalkClient client = getClient();
OapiRobotSendRequest request = new OapiRobotSendRequest();
// 消息類(lèi)型 - 文本
request.setMsgtype("text");
OapiRobotSendRequest.Text text = new OapiRobotSendRequest.Text();
text.setContent(content);
request.setText(text);
// @人
OapiRobotSendRequest.At at = new OapiRobotSendRequest.At();
// isAtAll類(lèi)型如果不為Boolean,請(qǐng)升級(jí)至最新SDK
at.setIsAtAll(false);
// 釘釘上注冊(cè)的手機(jī)號(hào)就行了
at.setAtMobiles(Collections.singletonList("13123920295"));
request.setAt(at);
OapiRobotSendResponse response = client.execute(request);
log.info("success:{}, code:{}, errorCode:{}, errorMsg:{}", response.isSuccess(), response.getCode(), response.getErrcode(), response.getErrmsg());
}
/**
* 發(fā)送消息測(cè)試
*/
public static void main(String[] args) throws UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeyException, ApiException {
sendText("測(cè)試消息");
}
}到此這篇關(guān)于SpringBoot項(xiàng)目發(fā)送釘釘消息的文章就介紹到這了,更多相關(guān)SpringBoot發(fā)送釘釘消息內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Java?for循環(huán)標(biāo)簽跳轉(zhuǎn)到指定位置的示例詳解
這篇文章主要介紹了Java?for循環(huán)標(biāo)簽跳轉(zhuǎn)到指定位置,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2023-05-05
Java前后端分離的在線點(diǎn)餐系統(tǒng)實(shí)現(xiàn)詳解
這是一個(gè)基于SpringBoot+Vue框架開(kāi)發(fā)的在線點(diǎn)餐系統(tǒng)。首先,這是一個(gè)前后端分離的項(xiàng)目。具有一個(gè)在線點(diǎn)餐系統(tǒng)該有的所有功能,感興趣的朋友快來(lái)看看吧2022-01-01
Spark學(xué)習(xí)筆記Spark Streaming的使用
這篇文章主要介紹了Spark學(xué)習(xí)筆記Spark Streaming的使用,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-06-06
Java中ThreadLocal避免內(nèi)存泄漏的方法詳解
ThreadLocal是Java中的一個(gè)線程本地存儲(chǔ)機(jī)制,它允許每個(gè)線程擁有一個(gè)獨(dú)立的本地存儲(chǔ)空間,用于存儲(chǔ)該線程的變量,本文主要介紹了ThreadLocal如何避免內(nèi)存泄漏,需要的朋友可以參考下2023-05-05
必須掌握的十個(gè)Lambda表達(dá)式簡(jiǎn)化代碼提高生產(chǎn)力
這篇文章主要為大家介紹了必須掌握的十個(gè)Lambda表達(dá)式來(lái)簡(jiǎn)化代碼提高生產(chǎn)力,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-04-04
SpringCloud如何實(shí)現(xiàn)Zuul集群(負(fù)載均衡)
這篇文章主要介紹了SpringCloud如何實(shí)現(xiàn)Zuul集群(負(fù)載均衡)的操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-07-07
關(guān)于SpringBoot攔截器中Bean無(wú)法注入的問(wèn)題
這兩天遇到SpringBoot攔截器中Bean無(wú)法注入問(wèn)題。下面介紹關(guān)于SpringBoot攔截器中Bean無(wú)法注入的問(wèn)題,感興趣的朋友一起看看吧2021-10-10

