天天看點

Springboot 整合 企業微信機器人助手推送消息

前言

這個東西有啥用,好玩?

确實, 好玩歸好玩,其實有很多使用場景。

可以自己選擇一些業務節點觸發這個機器人助手的消息推送;

簡單舉例:

1. 有人給你的系統留下回報意見了,推送到營運群去;

2.項目部署成功了,推送到運維群去;

3.有人新增業務資料了,推送到客服群去;

本篇内容:  

對接企微機器人,推送消息到群聊。 

消息類型有四種:

文本消息

圖檔消息

MarkDown格式文本消息

小卡片消息(小卡片哦~)

效果:

Springboot 整合 企業微信機器人助手推送消息

正文

注意點:

1.企業微信群聊,外部群聊不允許弄機器人。

Springboot 整合 企業微信機器人助手推送消息

 2.整合機器人的前提是,到相關群聊建機器人。

可以整合多個機器人,每個機器的身份辨別是 建立的時候 企微分發的一個key。

觸發哪個機器人去推消息,就使用哪個key。

機器人建立步驟:

①對着群聊右鍵,點選進入管理聊天消息 

Springboot 整合 企業微信機器人助手推送消息

②點選添加機器人

Springboot 整合 企業微信機器人助手推送消息

3.建立機器人

Springboot 整合 企業微信機器人助手推送消息

 4.建立成功(這個key就是每個機器人的唯一辨別,推送消息可以設計成傳key推送)

Springboot 整合 企業微信機器人助手推送消息

開始敲代碼整合:

慣例,先看下這次執行個體最終目錄結構:

Springboot 整合 企業微信機器人助手推送消息

1. 從頭開始 建一個項目:

Springboot 整合 企業微信機器人助手推送消息

 2.引入核心依賴:

<!-- http請求工具 -->

<dependency>

    <groupId>com.dtflys.forest</groupId>

    <artifactId>forest-spring-boot-starter</artifactId>

    <version>1.5.14</version>

</dependency>

Springboot 整合 企業微信機器人助手推送消息

3. 把配置檔案改成yml格式 (個人習慣),然後配上forset調用工具的配置,以及 機器人key

## 輕量級HTTP用戶端架構forest
forest:
  # 配置底層API為 okhttp3
  backend: okhttp3
  # 連接配接池最大連接配接數,預設值為500
  max-connections: 1000
  # 每個路由的最大連接配接數,預設值為500
  max-route-connections: 500
  # 請求逾時時間,機關為毫秒, 預設值為3000
  timeout: 3000
  # 連接配接逾時時間,機關為毫秒, 預設值為2000
  connect-timeout: 3000
  # 請求失敗後重試次數,預設為0次不重試
  retry-count: 1
  # 單向驗證的HTTPS的預設SSL協定,預設為SSLv3
  ssl-protocol: SSLv3
  # 打開或關閉日志,預設為true
  logEnabled: true
  # 打開/關閉Forest請求日志(預設為 true)
  log-request: true
  # 打開/關閉Forest響應狀态日志(預設為 true)
  log-response-status: true
  # 打開/關閉Forest響應内容日志(預設為 false)
  log-response-content: true

wechat:
  notice:
    key: 3f66977b-****-4af5-****-59*0c4****3d
server:
  port: 8571      

4. 建立 WechatNoticeClient.java

用于對接企微機器人推消息接口,因為我們整合了forest ,簡單用注解就行(其實自己用http工具也行)

import com.dtflys.forest.annotation.JSONBody;
import com.dtflys.forest.annotation.Post;
import com.dtflys.forest.annotation.Var;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @Author: JCccc
 * @Date: 2022-5-27 14:44
 * @Description: 企業微信機器人通知client
 */
@Component
public interface WechatNoticeClient {
    @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);


}      

5.建立 MyNoticeUtil.java  

用于封裝不同消息類型消息的推送方法,裡面調用的WechatNoticeClient.

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import sun.misc.BASE64Encoder;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: JCccc
 * @Date: 2022-5-27 14:48
 * @Description:
 */
@Component
public class MyNoticeUtil {
    @Autowired
    private WechatNoticeClient wechatNoticeClient;
    @Value("${wechat.notice.key}")
    private String NOTICE_KEY;

