使用钉钉机器人在群发送消息

RobotRequest

package com.iwhalecloud.iom.utils.helper.dingRobot;

import org.eclipse.xtend.lib.annotations.Data;

import java.util.List;
public class RobotRequest {
    /**
     * 消息类型
     */
    private String msgtype;

    /**
     * 文本类型
     */
    private Text text;

    /**
     * 被@的人
     */
    private At at;

    /**
     * link类型
     */
    private Link link;

    /**
     * markdown类型
     */
    private Markdown markdown;

    public String getMsgtype() {
        return msgtype;
    }

    public RobotRequest setMsgtype(String msgtype) {
        this.msgtype = msgtype;
        return this;
    }

    public Text getText() {
        return text;
    }

    public RobotRequest setText(Text text) {
        this.text = text;
        return this;
    }

    public At getAt() {
        return at;
    }

    public RobotRequest setAt(At at) {
        this.at = at;
        return this;
    }

    public Link getLink() {
        return link;
    }

    public RobotRequest setLink(Link link) {
        this.link = link;
        return this;
    }

    public Markdown getMarkdown() {
        return markdown;
    }

    public RobotRequest setMarkdown(Markdown markdown) {
        this.markdown = markdown;
        return this;
    }

    static class Text {
        /**
         * 消息内容。
         */
        private String content;

        public String getContent() {
            return content;
        }

        public Text setContent(String content) {
            this.content = content;
            return this;
        }
    }


    static class At {
        /**
         * 被@人的手机号。
         */
        private List<Object> atMobiles;

        /**
         * 是否@所有人。
         */
        private boolean isAtAll;

        public List<Object> getAtMobiles() {
            return atMobiles;
        }

        public At setAtMobiles(List<Object> atMobiles) {
            this.atMobiles = atMobiles;
            return this;
        }

        public boolean isAtAll() {
            return isAtAll;
        }

        public At setAtAll(boolean atAll) {
            isAtAll = atAll;
            return this;
        }
    }

    static class Link {
        /**
         * 消息内容。如果太长只会部分展示。
         */
        private String text;
        /**
         * 消息标题
         */
        private String title;

        /**
         * 点击消息跳转url
         */
        private String messageUrl;

        /**
         * 图片url
         */
        private String picUrl;

        public String getText() {
            return text;
        }

        public Link setText(String text) {
            this.text = text;
            return this;
        }

        public String getTitle() {
            return title;
        }

        public Link setTitle(String title) {
            this.title = title;
            return this;
        }

        public String getMessageUrl() {
            return messageUrl;
        }

        public Link setMessageUrl(String messageUrl) {
            this.messageUrl = messageUrl;
            return this;
        }

        public String getPicUrl() {
            return picUrl;
        }

        public Link setPicUrl(String picUrl) {
            this.picUrl = picUrl;
            return this;
        }
    }

    static class Markdown {
        /**
         * markdown格式的消息。
         */
        private String text;
        /**
         * 首屏会话透出的展示内容。
         */
        private String title;

        public String getText() {
            return text;
        }

        public Markdown setText(String text) {
            this.text = text;
            return this;
        }

        public String getTitle() {
            return title;
        }

        public Markdown setTitle(String title) {
            this.title = title;
            return this;
        }
    }


}
RobotResponse

package com.iwhalecloud.iom.utils.helper.dingRobot;

public class RobotResponse {
    /**
     * 结果码
     */
    private Integer code;
    /**
     * 结果信息
     */
    private String msg;

    public Integer getCode() {
        return code;
    }

    public RobotResponse setCode(Integer code) {
        this.code = code;
        return this;
    }

    public String getMsg() {
        return msg;
    }

    public RobotResponse setMsg(String msg) {
        this.msg = msg;
        return this;
    }
}
TestRobotMain

