Springboot整合企业微信机器人助手推送消息的实现

作者:小目标青年 时间:2023-08-18 08:37:37 

前言

这个东西有啥用,好玩?

确实, 好玩归好玩,其实很有使用场景。

可以自己选则一些业务节点触发这个机器人助手的消息推送;

简单举例:

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\\KmProjects\\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整合企业微信机器人助手推送消息的实现

其他的效果:

Springboot整合企业微信机器人助手推送消息的实现

来源:https://blog.csdn.net/qq_35387940/article/details/125003593

标签:Springboot,企业微信,机器人
0
投稿

猜你喜欢

  • C#实现下载网页HTML源码的方法

    2023-06-10 01:07:24
  • springSecurity之AuthenticationProvider用法解析

    2022-09-07 20:55:01
  • c#读写注册表示例分享

    2022-06-26 13:08:45
  • Android自定义view贝塞尔曲线

    2023-04-09 07:51:22
  • C# Pointer指针应用实例简述

    2021-12-21 12:48:55
  • Kotlin浅析延迟初始化与密封类的实现方法

    2023-05-06 13:54:44
  • C#命令模式(Command Pattern)实例教程

    2023-06-13 00:15:48
  • java之函数式接口解读

    2022-07-16 16:32:46
  • Spring Boot缓存实战之Redis 设置有效时间和自动刷新缓存功能(时间支持在配置文件中配置)

    2023-11-11 01:57:18
  • Android自定义View实现简易画板功能

    2022-12-03 15:36:27
  • Java实现AOP功能的封装与配置的小框架实例代码

    2022-12-27 10:57:45
  • C#实现泛型动态循环数组队列的方法

    2022-11-03 05:05:42
  • Java中Map实现线程安全的3种方式

    2021-10-07 21:23:36
  • 关于springboot集成阿里云短信的问题

    2023-08-23 09:46:15
  • IntelliJ IDEA2022.3 springboot 热部署含静态文件(最新推荐)

    2023-07-07 10:41:58
  • C# FileStream文件读写详解

    2021-10-27 15:44:14
  • Unity实现游戏存档框架

    2023-02-10 13:05:15
  • 详解MyBatis逆向工程

    2021-12-12 02:38:04
  • 探讨Object转为String的几种简易形式详解

    2023-08-21 11:47:27
  • 听说用了YYYY-MM-dd的程序员,前些天都在加班改Bug

    2023-07-05 17:48:00
  • asp之家 软件编程 m.aspxhome.com