Browse Source

【企业微信】【群聊机器人消息推送(来源反馈编号:江西科翔:2022120001)】

wuyx 3 years ago
parent
commit
fa296a44f2

+ 33 - 0
qywx-sdk/src/main/java/com/usoftchina/qywx/sdk/RobMessageSdk.java

@@ -0,0 +1,33 @@
+package com.usoftchina.qywx.sdk;
+
+import com.usoftchina.qywx.sdk.config.QywxProperties;
+import com.usoftchina.qywx.sdk.dto.BaseResp;
+import com.usoftchina.qywx.sdk.dto.SendRobMessageReq;
+import org.springframework.http.ResponseEntity;
+import org.springframework.ui.ModelMap;
+
+/**
+ * 群聊机器人消息推送
+ *
+ * @author yingp
+ */
+public class RobMessageSdk extends BaseSdk {
+
+    public RobMessageSdk(QywxProperties properties) {
+        super(properties);
+    }
+
+    /**
+     * 发送消息
+     * 应用支持推送文本、markdown文本等类型
+     * @param req
+     */
+    public BaseResp send(String key, SendRobMessageReq req) {
+        ResponseEntity<BaseResp> resp = restTemplate.postForEntity(baseUrl + "/cgi-bin/webhook/send?key={key}",
+                req.build(), BaseResp.class,
+                new ModelMap("key", key));
+        assertOK(resp);
+        return resp.getBody();
+    }
+
+}

+ 125 - 0
qywx-sdk/src/main/java/com/usoftchina/qywx/sdk/dto/SendRobMessageReq.java

@@ -0,0 +1,125 @@
+package com.usoftchina.qywx.sdk.dto;
+
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * 群聊机器人消息推送
+ * @author wuyx
+ */
+public class SendRobMessageReq {
+    /**
+     * 消息类型
+     *  text:文本类型
+     *     {
+     *          "msgtype": "text",
+     *          "text": {
+     *              "content": "广州今日天气:29度,大部分多云,降雨概率:60%",
+     *              "mentioned_list":["wangqing","@all"],
+     *              "mentioned_mobile_list":["13800001111","@all"]
+     *          }
+     *      }
+     *  markdown:markdown类型
+     *      {
+     *          "msgtype": "markdown",
+     *          "markdown": {
+     *              "content": "实时新增用户反馈<font color=\"warning\">132例</font>,请相关同事注意。\n
+     *                  >类型:<font color=\"comment\">用户反馈</font>
+     *                  >普通用户反馈:<font color=\"comment\">117例</font>
+     *                  >VIP用户反馈:<font color=\"comment\">15例</font>"
+     *          }
+     *      }
+     *  image:图片类型
+     *  file:文件类型
+     *  template_card:模版卡片类型
+     *  ...
+     */
+    private String msgtype;
+    /**
+     * 消息内容
+     */
+    private AbstractMessageBody body;
+
+    /**
+     * 文本消息
+     *
+     * @param content
+     * @return
+     */
+    public SendRobMessageReq text(String content, String[] mentionedList, String[] mentionedMobileList) {
+        this.msgtype = "text";
+        this.body = new Text(content,mentionedList,mentionedMobileList);
+        return this;
+    }
+
+    /**
+     * markdown消息
+     *
+     * @param content
+     * @return
+     */
+    public SendRobMessageReq markdown(String content) {
+        this.msgtype = "markdown";
+        this.body = new Markdown(content);
+        return this;
+    }
+
+
+    public Map<String, Object> build() {
+        Map<String, Object> message = new HashMap<>(3);
+        if (null != msgtype) {
+            message.put("msgtype", msgtype);
+            message.put(msgtype, body.build());
+        }
+        return message;
+    }
+
+    interface AbstractMessageBody {
+        Map<String, Object> build();
+    }
+
+    class Text implements AbstractMessageBody {
+        //文本内容,最长不超过2048个字节,必须是utf8编码
+        private final String content;
+        //userid的列表,提醒群中的指定成员(@某个成员),@all表示提醒所有人,如果开发者获取不到userid,可以使用mentioned_mobile_list
+        private final String[] mentionedList;
+        //手机号列表,提醒手机号对应的群成员(@某个成员),@all表示提醒所有人
+        private final String[] mentionedMobileList;
+
+        public Text(String content,String[] mentionedList,String[] mentionedMobileList) {
+            this.content = content;
+            this.mentionedList = mentionedList;
+            this.mentionedMobileList = mentionedMobileList;
+        }
+
+        @Override
+        public Map<String, Object> build() {
+            Map<String, Object> data = new HashMap<>(1);
+            data.put("content", content);
+            if(mentionedList!=null && mentionedList.length>0){
+                data.put("mentioned_list", mentionedList);
+            }
+            if(mentionedMobileList!=null && mentionedMobileList.length>0){
+                data.put("mentioned_mobile_list", mentionedMobileList);
+            }
+            return data;
+        }
+    }
+
+    class Markdown implements AbstractMessageBody {
+        //markdown内容,最长不超过4096个字节,必须是utf8编码
+        private final String content;
+
+        public Markdown(String content) {
+            this.content = content;
+        }
+
+        @Override
+        public Map<String, Object> build() {
+            Map<String, Object> data = new HashMap<>(1);
+            data.put("content", content);
+            return data;
+        }
+    }
+
+}

