zoukankan      html  css  js  c++  java
  • 使用钉钉创建企业内部机器人

    玩转钉钉机器人

    前言
    钉钉的出现为企业节约了大量人力成本,其中也开放了大量的外部api接口方便企业使用。今天我们就来说说企业自研钉钉机器人的使用方法。请尽情食用

    创建钉钉机器人

    如何创建钉钉机器人

    登录钉钉开发者后台,依次选择应用开发 > 企业内部开发 > 机器人,点击创建应用。
    20211102103251
    20211102103324

    这个时候,企业自己的机器人就创建好了。

    如何调用机器人api

    1、添加接口调用权限。应用创建后默认只开放登录和消息通知接口的调用权限,您需要根据开发需要,添加对应的接口使用权限。

    2、获取应用的access_token。access_token相当于是身份凭证。调用接口时,通过access_token来鉴权调用者身份。

    20211102103745

    下载官网的sdk包:
    https://developers.dingtalk.com/document/app/download-the-server-side-sdk
    机器人回调所需要使用的apk
    <dependency>
        <groupId>com.aliyun</groupId>
            <artifactId>dingtalk</artifactId>
        <version>1.1.84</version>
    </dependency>
    

    支持的消息格式

    text类型

    {
        "at": {
            "atMobiles": [
                "180xxxxxx"
            ],
            "atUserIds": [
                "user123"
            ],
            "isAtAll": false
        },
        "text": {
            "content": "我就是我, @180xxxxxx 是不一样的烟火"
        },
        "msgtype": "text"
    }
    

    20211102104614

    markdown类型

    {
         "msgtype": "markdown",
         "markdown": {
             "title":"杭州天气",
             "text": "#### 杭州天气 @150XXXXXXXX \n> 9度,西北风1级,空气良89,相对温度73%\n> ![screenshot](https://img.alicdn.com/tfs/TB1NwmBEL9TBuNjy1zbXXXpepXa-2400-1218.png)\n> ###### 10点20分发布 [天气](https://www.dingalk.com) \n"
         },
          "at": {
              "atMobiles": [
                  "150XXXXXXXX"
              ],
              "atUserIds": [
                  "user123"
              ],
              "isAtAll": false
          }
     }
    

    20211102104707

    整体跳转actionCard类型

    {
        "msgtype": "actionCard",
        "actionCard": {
            "title": "打造一间咖啡厅", 
            "text": "![screenshot](https://img.alicdn.com/tfs/TB1NwmBEL9TBuNjy1zbXXXpepXa-2400-1218.png) \n #### 乔布斯 20 年前想打造的苹果咖啡厅 \n\n Apple Store 的设计正从原来满满的科技感走向生活化,而其生活化的走向其实可以追溯到 20 年前苹果一个建立咖啡馆的计划",
            "singleTitle" : "阅读全文",
            "singleURL" : "https://www.dingtalk.com/"
        }
    }
    

    20211102104746

    feedCard类型

    {
        "msgtype": "feedCard",
        "feedCard": {
            "links": [
                {
                    "title": "时代的火车向前开1", 
                    "messageURL": "https://www.dingtalk.com/", 
                    "picURL": "https://img.alicdn.com/tfs/TB1NwmBEL9TBuNjy1zbXXXpepXa-2400-1218.png"
                },
                {
                    "title": "时代的火车向前开2", 
                    "messageURL": "https://www.dingtalk.com/", 
                    "picURL": "https://img.alicdn.com/tfs/TB1NwmBEL9TBuNjy1zbXXXpepXa-2400-1218.png"
                }
            ]
        }
    }
    

    20211102104833

    使用钉钉机器人推送消息

     @PostMapping(value = "/robots")
        public String helloRobots(@RequestBody RobotResponse robotResponse
        ) throws Exception {
            String[] content = robotResponse.getText().getContent().split(" ");
            if (content.length == 2) {
                return dingtalkRobotTypeService.findByQuestion(content[0], content[1]);
            } else if (content.length == 1) {
                if (content[0].equals("公告")) {
                    return RobotReplyService.feedCard(Arrays.asList(
                            new RobotFeedCard.FeedCardBean.LinksBean("时代的火车向前开1", "https://www.dingtalk.com/", "https://img.alicdn.com/tfs/TB1NwmBEL9TBuNjy1zbXXXpepXa-2400-1218.png"),
                            new RobotFeedCard.FeedCardBean.LinksBean("时代的火车向前开2", "https://www.dingtalk.com/", "https://img.alicdn.com/tfs/TB1NwmBEL9TBuNjy1zbXXXpepXa-2400-1218.png"),
                            new RobotFeedCard.FeedCardBean.LinksBean("时代的火车向前开2", "https://www.dingtalk.com/", "https://img.alicdn.com/tfs/TB1NwmBEL9TBuNjy1zbXXXpepXa-2400-1218.png"),
                            new RobotFeedCard.FeedCardBean.LinksBean("时代的火车向前开2", "https://www.dingtalk.com/", "https://img.alicdn.com/tfs/TB1NwmBEL9TBuNjy1zbXXXpepXa-2400-1218.png")));
                } else if (content[0].equals("活动")) {
                    return RobotReplyService.aloneActionCard("你想参加这次活动", "![screenshot](https://img.alicdn.com/tfs/TB1NwmBEL9TBuNjy1zbXXXpepXa-2400-1218.png) \n>你就说你想不想参加活动吧\n>", 1, Arrays.asList(
                            new RobotAloneActionCard.ActionCardBean.BtnsBean("参加", "fsdfsdf"), new RobotAloneActionCard.ActionCardBean.BtnsBean("不想参加", "不想参加")));
                } else if (content[0].equals("测试")) {
                    return RobotReplyService.markdown(null, "啦啦啦啦", "[啦啦啦啦](啦啦啦啦啦)");
    
                }
                return dingtalkRobotService.findByQuestion(content[0]);
            } else {
                return RobotReplyService.text(null, "不知道你想说啥");
            }
        }
    

    机器人交互式卡片设计

    如何发送交互式卡片

    配置消息模板

    1、登录钉钉OA管理后台。

    2、进入钉钉可交互卡片搭建平台,在搭建平台上则可以看到当前组织内所创建的所有互动消息模板。
    20211102105214
    3、单击右上角的新增模板,然后输入模板名称,选择卡片类型,最后单击确认完成模板创建。
    20211102105538

    修改机器人交互卡片回调地址

    /**
         * 注册回调地址
         *
         * @throws BusinessException
         * @throws ApiException
         */
        public static OapiImChatScencegroupInteractivecardCallbackRegisterResponse registerURL(String url) throws Exception {
            DingTalkClient client = new DefaultDingTalkClient(O_API + "top/im/chat/scencegroup/interactivecard/callback/register");
            RobotCallBack req = new RobotCallBack();
            req.setCallbackUrl(url + "/robot/callback");
            req.setApiSecret("bgRtxxxx");
            req.setForceUpdate("true");
            OapiImChatScencegroupInteractivecardCallbackRegisterResponse rsp = client.execute(req, AccessTokenUtil.getAccessToken());
            return rsp;
        }
    

    发送机器人交互消息

    /**
         * 机器人推送互动卡片
         *
         * @param cardId
         * @param phone
         * @param cardData
         * @throws Exception
         */
        public static void sendCardMsg(String cardId, String phone, Map<String, String> cardData) throws Exception {
            String userId = getUserIdByMobile(phone);
            com.aliyun.dingtalkim_1_0.Client client = new com.aliyun.dingtalkim_1_0.Client(AccessTokenUtil.getHttpConfig());
            SendInteractiveCardHeaders sendInteractiveCardHeaders = new SendInteractiveCardHeaders();
            sendInteractiveCardHeaders.xAcsDingtalkAccessToken = AccessTokenUtil.getAccessToken();
            SendInteractiveCardRequest sendInteractiveCardRequest = new SendInteractiveCardRequest()
                    .setCardTemplateId(cardId)
                    .setReceiverUserIdList(Collections.singletonList(userId))
                    .setOutTrackId(IdUtil.simpleUUID())
                    .setCardData(new SendInteractiveCardRequest.SendInteractiveCardRequestCardData().setCardParamMap(cardData))
                    .setOpenConversationId("cidJeCuP2boERqlkwy0rv4qHg")
                    .setConversationType(1);
            try {
                client.sendInteractiveCardWithOptions(sendInteractiveCardRequest, sendInteractiveCardHeaders, new RuntimeOptions());
            } catch (TeaException err) {
                log.error(JSON.toJSONString(err.getData()));
            } catch (Exception _err) {
                TeaException err = new TeaException(_err.getMessage(), _err);
                log.error(JSON.toJSONString(err.getData()));
            }
        }
    

    20211102105837

    接受交互卡片回调消息

     /**
         * 钉钉机器人触发回调事件
         *
         * @param tractId
         * @param cardData
         * @throws Exception
         */
        public static void updateCardMsg(String tractId, Map<String, String> cardData) throws Exception {
            com.aliyun.dingtalkim_1_0.Client client = new com.aliyun.dingtalkim_1_0.Client(AccessTokenUtil.getHttpConfig());
            UpdateInteractiveCardHeaders updateInteractiveCardHeaders = new UpdateInteractiveCardHeaders();
            updateInteractiveCardHeaders.xAcsDingtalkAccessToken = AccessTokenUtil.getAccessToken();
            UpdateInteractiveCardRequest updateInteractiveCardRequest = new UpdateInteractiveCardRequest()
                    .setOutTrackId(tractId)
                    .setCardData(new UpdateInteractiveCardRequest.UpdateInteractiveCardRequestCardData()
                            .setCardParamMap(cardData))
                    .setUserIdType(1);
            try {
                UpdateInteractiveCardResponse updateInteractiveCardResponse = client.updateInteractiveCardWithOptions(updateInteractiveCardRequest, updateInteractiveCardHeaders, new RuntimeOptions());
                log.info(JSONObject.toJSONString(updateInteractiveCardResponse));
            } catch (TeaException err) {
                log.error(JSON.toJSONString(err.getData()));
            } catch (Exception _err) {
                TeaException err = new TeaException(_err.getMessage(), _err);
                log.error(JSON.toJSONString(err.getData()));
            }
        }
    

    20211102110015

    这个时候 我们就可以按照自己的需求来开发相应业务逻辑了

    文章参考:钉钉开发展中心

    福禄·研发中心 福小雄
  • 相关阅读:
    Notes of Daily Scrum Meeting(12.18)
    Notes of Daily Scrum Meeting(12.17)
    Notes of Daily Scrum Meeting(12.16)
    Notes of Daily Scrum Meeting(12.8)
    Notes of Daily Scrum Meeting(12.5)
    Notes of Daily Scrum Meeting(12.3)
    Notes of Daily Scrum Meeting(11.12)
    Linux中profile、bashrc、bash_profile之间的区别和联系
    Linux GCC编译
    mysql 5.7.16 远程连接
  • 原文地址:https://www.cnblogs.com/fulu/p/15527278.html
Copyright © 2011-2022 走看看