    /**
     * 發送文本消息
     */
    public void sendTextMsg() {
        Map<String, Object> sendMap = new HashMap<>();
        //設定消息類型 txt文本
        sendMap.put("msgtype", "text");
        Map<String, String> contentMap = new HashMap<>();
        contentMap.put("content", "你好,我是JCccc的機器人");
        sendMap.put("text", contentMap);
        wechatNoticeClient.sendWechatMsg(NOTICE_KEY, sendMap);
    }

    /**
     * 發送markdown文本消息
     */
    public void sendMarkDownTextMsg() {
        Map<String, Object> sendMap = new HashMap<>();
        //設定消息類型 markdown文本
        sendMap.put("msgtype", "markdown");
        Map<String, String> contentMap = new HashMap<>();
        contentMap.put("content", "JCccc,您的賬戶餘額已到賬<font color=\\\"warning\\\">15000元</font>,開心起來吧。\\\n" +
                "         >付款方:<font color=\\\"comment\\\">白日做夢</font>");
        sendMap.put("markdown", contentMap);
        wechatNoticeClient.sendWechatMsg(NOTICE_KEY, sendMap);
    }

    /**
     * 發送圖檔消息
     */
    public void sendImageMsg() {
        String url = "D:\\Program Files\\JcProjects\\dotest\\src\\main\\resources\\static\\test.png";
        Map<String, Object> sendMap = new HashMap<>();
        sendMap.put("msgtype", "image");
        Map<String, String> contentMap = new HashMap<>();
        contentMap.put("md5", getMd5(url));
        contentMap.put("base64", getBase64(url).replaceAll("\r|\n", ""));
        sendMap.put("image", contentMap);
        wechatNoticeClient.sendWechatMsg(NOTICE_KEY, sendMap);
    }

    /**
     * 發送圖文消息
     */
    public void sendImageAndTxtMsg() {
        Map<String, Object> sendMap = new HashMap<>();
        sendMap.put("msgtype", "news");
        Map<String, Object> contentMap = new HashMap<>();
        List<Map<String, Object>> list = new ArrayList<>();
        Map<String, Object> obj = new HashMap<>();
        obj.put("title", "小目标青年的部落格");
        obj.put("description", "大家給他點點贊!");
        obj.put("url", "https://blog.csdn.net/qq_35387940");
        obj.put("picurl", "https://img-blog.csdnimg.cn/6bc435ac39514cb780739ea1cc34c409.png");
        list.add(obj);
        contentMap.put("articles", list);
        sendMap.put("news", contentMap);
        wechatNoticeClient.sendWechatMsg(NOTICE_KEY, sendMap);
    }


    /**
     * 圖檔轉為base64編碼
     */
    public String getBase64(String imgFile) {
        InputStream in = null;
        byte[] data = null;
        //  讀取圖檔位元組數組
        try {
            in = new FileInputStream(imgFile);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 對位元組數組Base64編碼
        BASE64Encoder encoder = new BASE64Encoder();
        // 傳回Base64編碼過的位元組數組字元串
        return encoder.encode(data);
    }

    /**
     * 擷取檔案的MD5值
     *
     * @param path
     * @return
     */
    public 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 (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


}      

6.簡單寫一個測試接口模拟觸發一下機器人:

import com.jc.dotest.wechat.MyNoticeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Author: JCccc
 * @Date: 2022-5-27 14:52
 * @Description:
 */
@RestController
public class TestController {

    @Autowired
    MyNoticeUtil myNoticeUtil;

    @GetMapping("/doTest")
    public String doTest(@RequestParam("testType") String testType){
        if (testType.equals("1")){
            myNoticeUtil.sendTextMsg();
        }
        if (testType.equals("2")){
            myNoticeUtil.sendMarkDownTextMsg();
        }
        if (testType.equals("3")){
            myNoticeUtil.sendImageMsg();
        }
        if (testType.equals("4")){
            myNoticeUtil.sendImageAndTxtMsg();
        }
        return "success";
    }

}      

測試效果:

觸發發送文本消息

Springboot 整合 企業微信機器人助手推送消息

效果: 

Springboot 整合 企業微信機器人助手推送消息