钉钉消息推送

    首先,我们来看一下钉钉消息推送的官方sdk https://open-doc.dingtalk.com/microapp/serverapi2/qf2nxq
    从官方文档中可以看出,当前自定义机器人支持文本 (text)、连接 (link)、markdown (markdown)、ActionCard、FeedCard等五种消息类型.作者使用的系统主要发送文本消息,故本文以text类型为例做主要讲解,其他类型请自行修改对应输入格式即可.
    实现钉钉消息推送主要分两步:
        1.在钉钉群中设置自定义机器人
        2.代码实现

一.设置机器人具体步骤:

    1.找到需要发消息的群,点击右上角的"..."

钉钉消息推送_第1张图片
设置机器人

    2.在弹出的群设置中点击"群机器人"

钉钉消息推送_第2张图片
设置机器人2

    3.在弹出的"群机器人"页面中选择"自定义"

钉钉消息推送_第3张图片
设置机器人3

    4.在弹出的"机器人详情"点击"添加"

钉钉消息推送_第4张图片
设置机器人4

    5.输入机器人姓名,点击完成

钉钉消息推送_第5张图片
设置机器人5

    6.复制机器人的wbhook值

钉钉消息推送_第6张图片
设置机器人6

    ok,设置机器人完成,下面就可以上代码啦.

二.代码实现:

    代码结构:


钉钉消息推送_第7张图片
代码结构

    话不多说,上代码
Car.java
---

    public class Car implements Serializable {
        private static final long serialVersionUID = 19930906L;
        // id
        private String id;
        // 品牌
        private String brand;
        // 颜色
        private String color;
        // 价格
        private Integer price;

        public Car() {}

        public Car(String id, String brand, String color, Integer price) {this.id = id; this.brand = brand;this.color = color;this.price = price;}

        public String getId() {return id;}

        public void setId(String id) {this.id = id;}

        public String getBrand() {return brand;}

        public void setBrand(String brand) {this.brand = brand;}

        public String getColor() {return color;}

        public void setColor(String color) {this.color = color;}

        public Integer getPrice() {return price;}

        public void setPrice(Integer price) {this.price = price;}

        @Override public String toString() {
                return "您要提的车: \n " + "编号='" + id + '\'' + "\n" + " 品牌='" + brand + '\'' + "\n" + " 颜色='" + color + '\'' + "\n" + " 价格='" + price + '\'' ;
        }
}
---

TextMessage.java
---

    public class TextMessage {
        // 发送消息文本
        private String text;

        // @相关人员
        private List atMobiles;

        // 是否全部@
        private boolean isAtAll;

        public TextMessage() {}

        public TextMessage(String text, List atMobiles, boolean isAtAll) {this.text = text;this.atMobiles = atMobiles;this.isAtAll = isAtAll;}

        public TextMessage(String text) {this.text = text;}

        public String getText() {return text;}

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

        public List getAtMobiles() {return atMobiles;}

        public void setAtMobiles(List atMobiles) {this.atMobiles = atMobiles;}

        public boolean isAtAll() {return isAtAll;}

        public void setIsAtAll(boolean isAtAll) {this.isAtAll = isAtAll;}

        public String toJsonString() {
            Map items = Maps.newHashMap();
            items.put("msgtype", "text");

            Map textContent = Maps.newHashMap();
            if (StringUtil.isEmpty(text)) {throw new IllegalArgumentException("text should not be blank");}
            textContent.put("content", text);
            items.put("text", textContent);

            Map atItems = Maps.newHashMap();
            if (atMobiles != null && !atMobiles.isEmpty()) {atItems.put("atMobiles", atMobiles);}
            if (isAtAll) {atItems.put("isAtAll", isAtAll);}
            items.put("at", atItems);

            return JSON.toJSONString(items);
        }
    }
---

SendResult.java
---

    public class SendResult {

        private boolean isSuccess;

        private Integer errorCode;

        private String errorMsg;

        public boolean isSuccess() {return isSuccess;}

        public void setIsSuccess(boolean isSuccess) {this.isSuccess = isSuccess;}

        public Integer getErrorCode() {return errorCode;}

        public void setErrorCode(Integer errorCode) {this.errorCode = errorCode;}

        public String getErrorMsg() {return errorMsg;}

        public void setErrorMsg(String errorMsg) {this.errorMsg = errorMsg;}

        @Override

        public String toString() {
            Map items = new HashMap();
            items.put("errorCode", errorCode);
            items.put("errorMsg", errorMsg);
            items.put("isSuccess", isSuccess);
            return JSON.toJSONString(items);
        }
    }

---

ChatbotSend.java
---

    public class ChatbotSend {

        public static String WEBHOOK_TOKEN = "https://oapi.dingtalk.com/robot/send?access_token=908a861a9ca64f7c8d2d84c6df6b7b40ae02510ce20c3f503fc360554db90f8b";

        public static void main(String args[]) throws Exception {

            // 创建httpClient对象
            HttpClient httpclient = HttpClients.createDefault();
            // 设置请求地址
            HttpPost httppost = new HttpPost(WEBHOOK_TOKEN);
            // 设置请求头
            httppost.addHeader("Content-Type", "application/json; charset=utf-8");
            // 创建消息,编辑信息
            Car car = new Car("001","PORSCHE","red", 188888888);
            List phoneNumberList = Lists.newArrayList("18861875152");
            String textMessage = new TextMessage(car.toString(), phoneNumberList, false).toJsonString();

            /**
            * 消息模板 toJsonString
            * String textMessage = "{ \"msgtype\": \"text\", \"text\": {\"content\":\""+ sendStr +"\"},\"at\": {\"atMobiles\":[\"15827624153\"],\"isAtAll\":false}}";
            */
            // 设置请求内容
            StringEntity se = new StringEntity(textMessage, "utf-8");
            httppost.setEntity(se);
            // 执行http请求
            HttpResponse response = httpclient.execute(httppost);
            // 请求成功打印消息结果
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                String result = EntityUtils.toString(response.getEntity(), "utf-8");
                System.out.println(result);
            }
        }
    }
---

RobotClient.java
---

    public class RobotClient {
        HttpClient httpclient = HttpClients.createDefault();
        public SendResult send(String webhook, TextMessage message) throws IOException {
            HttpPost httppost = new HttpPost(webhook);
            httppost.addHeader("Content-Type", "application/json; charset=utf-8");

            StringEntity se = new StringEntity(message.toJsonString(), "utf-8");
            httppost.setEntity(se);

            SendResult sendResult = new SendResult();
            HttpResponse response = httpclient.execute(httppost);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                String result = EntityUtils.toString(response.getEntity());
                JSONObject obj = JSONObject.parseObject(result);
                Integer errcode = obj.getInteger("errcode");
                sendResult.setErrorCode(errcode);
                sendResult.setErrorMsg(obj.getString("errmsg"));
                sendResult.setIsSuccess(errcode.equals(0));
            }

            return sendResult;
         }
    }
---

StringUtil.java
---

    public class StringUtil {
        public static boolean isEmpty(String text) {return (text == null || text.isEmpty()) ? true : false;}
    }

DingTalkDemoApplication.java

    public class DingTalkDemoApplication {
        public static void main(String[] args) {
            SpringApplication.run(DingTalkDemoApplication.class, args);
        }
    }
---

实现效果:

钉钉消息推送_第8张图片
实现效果

最后附上代码地址:https://git.dev.tencent.com/nshm/dingTalk-learning.git

你可能感兴趣的:(钉钉消息推送)