package com.iwhalecloud.iom.utils.helper.dingRobot;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonArray;
import com.iwhalecloud.iom.base.utils.GsonUtils;
import com.iwhalecloud.iom.base.utils.data.StringUtils;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StopWatch;
import org.springframework.web.client.RestTemplate;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;

public class TestRobotMain {
    private static Logger logger = LoggerFactory.getLogger(TestRobotMain.class);
    /**
     * 消息类型
     */
    private static final String MSG_TYPE_TEXT = "text";
    private static final String MSG_TYPE_LINK = "link";
    private static final String MSG_TYPE_MARKDOWN = "markdown";
    private static final String MSG_TYPE_ACTION_CARD = "actionCard";
    private static final String MSG_TYPE_FEED_CARD = "feedCard";

    private static final String ACCESS_TOKEN = "https://oapi.dingtalk.com/robot/send?access_token=2f5ef6b25b3c9c2becc77240a3db917455ca623061f0ed24f7118bae7d46a518";

    public static void main(String[] args) throws Exception {
        try {
            HttpEntity<String> demandResponse = callQuery();

            String result = demandResponse.getBody();
            List<Map> resultList = JSONObject.parseObject(result, List.class);
            Map<String, List<String>> resultMap = new HashMap<>();
            List<Map> haveDealStaffList = new ArrayList<>();
            List<String> transIds = new ArrayList<>();
            List<String> dealStaffs = new ArrayList<>();
            StopWatch s = new StopWatch();
            s.start();
            for (Map map : resultList) {
                String transId = map.get("transId").toString();
                String dealStaff = map.get("dealStaff").toString();
                if (!dealStaff.equals("[]")) {
                    if (!dealStaffs.contains(dealStaff)) {
                        dealStaffs.add(dealStaff);
                    }
                    Map<String, String> childMap = new HashMap<>();
                    transIds.add(transId);
                    childMap.put(transId, dealStaff);
                    haveDealStaffList.add(childMap);
                }
            }
            for (String dealStaff : dealStaffs) {
                List<String> onlyTransIds = new ArrayList<>();
                for (String transId : transIds) {
                    for (Map map : haveDealStaffList) {
                        if (map.get(transId) != null && map.get(transId).equals(dealStaff)) {
                            onlyTransIds.add(transId);
                        }
                    }
                }
                resultMap.put(dealStaff, onlyTransIds);
            }
            StringBuilder sb = new StringBuilder();
            sb.append(String.format("共有%d张需求单七天内到期,请登录zmp尽快处理!", transIds.size()));
            sb.append("\r\n");
            for (String dealStaff : dealStaffs) {
                sb.append(String.format("zmp%s-%s", resultMap.get(dealStaff), dealStaff.substring(dealStaff.lastIndexOf("]") + 1)));
                sb.append("\r\n");
            }

            //发送钉钉机器人请求
            sendRobotRequest(sb.toString());
        } catch (Exception e) {
          throw new RuntimeException("捕获数据异常"+e.getMessage());
        }
    }

    /**
     * 发送钉钉机器人请求
     */
    private static void sendRobotRequest(String content) throws Exception {
        long timestamp = System.currentTimeMillis();
        String secret = "SEC10850f0b9829ca30030f7424d14d778381b547b15f9bfac937b3a52ba3f1c209";
        String sign = getSign(timestamp, secret);
        System.out.println("当前时间戳:" + timestamp);
        System.out.println("签名值:" + sign);
        String url = String.format(ACCESS_TOKEN + "&timestamp=%s&sign=%s", timestamp, sign);
        List<Object> mobileList = new ArrayList<>();
        HttpEntity<String> response = sendText(url, content, mobileList, true);
        if (response != null) {
            logger.info("发送成功:" + response.getBody());
        } else {
            logger.info("发送失败,请求返回结果为null");
        }
    }

