当前位置: 首页 > news >正文

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

前言

这个东西有啥用,好玩?

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

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

简单举例:

1. 有人给你的系统留下反馈意见了,推送到运营群去;

2.项目部署成功了,推送到运维群去;

3.有人新增业务资料了,推送到客服群去;

本篇内容:
 

对接企微机器人,推送消息到群聊。 

消息类型有四种:

文本消息

图片消息

MarkDown格式文本消息

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

效果:


正文

注意点:

1.企业微信群聊,外部群聊不允许弄机器人。

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

可以整合多个机器人,每个机器的身份标识是 创建的时候 企微分发的一个key。

触发哪个机器人去推消息,就使用哪个key。

机器人创建步骤:


①对着群聊右键,点击进入管理聊天消息 

②点击添加机器人

3.创建机器人

 4.创建成功(这个key就是每个机器人的唯一标识,推送消息可以设计成传key推送)

开始敲代码整合:

惯例,先看下这次实例最终目录结构:

1. 从头开始 建一个项目:

 2.引入核心依赖:
 

<!-- http请求工具 -->
<dependency>
    <groupId>com.dtflys.forest</groupId>
    <artifactId>forest-spring-boot-starter</artifactId>
    <version>1.5.14</version>
</dependency>
 


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 同一次调用日志怎么用ID串起来,方便最终查找
  • IDEA 运行Tomcat项目 控制台乱码
  • Springboot 整合 xxljob 使用定时任务调度(新手入门篇)
  • Springboot @SpringBootTest 单元测试执行两次的问题
  • Amazon ElastiCache 飞速搭建缓存服务集群,这才叫快
  • Springboot 整合 xxljob 动态API调度任务(进阶篇)
  • getReader() has already been called for this request
  • (Redis使用系列) Springboot 使用redis实现接口幂等性拦截 十一
  • 客观看待mybatis 中使用 where 1=1
  • MySql 怎么查出符合条件的最新的数据行?
  • Springboot 手动分页查询,分批批量插入数据
  • SpringBoot (走读源码)静态方法中调用spring注入的对象,注入对象为null?
  • HashMap 使用的时候指定容量?你真的用明白了吗?(值得一阅)
  • 用这个免费CDN,治愈WordPress网站加载缓慢的大难题
  • 搞什么啊? URI 和 URL 到现在还不清楚?
  • co.js - 让异步代码同步化
  • Consul Config 使用Git做版本控制的实现
  • ES6系列(二)变量的解构赋值
  • HTTP中GET与POST的区别 99%的错误认识
  • idea + plantuml 画流程图
  • JS进阶 - JS 、JS-Web-API与DOM、BOM
  • Mysql优化
  • React as a UI Runtime(五、列表)
  • Web Storage相关
  • 离散点最小(凸)包围边界查找
  • 目录与文件属性:编写ls
  • 爬虫进阶 -- 神级程序员:让你的爬虫就像人类的用户行为!
  • 前端临床手札——文件上传
  • 前言-如何学习区块链
  • 区块链共识机制优缺点对比都是什么
  • 三分钟教你同步 Visual Studio Code 设置
  • 使用agvtool更改app version/build
  • 使用common-codec进行md5加密
  • 试着探索高并发下的系统架构面貌
  • 正则与JS中的正则
  • “十年磨一剑”--有赞的HBase平台实践和应用之路 ...
  • 【运维趟坑回忆录】vpc迁移 - 吃螃蟹之路
  • UI设计初学者应该如何入门?
  • ​猴子吃桃问题:每天都吃了前一天剩下的一半多一个。
  • # .NET Framework中使用命名管道进行进程间通信
  • # 达梦数据库知识点
  • #QT项目实战(天气预报)
  • #ubuntu# #git# repository git config --global --add safe.directory
  • #设计模式#4.6 Flyweight(享元) 对象结构型模式
  • $.ajax中的eval及dataType
  • (2)Java 简介
  • (26)4.7 字符函数和字符串函数
  • (poj1.2.1)1970(筛选法模拟)
  • (ZT) 理解系统底层的概念是多么重要(by趋势科技邹飞)
  • (zt)基于Facebook和Flash平台的应用架构解析
  • (附源码)springboot美食分享系统 毕业设计 612231
  • (六) ES6 新特性 —— 迭代器(iterator)
  • (十一)JAVA springboot ssm b2b2c多用户商城系统源码:服务网关Zuul高级篇
  • (新)网络工程师考点串讲与真题详解
  • (一)Dubbo快速入门、介绍、使用