钉钉消息推送

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

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

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

设置机器人

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

设置机器人2

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

设置机器人3

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

设置机器人4

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

设置机器人5

    6.复制机器人的wbhook值

设置机器人6

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

二.代码实现:

    代码结构:


代码结构

    话不多说,上代码
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<String> atMobiles;

        // 是否全部@
        private boolean isAtAll;

        public TextMessage() {}

        public TextMessage(String text, List<String> 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<String> getAtMobiles() {return atMobiles;}

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

        public boolean isAtAll() {return isAtAll;}

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

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

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

            Map<String, Object> 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<String, Object> items = new HashMap<String, Object>();
            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<String> 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);
        }
    }
---

实现效果:

实现效果

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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 196,099评论 5 462
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 82,473评论 2 373
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 143,229评论 0 325
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,570评论 1 267
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,427评论 5 358
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,335评论 1 273
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,737评论 3 386
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,392评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,693评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,730评论 2 312
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,512评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,349评论 3 314
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,750评论 3 299
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,017评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,290评论 1 251
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,706评论 2 342
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,904评论 2 335