SpringBoot中集成企業(yè)微信機(jī)器人實現(xiàn)運(yùn)維報警的示例
在企業(yè)運(yùn)營中,為了實現(xiàn)工作效率和執(zhí)行效率的提升,往往會選擇在社群中使用群聊機(jī)器人進(jìn)行協(xié)助管理。機(jī)器人可以定時或者按照一定的規(guī)則給群里發(fā)信息并@群成員等。群聊機(jī)器人可以活躍氣氛,關(guān)懷員工比如根據(jù)天氣情況提醒員工注意天氣變化,發(fā)送節(jié)日、生日祝福等。它也可以進(jìn)行工作提醒,幫助員工更好的做系統(tǒng)化的回報總結(jié),機(jī)器人可以依托業(yè)務(wù)系統(tǒng),每天定時發(fā)送工作總結(jié)給對應(yīng)負(fù)責(zé)人,幫助員工更好地復(fù)盤工作。
1、注冊企業(yè)微信
注冊地址:https://work.weixin.qq.com/wework_admin/register_wx?from=myhome
這里的注冊企業(yè)微信,不一定需要你有企業(yè)信息,可以任意填寫,不需要審核
2、添加群機(jī)器人
加入企業(yè)微信后,會有一個該企業(yè)的全員群,我們可以在群內(nèi)添加機(jī)器人:

填寫機(jī)器人名稱


添加成功后,得到機(jī)器人的 Webhook 地址,我們需要用到它,特別特別要注意:一定要保護(hù)好機(jī)器人的 webhook 地址,避免泄漏!不要分享到 github、博客等可被公開查閱的地方,否則壞人就可以用你的機(jī)器人來發(fā)垃圾消息了。
3、引入 forest 依賴
<!-- http請求工具 -->
<dependency>
<groupId>com.dtflys.forest</groupId>
<artifactId>forest-spring-boot-starter</artifactId>
<version>1.5.14</version>
</dependency>
forest 是聲明式 HTTP 客戶端 API 框架,讓 Java 發(fā)送 HTTP/HTTPS 請求不再難。它比 OkHttp 和 HttpClient 更高層,是封裝調(diào)用第三方 restful api client 接口的好幫手,是 retrofit 和 feign 之外另一個選擇。通過在接口上聲明注解的方式配置 HTTP 請求接口,Gitee 地址:https://gitee.com/dromara/forest
文檔地址:https://forest.dtflyx.com/
相關(guān)配置:
## 輕量級HTTP客戶端框架forest forest: # 配置底層API為 okhttp3 backend: okhttp3 # 連接池最大連接數(shù),默認(rèn)值為500 max-connections: 1000 # 每個路由的最大連接數(shù),默認(rèn)值為500 max-route-connections: 500 # 請求超時時間,單位為毫秒, 默認(rèn)值為3000 timeout: 3000 # 連接超時時間,單位為毫秒, 默認(rèn)值為2000 connect-timeout: 3000 # 請求失敗后重試次數(shù),默認(rèn)為0次不重試 retry-count: 1 # 單向驗證的HTTPS的默認(rèn)SSL協(xié)議,默認(rèn)為SSLv3 ssl-protocol: SSLv3 # 打開或關(guān)閉日志,默認(rèn)為true logEnabled: true # 打開/關(guān)閉Forest請求日志(默認(rèn)為 true) log-request: true # 打開/關(guān)閉Forest響應(yīng)狀態(tài)日志(默認(rèn)為 true) log-response-status: true # 打開/關(guān)閉Forest響應(yīng)內(nèi)容日志(默認(rèn)為 false) log-response-content: true
4、請求方法
import com.dtflys.forest.annotation.JSONBody;
import com.dtflys.forest.annotation.Post;
import com.dtflys.forest.annotation.Var;
import java.util.Map;
public interface WechatClient {
@Post(
url = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key={key}",
headers = {
"Accept-Charset: utf-8",
"Content-Type: application/json"
},
dataType = "json")
void sendWechatMsg(@Var("key") String key, @JSONBody Map<String, Object> body);
}
使用 forest 做 http 請求非常方便,只需要使用注解的方式輕松完成請求
5、發(fā)送消息
注入請求接口:
@Resource private WechatClient wechatClient;
1、發(fā)送文本消息
/**
* 發(fā)送文本消息
*/
public void sendTextMsg() {
Map<String, Object> map = new HashMap<>();
map.put("msgtype", "text");
Map<String, String> content = new HashMap<>();
content.put("content", "hello world!");
map.put("text", content);
wechatClient.sendWechatMsg("xxxxxxxxxxxxxxxxxx", map);
}
其中:xxxxxxxxxxxxxx 為你的機(jī)器人的 Webhook 地址的 key
如果我們想 @某人時,我們可以在 content 中這樣寫:
content.put("content", "hello world!<@zhangsan>");這樣就可以 @zhangsan 了,僅支持 text、markdown 類型的消息
2、發(fā)送 MD 消息
/**
* 發(fā)送md消息
*/
public void sendMarkdownMsg() {
Map<String, Object> map = new HashMap<>();
map.put("msgtype", "markdown");
Map<String, String> content = new HashMap<>();
content.put("content", "實時新增用戶反饋<font color=\\\"warning\\\">132例</font>,請相關(guān)同事注意。\\n\n" +
" >類型:<font color=\\\"comment\\\">用戶反饋</font>\n" +
" >普通用戶反饋:<font color=\\\"comment\\\">117例</font>\n" +
" >VIP用戶反饋:<font color=\\\"comment\\\">15例</font>");
map.put("markdown", content);
wechatClient.sendWechatMsg("xxxxxxxxxxxxxxxxxx", map);
}
markdown 語法教程見:https://mp.weixin.qq.com/s/uvxdj4tdWePkGbdD5I9iLQ
3、發(fā)送圖片消息
/**
* 發(fā)送圖片消息
*/
public void sendImageMsg() {
String url = "C:\\Users\\admin\\Desktop\\test.png";
Map<String, Object> map = new HashMap<>();
map.put("msgtype", "image");
Map<String, String> content = new HashMap<>();
content.put("md5", getMd5(url));
content.put("base64", getBase64(url));
map.put("image", content);
wechatClient.sendWechatMsg("xxxxxxxxxxxxxxxxxx", map);
}
我們需要圖片的 base64 編碼和 MD5 值,方法如下:
/**
* 圖片轉(zhuǎn)為base64編碼
*/
public static String getBase64(String imgFile) {
InputStream in = null;
byte[] data = null;
// 讀取圖片字節(jié)數(shù)組
try {
in = new FileInputStream(imgFile);
data = new byte[in.available()];
in.read(data);
in.close();
} catch (IOException e) {
e.printStackTrace();
}
// 對字節(jié)數(shù)組Base64編碼
BASE64Encoder encoder = new BASE64Encoder();
// 返回Base64編碼過的字節(jié)數(shù)組字符串
return encoder.encode(data);
}
/**
* 獲取文件的MD5值
*
* @param path
* @return
*/
public static String getMd5(String path) {
try {
MessageDigest md5 = MessageDigest.getInstance("MD5");
FileInputStream fis = new FileInputStream(path);
byte[] buffer = new byte[1024];
int len;
while ((len = fis.read(buffer)) != -1) {
md5.update(buffer, 0, len);
}
fis.close();
byte[] byteArray = md5.digest();
StringBuilder sb = new StringBuilder();
for (byte b : byteArray) {
sb.append(String.format("%02x", b));
}
return sb.toString();
} catch (IOException | NoSuchAlgorithmException e) {
e.printStackTrace();
}
return null;
}
這里會有一個坑,發(fā)送請求后,返回的請求碼是 200,但是收不到消息,會看到提示信息:
{"errcode":301019,"errmsg":"media md5 not match, hint: [1651825628340383128465893], from ip: 218.201.194.160, more info at https://open.work.weixin.qq.com/devtool/query?e=301019"}
提示我們:媒體md5不匹配
其實,并不是 MD5 的問題,是 base64 的問題,轉(zhuǎn)化出來的 base64 編碼 存在 \r\n,我們需要將其替換掉,這樣寫:
content.put("base64", getBase64(url).replaceAll("\r|\n", ""));4、發(fā)送圖文消息
/**
* 發(fā)送圖文消息
*/
public void sendNewsMsg() {
Map<String, Object> map = new HashMap<>();
map.put("msgtype", "news");
Map<String, Object> content = new HashMap<>();
List<Map<String, Object>> list = new ArrayList<>();
Map<String, Object> obj = new HashMap<>();
obj.put("title", "中秋節(jié)禮品領(lǐng)取");
obj.put("description", "今年中秋節(jié)公司有豪禮相送");
obj.put("url", "www.qq.com");
obj.put("picurl", "http://res.mail.qq.com/node/ww/wwopenmng/images/independent/doc/test_pic_msg1.png");
list.add(obj);
content.put("articles", list);
map.put("news", content);
wechatClient.sendWechatMsg("xxxxxxxxxxxxxxxxxx", map);
}
6、測試
1、發(fā)送文本消息

