1.需求
在項目中將某個操作後的數據發送給釘釘機器人。
2.配置自定義的釘釘機器人
釘釘的 WebHook 自定義機器人的配置文檔:https://ding-doc.dingtalk.com/doc#/serverapi3/iydd5h
下載釘釘電腦版,創建一個羣,選擇智能羣助手,添加自定義機器人
然後選擇加密方式,這裏選標籤加密,會生成webhook的地址和祕鑰
3.封裝參數發送的代碼:
//1.添加安全設置,構造請求uri(此處直接封裝uri而非用String類型來進行http請求:RestTemplate 在執行請求時,如果路徑爲String類型,將分析路徑參數並組合路徑,此時會丟失sign的部分特殊字符)
long timestamp = System.currentTimeMillis();
URI uri = new URI(hook.getWebhookPath() + "×tamp=" + timestamp + "&sign=" + addSignature(hook.getSecret(), timestamp));
//2.添加發送類型
request.put("msgtype", "markdown");
//3.添加@對象
Map<String, Object> at = new HashMap<>();
at.put("isAtAll", CollectionUtils.isEmpty(mobiles));
if (!CollectionUtils.isEmpty(mobiles)) {
at.put("atMobiles", mobiles);
}
request.put("at", at);
for (String mobile : mobiles) {
text = "@" + mobile + text;
}
//4.添加發送內容
Map<String, Object> markdown = new HashMap<>();
markdown.put("text", text);
markdown.put("title", title);
request.put("markdown", markdown);
//額外內容
request.put("web_uri", uri);
JSONObject jsonObject = new JSONObject();
jsonObject.put("requestBody", JSON.toJSONString(request));
webHookJsonSendDTO.setObjectAttributes(jsonObject);
//5.發送請求
webhookRecordDTO.setSendTime(new Date());
webhookRecordDetailDTO.setRequestHeaders(REQUEST_HEADER);
webhookRecordDetailDTO.setRequestBody(webHookJsonSendDTO.getObjectAttributes().get("requestBody").toString());
response = template.postForEntity(uri, request, String.class);
測試:
此時傳過來相應的參數,機器人就會在羣裏推送消息