+ 5 - 0
uas-office-qywx/src/main/java/com/usoftchina/uas/office/qywx/config/QywxConfig.java

@@ -41,6 +41,11 @@ public class QywxConfig {
         return new MessageSdk(qywxProperties());
     }
 
+    @Bean
+    public RobMessageSdk robMessageSdk() {
+        return new RobMessageSdk(qywxProperties());
+    }
+
     @Bean
     public OaSdk oaSdk() {
         return new OaSdk(qywxProperties());

+ 64 - 0
uas-office-qywx/src/main/java/com/usoftchina/uas/office/qywx/entity/UApprovalRobMsg.java

@@ -0,0 +1,64 @@
+package com.usoftchina.uas.office.qywx.entity;
+
+
+/**
+ * @author wuyx
+ * @date 2022/12/26
+ */
+public class UApprovalRobMsg {
+    private Integer id_;
+    private String type_;
+    private String key_;
+    private String msg_;
+    private String ems_;
+    private String mobiles_;
+
+    public Integer getId_() {
+        return id_;
+    }
+
+    public void setId_(Integer id_) {
+        this.id_ = id_;
+    }
+
+    public String getType_() {
+        return type_;
+    }
+
+    public void setType_(String type_) {
+        this.type_ = type_;
+    }
+
+    public String getKey_() {
+        return key_;
+    }
+
+    public void setKey_(String key_) {
+        this.key_ = key_;
+    }
+
+    public String getMsg_() {
+        return msg_;
+    }
+
+    public void setMsg_(String msg_) {
+        this.msg_ = msg_;
+    }
+
+    public String getEms_() {
+        return ems_;
+    }
+
+    public void setEms_(String ems_) {
+        this.ems_ = ems_;
+    }
+
+    public String getMobiles_() {
+        return mobiles_;
+    }
+
+    public void setMobiles_(String mobiles_) {
+        this.mobiles_ = mobiles_;
+    }
+
+}

+ 11 - 0
uas-office-qywx/src/main/java/com/usoftchina/uas/office/qywx/service/UasUApprovalMsgService.java

@@ -1,6 +1,7 @@
 package com.usoftchina.uas.office.qywx.service;
 
 import com.usoftchina.uas.office.qywx.entity.UApprovalMsg;
+import com.usoftchina.uas.office.qywx.entity.UApprovalRobMsg;
 import com.usoftchina.uas.office.service.AbstractService;
 import org.springframework.stereotype.Service;
 
@@ -22,4 +23,14 @@ public class UasUApprovalMsgService extends AbstractService {
         jdbcTemplate.execute("INSERT INTO UAPPROVALMSG_HIS (ID_, TYPE_, TITLE_, MSG_, EMS_, URL_,PUSHDATE_,PUSHSTATUS_,FAILREASON_) " +
                 " SELECT TT.*,SYSDATE,'"+status+"','"+reason+"' FROM UAPPROVALMSG TT WHERE TT.ID_ = "+id_);
     }
+    public List<UApprovalRobMsg> getAllRobMsg() {
+        return queryForBeanList("select * from UApprovalRobMsg where key_ IS NOT NULL AND TYPE_ IS NOT NULL", UApprovalRobMsg.class);
+    }
+    public void delRobMsg(){
+        jdbcTemplate.execute("delete UApprovalRobMsg where ID_ IN (SELECT ID_ FROM UApprovalRobMsg_HIS) ");
+    }
+    public void recodRobMsg(Integer id_,String status,String reason){
+        jdbcTemplate.execute("INSERT INTO UApprovalRobMsg_HIS (ID_,key_, TYPE_,MSG_, EMS_, MOBILES_,PUSHDATE_,PUSHSTATUS_,FAILREASON_) " +
+                " SELECT ID_,key_, TYPE_,MSG_, EMS_, MOBILES_,SYSDATE,'"+status+"','"+reason+"' FROM UApprovalRobMsg TT WHERE TT.ID_ = "+id_);
+    }
 }