    /**
     * 请求获取数据
     *
     * @return
     */
    public static HttpEntity<String> callQuery() {
        Date date = new Date();
        SimpleDateFormat formatAccurate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String currdateAccurate = formatAccurate.format(date);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String currdate = format.format(date);
        //  封装参数,千万不要替换为Map与HashMap,否则参数无法传递
        MultiValueMap<String, Object> content = new LinkedMultiValueMap<>();
        content.add("DEAL_STAFF", "26367,29057,29355,28698,17457,18061,18129,18193,18531,18632,20175,20176," +
                "20180,21171,23211,23464,23845,24462,24787,25254,27129,27324,28540,13938,518,882,996,2306,2565," +
                "3672,4126,4760,10838,12282,12283,14104,14304,14822,14975,15124,8673,8678,15522,15755");
        content.add("serviceName", "QueryTansAdv");
        content.add("DIR_ID", "6");
        content.add("ORG_STATE", "1");
        content.add("ISREQ", "1");
        content.add("DEV_CENTER_CODE", "'GZ'");
        //处理日期
        content.add("CREATE_S_DATE", "2021-02-05 00:00:00");
        content.add("CREATE_E_DATE", "2021-03-06 23:59:59");
//       content.add("DESIGN_S_DATE", "2021-03-02");
//        content.add("DESIGN_E_DATE", "2021-03-05");
        HttpHeaders headers = new HttpHeaders();
        HttpEntity<String> response = null;
        headers.set("Cookie", "SESSION=b594ee0d-50be-4609-b7ee-00fbcaef3328");
        String url = "请求地址接口";
        HttpEntity<MultiValueMap<String, Object>> message = new HttpEntity<MultiValueMap<String, Object>>(content, headers);
        RestTemplate restTemplate = new RestTemplate();
        try {
            response = restTemplate.exchange(url, HttpMethod.POST, message, String.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return response;
    }

    /**
     * 获取签名值
     */
    private static String getSign(long timestamp, String secret) throws Exception {
        String stringToSign = timestamp + "\n" + secret;
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
        byte[] signData = mac.doFinal(stringToSign.getBytes(StandardCharsets.UTF_8));
        String sign = URLEncoder.encode(new String(Base64.encodeBase64(signData)), "UTF-8");
        return sign;
    }

    /**
     * 发送消息
     */
    public static HttpEntity<String> sendText(String url, String content, List<Object> mobileList, boolean isAtAll) throws Exception {
        if (StringUtils.isEmpty(content)) {
            return null;
        }
        RobotRequest.Text text = new RobotRequest.Text();
        text.setContent(content);
        RobotRequest request = new RobotRequest();
        RobotRequest.At at = new RobotRequest.At();
        if (CollectionUtils.isNotEmpty(mobileList)) {
            at.setAtMobiles(mobileList);
        }
        at.setAtAll(isAtAll);
        request.setAt(at);
        request.setMsgtype(MSG_TYPE_TEXT);
        request.setText(text);

        HttpHeaders headers = new HttpHeaders();
        HttpEntity<String> response = null;
        headers.setContentType(MediaType.parseMediaType("application/json"));
        HttpEntity<Object> message = new HttpEntity<Object>(GsonUtils.toJson(request), headers);
        RestTemplate restTemplate = new RestTemplate();
        try {
            response = restTemplate.exchange(url, HttpMethod.POST, message, String.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return response;
    }

    /**
     * 获取结束时间,精确到时分秒
     *
     * @param date
     * @return
     */
    public static String endDateAccurate(Date date) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar ca = Calendar.getInstance();
        //num为增加的天数,可以改变的
        ca.add(Calendar.DATE, 7);
        date = ca.getTime();
        String enddate = format.format(date);
        return enddate;
    }

    /**
     * 获取结束时间日期
     *
     * @param date
     * @return
     */
    public static String endDate(Date date) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Calendar ca = Calendar.getInstance();
        // num为增加的天数,可以改变的
        ca.add(Calendar.DATE, 7);
        date = ca.getTime();
        String enddate = format.format(date);
        return enddate;
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值