服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Java教程 - Springboot整合企业微信机器人助手推送消息的实现

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

2023-02-06 15:46小目标青年 Java教程

本文主要介绍了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\\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整合企业微信机器人助手推送消息的实现

到此这篇关于Springboot整合企业微信机器人助手推送消息的实现的文章就介绍到这了,更多相关Springboot企业微信机器人推送内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://blog.csdn.net/qq_35387940/article/details/125003593

延伸 · 阅读

精彩推荐
  • Java教程Java中浮点数精度问题的解决方法

    Java中浮点数精度问题的解决方法

    这篇文章给大家介绍了Java中浮点数精度问题的解决方法,本文给大家介绍的非常详细,有问题描述有原因分析,非常不错,具有参考借鉴价值,感兴趣的朋...

    mrr3392020-06-20
  • Java教程Spring Cloud中使用Feign,@RequestBody无法继承的解决方案

    Spring Cloud中使用Feign,@RequestBody无法继承的解决方案

    这篇文章主要介绍了Spring Cloud中使用Feign,@RequestBody无法继承的解决方案,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不...

    phoebechen_gz7712022-02-24
  • Java教程Java使用Socket简单通讯详解

    Java使用Socket简单通讯详解

    这篇文章主要介绍了Java使用Socket简单通讯详解,本篇文章通过简要的案例,讲解了该项技术的了解与使用,以下就是详细内容,需要的朋友可以参考下...

    Aputonos4952021-11-15
  • Java教程java实现客户管理系统

    java实现客户管理系统

    这篇文章主要为大家详细介绍了java实现客户管理系统,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...

    @java小白9722022-12-26
  • Java教程分布式难题ElasticSearch解决大数据量检索面试

    分布式难题ElasticSearch解决大数据量检索面试

    这篇文章主要为大家介绍了分布式面试难题,ElasticSearch解决大数据量检索的问题分析回答,让面试官无话可说,帮助大家实现面试开薪自由...

    Q.E.D4562022-09-06
  • Java教程你真的了解Java的多线程方法吗

    你真的了解Java的多线程方法吗

    这篇文章主要为大家详细介绍了Java的多线程方法,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下,希望能够给你带...

    WYSCODER9312022-10-27
  • Java教程SpringBoot设置接口超时时间的方法

    SpringBoot设置接口超时时间的方法

    这篇文章主要介绍了SpringBoot设置接口超时时间的方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们...

    inner_peace84122022-01-06
  • Java教程mybatis自定义类型处理器TypehHandler示例详解

    mybatis自定义类型处理器TypehHandler示例详解

    我们在写mapper映射器的配置文件时,不经意间已经用到类型转换,不过是mybatis帮我们完成的,下面这篇文章主要给大家介绍了关于mybatis自定义类型处理器...

    xwlmdd12482021-05-31