+ 84 - 0
uas-office-qywx/src/main/java/com/usoftchina/uas/office/qywx/task/QywxPushRobotMsgTask.java

@@ -0,0 +1,84 @@
+package com.usoftchina.uas.office.qywx.task;
+
+import com.usoftchina.qywx.sdk.RobMessageSdk;
+import com.usoftchina.qywx.sdk.dto.SendRobMessageReq;
+import com.usoftchina.uas.office.entity.DataCenter;
+import com.usoftchina.uas.office.jdbc.DataSourceHolder;
+import com.usoftchina.uas.office.qywx.entity.UApprovalRobMsg;
+import com.usoftchina.uas.office.qywx.service.UasUApprovalMsgService;
+import com.usoftchina.uas.office.util.StringUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.scheduling.annotation.Scheduled;
+import org.springframework.stereotype.Component;
+
+import java.util.List;
+
+
+/**
+ * @author wuyx
+ * @date 2022/12/26
+ */
+@Component
+public class QywxPushRobotMsgTask {
+
+    @Autowired
+    private RobMessageSdk robMessageSdk;
+
+    @Autowired
+    private UasUApprovalMsgService uasUApprovalMsgService;
+
+    private final Logger logger = LoggerFactory.getLogger(QywxPushRobotMsgTask.class);
+
+    /**
+     *企业微信群聊机器人自定义消息推送
+     */
+    @Scheduled(cron="0 0/2 * * * ?")
+    public void pushUapprovalRobMsg() {
+        DataCenter dataCenter = DataCenter.INSTANCE;
+        if (null != dataCenter && null != dataCenter.getUsername() && null != dataCenter.getPassword() && null != dataCenter.getUrl()) {
+            try {
+                DataSourceHolder.set(dataCenter);
+                try {
+                    List<UApprovalRobMsg> uMsgList = uasUApprovalMsgService.getAllRobMsg();
+                    for(UApprovalRobMsg uMsg : uMsgList){
+                        SendRobMessageReq sendMsg = new SendRobMessageReq();
+                        String robKey = uMsg.getKey_();
+                        if(!StringUtils.hasText(robKey)){
+                            uasUApprovalMsgService.recodMsg(uMsg.getId_(),"FAIL","未设置机器人KEY");
+                            logger.info("send uas chatrobot message error no robot key", uMsg);
+                            continue;
+                        }
+                        if(uMsg.getType_().toUpperCase().equals("MARKDOWN")){
+                            sendMsg.markdown(uMsg.getMsg_());
+                        }else {
+                            String[] ems = new String[]{};
+                            if(StringUtils.hasText(uMsg.getEms_())){
+                                ems = uMsg.getEms_().split(",");
+                            }
+                            String[] mobiles = new String[]{};
+                            if(StringUtils.hasText(uMsg.getMobiles_())){
+                                mobiles = uMsg.getMobiles_().split(",");
+                            }
+                            sendMsg.text(uMsg.getMsg_(),ems,mobiles);
+                        }
+                        try {
+                            robMessageSdk.send(robKey,sendMsg);
+                            uasUApprovalMsgService.recodRobMsg(uMsg.getId_(),"SUCESS","");
+                            logger.info("send uas chatrobot message sucess {}", uMsg);
+                        }catch (Exception e){
+                            uasUApprovalMsgService.recodRobMsg(uMsg.getId_(),"FAIL",(e.getMessage().length() >= 1000 ? e.getMessage().substring(0,1000) : e.getMessage()));
+                            throw e;
+                        }
+                    }
+                }catch (Exception e){
+                    logger.error("send uas chatrobot message error", e);
+                }
+            } finally {
+                uasUApprovalMsgService.delRobMsg();
+                DataSourceHolder.clear();
+            }
+        }
+    }
+}