2、發(fā)送 MD 消息

3、發(fā)送圖片消息

4、發(fā)送圖文消息

5、發(fā)送文本消息并@群員

到此這篇關(guān)于SpringBoot中集成企業(yè)微信機(jī)器人實現(xiàn)運(yùn)維報警的示例的文章就介紹到這了,更多相關(guān)SpringBoot運(yùn)維報警內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Java實現(xiàn)定時讀取json文件里內(nèi)容的示例代碼
有時候我們會需要定時來讀取JSON配置文件里的內(nèi)容,來執(zhí)行一些業(yè)務(wù)邏輯上的操作,本文就介紹了Java實現(xiàn)定時讀取json文件里內(nèi)容的示例代碼,感興趣的可以了解一下2023-08-08
SpringBoot中的multipartResolver上傳文件配置
這篇文章主要介紹了SpringBoot中的multipartResolver上傳文件配置,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-10-10
Spring利用@Validated注解實現(xiàn)參數(shù)校驗詳解
這篇文章主要為大家詳細(xì)介紹了在?Spring?項目中使用?@Validated?進(jìn)行參數(shù)校驗的方法和常見應(yīng)用場景,感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2023-05-05
Java實現(xiàn)Jar文件的遍歷復(fù)制與文件追加
這篇文章主要為大家詳細(xì)介紹了如何利用Java實現(xiàn)Jar文件的遍歷復(fù)制與文件追加功能,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2024-11-11
Java生成范圍內(nèi)隨機(jī)整數(shù)的三種方法
在Java中生成隨機(jī)數(shù)的場景有很多,下面這篇文章主要給大家介紹了關(guān)于Java生成范圍內(nèi)隨機(jī)整數(shù)的三種方法,文中通過實例代碼介紹的非常詳細(xì),需要的朋友可以參考下2022-07-07

