对接钉钉消息样例:DING消息、机器人

一、钉钉开放平台配置信息

private static String robotCode =

private static String appkey =

private static String appsecret =

private static Long agentId =

二、钉钉开放平台token、用户信息

java 复制代码
    public static Client createClient() throws Exception {
        Config config = new Config();
        config.protocol = "https";
        config.regionId = "central";
        return new com.aliyun.dingtalkrobot_1_0.Client(config);
    }

    /**
     * 根据手机号获取钉钉ID
     *
     * @param phone
     * @return
     */
    private static String getDingUserId(String phone) {
        String userId = "";
        try {
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/getbymobile");
            OapiV2UserGetbymobileRequest req = new OapiV2UserGetbymobileRequest();
            req.setMobile(phone);
            req.setSupportExclusiveAccountSearch(true);
            OapiV2UserGetbymobileResponse rsp = client.execute(req, getAccessToken());
            log.info("获取userId:{}", JSON.toJSONString(rsp.getResult()));
            userId = rsp.getResult().getExclusiveAccountUseridList().get(0);
        } catch (ApiException e) {
            log.error("根据手机号获取userID失败:{}", e.getMessage());
        }
        return userId;
    }

    /**
     * 获取钉钉accessToken
     *
     * @return
     */
    private static String getAccessToken() {
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken");
        OapiGettokenRequest req = new OapiGettokenRequest();
        req.setAppkey(appkey);
        req.setAppsecret(appsecret);
        req.setHttpMethod("GET");
        OapiGettokenResponse rsp = null;
        try {
            rsp = client.execute(req);
            return rsp.getAccessToken();
        } catch (ApiException e) {
            log.error("获取钉钉accessToken失败:{}", e.getMessage());
        }
        return null;
    }

2.1、发送DING消息

java 复制代码
    @Retryable(value = {Exception.class}, maxAttempts = 3, backoff = @Backoff(delay = 1000))
    public static String snedDingdingMessage(String content, String phone) throws Exception {
        Client client = DingDingRobotUtil.createClient();
        RobotSendDingHeaders robotSendDingHeaders = new RobotSendDingHeaders();
        robotSendDingHeaders.xAcsDingtalkAccessToken = getAccessToken();
        String dingUserId = getDingUserId(phone);
        if (StrUtil.isBlank(dingUserId)) {
            return "获取钉钉userId失败";
        }
        RobotSendDingRequest robotSendDingRequest = new RobotSendDingRequest()
                .setRobotCode(robotCode)
                .setContent(content)
                .setRemindType(1)
                .setReceiverUserIdList(Arrays.asList(dingUserId));
        log.info("钉钉消息:{}", robotSendDingRequest);
        RobotSendDingResponse response;
        try {
            response = client.robotSendDingWithOptions(robotSendDingRequest, robotSendDingHeaders, new RuntimeOptions());
            log.info("消息发送结果:{}", JSON.toJSONString(response));
            return JSON.toJSONString(response);
        } catch (Exception e) {
            return e.getMessage();
        }

    }

2.2、发送机器人消息-图文形式

图片转为base64编码,然后上传钉钉获取media_id,发送图文消息

java 复制代码
  public static String messageNoticePush(String base64, String content, String phone) {
        try {
            // 1. 获取accessToken和用户ID
            String accessToken = getAccessToken();
            String dingUserId = getDingUserId(phone);
            log.info("获取token了:{}" + accessToken);

            // 2. 初始化客户端
            DingTalkClient talkClient = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/message/corpconversation/asyncsend_v2");

            // 3. 构建请求基础信息
            OapiMessageCorpconversationAsyncsendV2Request request = new OapiMessageCorpconversationAsyncsendV2Request();
            request.setUseridList(dingUserId);
            request.setAgentId(agentId); // 替换为你的实际AgentId


            OapiMessageCorpconversationAsyncsendV2Request.Msg msg = new OapiMessageCorpconversationAsyncsendV2Request.Msg();

//            图片
            msg.setMsgtype("markdown");
            OapiMessageCorpconversationAsyncsendV2Request.Markdown markdown = new OapiMessageCorpconversationAsyncsendV2Request.Markdown();
            markdown.setTitle("设备预警");
            // 4. 上传图片获取media_id
            if (StrUtil.isNotBlank(base64)) {
                log.info("存在图片");
                String mediaId = upload(base64); // 假设这是你上传图片的方法
                markdown.setText(content + "\n " +
                        "> ![image](" + mediaId + ") \n ");
            } else {
                log.info("无图片");
                markdown.setText(content);
            }
            msg.setMarkdown(markdown);
            request.setMsg(msg);
            OapiMessageCorpconversationAsyncsendV2Response response = talkClient.execute(request, accessToken);
            log.info("调用钉钉接口完毕:{}" + response);

            if (response.getErrcode().equals(0L)) {
                log.info("推送成功: {}", response.getBody());
                return "success";
            } else {
                log.error("推送失败,错误码: {}, 错误信息: {}", response.getErrcode(), response.getErrmsg());
                return "failed";
            }
        } catch (Exception e) {
            log.error("推送失败: ", e);
            return "error";
        }
    }


    public static String upload(String base64Pic) throws IOException {

        String pureBase64 = base64Pic.replaceFirst("data:image/\\w+;base64,", "");
        byte[] fileBytes = Base64.getDecoder().decode(pureBase64);
        HttpRequest body = HttpUtil.createPost(
                        "https://oapi.dingtalk.com/media/upload?access_token=" + getAccessToken()
                )
                .header("Content-Type", "multipart/form-data")
                .form("type", "image")
                .form("media", fileBytes, "image.png");

        String result = body.execute().body();
        JSONObject json = JSONUtil.parseObj(result);
        log.info("上传文件:{}" + json);

        if (json.getInt("errcode") != 0) {
            throw new IOException("钉钉返回错误: " + json.getStr("errmsg"));
        }
        return json.getStr("media_id");
    }

注意:普通文本发送图文消息是文字+图片url链接(BING\机器人均可);

base64格式的图片只能通过机器人;

钉钉链接地址:发送DING消息 - 钉钉开放平台

相关推荐
程序猿_极客几秒前
【2025 最新】 Python 安装教程 以及 Pycharm 安装教程(超详细图文指南,附常见问题解决)
开发语言·python·pycharm·python安装以及配置
2501_941235732 分钟前
C++中的装饰器模式变体
开发语言·c++·算法
2501_941111252 分钟前
基于C++的爬虫框架
开发语言·c++·算法
b***66614 分钟前
Python 爬虫实战案例 - 获取社交平台事件热度并进行影响分析
开发语言·爬虫·python
ModestCoder_11 分钟前
Tokenization的演进:从NLP基石到多模态AI的“通用翻译器”
开发语言·人工智能·自然语言处理·机器人·具身智能
小虾米 ~11 分钟前
RocketMQ DefaultMQPushConsumer vs DefaultLitePullConsumer
java·rocketmq·java-rocketmq
q***216013 分钟前
【监控】spring actuator源码速读
java·spring boot·spring
Kuo-Teng24 分钟前
LeetCode 142: Linked List Cycle II
java·算法·leetcode·链表·职场和发展
Moe48830 分钟前
ConcurrentHashMap 重要方法实现原理和源码解析(一)
java·后端
hweiyu0030 分钟前
GO的优缺点
开发语言·后端·golang