SpringBoot项目发送钉钉消息功能实现

 更新时间:2024年02月02日 11:16:07   作者:c103363  
在工作中的一些告警需要发送钉钉通知,有的是发给个人,有的要发到群里,这时项目就需要接入钉钉,实现发消息的功能,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧

背景:在工作中的一些告警需要发送钉钉通知,有的是发给个人,有的要发到群里,这时项目就需要接入钉钉,实现发消息的功能

1. 添加钉钉依赖

<dependency>
  <groupId>com.aliyun</groupId>
  <artifactId>dingtalk</artifactId>
  <version>2.0.14</version>
</dependency>
<dependency>
  <groupId>com.aliyun</groupId>
  <artifactId>alibaba-dingtalk-service-sdk</artifactId>
  <version>2.0.0</version>
</dependency>

2. 发送工作通知

发送通知需要使用access_token,获取token需要根据AppKey、AppSecret,所以需要在钉钉后台建一个应用,获许AppKey和AppSecret

2.1. 后台建一个应用

获取token文档:

https://open.dingtalk.com/document/orgapp/obtain-the-access_token-of-an-internal-app 

发消息文档:

https://open.dingtalk.com/document/orgapp/asynchronous-sending-of-enterprise-session-messages

2.2. 详细代码如下

替换相应的配置就可以直接发送了

import com.aliyun.dingtalkoauth2_1_0.models.GetAccessTokenResponse;
import com.aliyun.tea.TeaException;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiMessageCorpconversationAsyncsendV2Request;
import com.dingtalk.api.response.OapiMessageCorpconversationAsyncsendV2Response;
/**
 * @author csn
 * @date 2024/1/26
 * @description 发送个人消息
 */
public class SimpleExample {
    // 钉钉官方文档 - 获取 AccessToken
    // https://open.dingtalk.com/document/orgapp/obtain-the-access_token-of-an-internal-app
    // 钉钉官方文档 - 发送工作通知消息
    // https://open.dingtalk.com/document/orgapp/asynchronous-sending-of-enterprise-session-messages
    /**
     * 应用的 AgentId
     */
    private static Long AGENT_ID = 2883514974L;
    /**
     * 应用的 AppKey
     */
    private static String APP_KEY = "dingiektffikbgglasadcs";
    /**
     * 应用的 AppSecret
     */
    private static String APP_SECRET = "_Ha8VQMwM_Hht3jWrPR8502O3BIQ_Lzf-G7DsK4c-u2hz6y2hzFZ7WinumIy6X7khg";
    /**
     * 使用 Token 初始化账号Client
     *
     * @return Client
     * @throws Exception
     */
    public static com.aliyun.dingtalkoauth2_1_0.Client createClient() throws Exception {
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config();
        config.protocol = "https";
        config.regionId = "central";
        return new com.aliyun.dingtalkoauth2_1_0.Client(config);
    }
    /**
     * 获取 AccessToken
     *
     * @return AccessToken
     * @throws Exception
     */
    public static String getAccessToken() throws Exception {
        com.aliyun.dingtalkoauth2_1_0.Client client = createClient();
        com.aliyun.dingtalkoauth2_1_0.models.GetAccessTokenRequest getAccessTokenRequest = new com.aliyun.dingtalkoauth2_1_0.models.GetAccessTokenRequest()
        .setAppKey(APP_KEY)
        .setAppSecret(APP_SECRET);
        try {
            GetAccessTokenResponse accessToken = client.getAccessToken(getAccessTokenRequest);
            return accessToken.body.getAccessToken();
        } catch (TeaException err) {
            if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                // err 中含有 code 和 message 属性,可帮助开发定位问题
            }
        } catch (Exception exception) {
            TeaException err = new TeaException(exception.getMessage(), exception);
            if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                // err 中含有 code 和 message 属性,可帮助开发定位问题
            }
        }
        return null;
    }
    /**
     * 发送消息
     */
    public static void sendMessage() throws Exception {
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/message/corpconversation/asyncsend_v2");
        OapiMessageCorpconversationAsyncsendV2Request request = new OapiMessageCorpconversationAsyncsendV2Request();
        // 应用上可以看到
        request.setAgentId(AGENT_ID);
        // 发送给谁 (接收人的钉钉 userid)
        request.setUseridList("0168333232323702649");
        request.setToAllUser(false);
        OapiMessageCorpconversationAsyncsendV2Request.Msg msg = new OapiMessageCorpconversationAsyncsendV2Request.Msg();
        // 消息类型 - markdown
        msg.setMsgtype("markdown");
        msg.setMarkdown(new OapiMessageCorpconversationAsyncsendV2Request.Markdown());
        msg.getMarkdown().setText("##### text");
        msg.getMarkdown().setTitle("### Title");
        request.setMsg(msg);
        // token
        OapiMessageCorpconversationAsyncsendV2Response rsp = client.execute(request, getAccessToken());
        System.out.println(rsp.getBody());
    }
    /**
     * 测试发送个人消息
     */
    public static void main(String[] args) throws Exception {
        sendMessage();
    }
}

3. 发送群消息

3.1. 群内建立机器人

获取secret和Webhook就可以发送了

文档:

https://open.dingtalk.com/document/orgapp/custom-bot-to-send-group-chat-messages

建立机器人步骤如下:

img

img

给机器人取个名字

安全设置必选选一个,这里选择加签,后面要用到,具体原因可以看文档

img

完成后又个Webhook,这个是发送消息用的url

img

3.2. 详细代码如下

替换相应的配置就可以直接发送了

import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiRobotSendRequest;
import com.dingtalk.api.response.OapiRobotSendResponse;
import com.taobao.api.ApiException;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.codec.binary.Base64;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Collections;
/**
 * @author csn
 * @date 2024/1/26
 * @description 机器人发送群消息
 */
@Slf4j
public class BotExample {
    // 钉钉官方文档
    // https://open.dingtalk.com/document/orgapp/custom-bot-to-send-group-chat-messages
    /**
     * 机器人的加签秘钥 (替换成自己的)
     */
    private static final String SECRET = "SEC9a6b2202a0b92847fd7098630d20b4da9c02862d3696968a27b96d1e5fa073400o23412";
    /**
     * 机器人的webhook (替换成自己的)
     */
    private static final String URL = "https://oapi.dingtalk.com/robot/send?access_token=3c3628a434166b0b9180ddba360asd06b9999270e1655a031c74b362b069ef2f328";
    /**
     * 组装签名url
     *
     * @return url
     */
    public static String getUrl() throws NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeyException {
        Long timestamp = System.currentTimeMillis();
        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");
        String signResult = "&timestamp=" + timestamp + "&sign=" + sign;
        // 得到拼接后的 URL
        return URL + signResult;
    }
    /**
     * 获取客户端
     *
     * @return
     */
    public static DingTalkClient getClient() throws NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeyException {
        return new DefaultDingTalkClient(getUrl());
    }
    /**
     * 发送消息
     *
     * @param content
     * @throws ApiException
     * @throws NoSuchAlgorithmException
     * @throws UnsupportedEncodingException
     * @throws InvalidKeyException
     */
    public static void sendText(String content) throws ApiException, NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeyException {
        DingTalkClient client = getClient();
        OapiRobotSendRequest request = new OapiRobotSendRequest();
        // 消息类型 - 文本
        request.setMsgtype("text");
        OapiRobotSendRequest.Text text = new OapiRobotSendRequest.Text();
        text.setContent(content);
        request.setText(text);
        // @人
        OapiRobotSendRequest.At at = new OapiRobotSendRequest.At();
        // isAtAll类型如果不为Boolean,请升级至最新SDK
        at.setIsAtAll(false);
        // 钉钉上注册的手机号就行了
        at.setAtMobiles(Collections.singletonList("13123920295"));
        request.setAt(at);
        OapiRobotSendResponse response = client.execute(request);
        log.info("success:{}, code:{}, errorCode:{}, errorMsg:{}", response.isSuccess(), response.getCode(), response.getErrcode(), response.getErrmsg());
    }
    /**
     * 发送消息测试
     */
    public static void main(String[] args) throws UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeyException, ApiException {
        sendText("测试消息");
    }
}

到此这篇关于SpringBoot项目发送钉钉消息的文章就介绍到这了,更多相关SpringBoot发送钉钉消息内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • MyBatisPlus+Lombok实现分页功能的方法详解

    MyBatisPlus+Lombok实现分页功能的方法详解

    Lombok是一个Java类库,提供了一组注解,简化POJO实体类开发。本文将为大家介绍一下Lombok的使用以及如何利用MyBatisPlus+Lombok实现分页功能,感兴趣的可以动手尝试一下
    2022-07-07
  • 基于Java的电梯系统实现过程

    基于Java的电梯系统实现过程

    这篇文章主要介绍了基于Java的电梯系统实现过程,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2019-10-10
  • SpringBoot与JWT整合方式

    SpringBoot与JWT整合方式

    文章介绍了如何在Spring Boot项目中整合JWT(JSON Web Token),包括JWT的结构、使用方法、测试以及配置,主要内容涵盖了依赖配置、数据库表设计、实体类、数据访问层、服务层、JWT工具类、拦截器配置和控制器测试等多个方面
    2024-11-11
  • Java全能工具类之Hutool的用法详解

    Java全能工具类之Hutool的用法详解

    Hutool是一个Java工具类库,由国内的程序员loolly开发,目的是提供一些方便、快捷、实用的工具类和工具方法,本文就来详细聊聊它的使用吧
    2023-03-03
  • Maven的porfile与SpringBoot的profile结合使用案例详解

    Maven的porfile与SpringBoot的profile结合使用案例详解

    这篇文章主要介绍了Maven的porfile与SpringBoot的profile结合使用,通过maven的profile功能,在打包的时候,通过-P指定maven激活某个pofile,这个profile里面配置了一个参数activatedProperties,不同的profile里面的这个参数的值不同,需要的朋友可以参考下吧
    2021-12-12
  • Java中的分布式概念说明

    Java中的分布式概念说明

    在Java中,分布式系统是由一组通过网络进行通信、为了完成共同的任务而协调工作的计算机节点组成的系统,这种系统架构的目的是利用更多的机器处理更多的数据,从而解决单个计算机无法应对的计算、存储任务,本文给大家介绍Java中的分布式概念说明,感兴趣的朋友一起看看吧
    2025-09-09
  • 解决springmvc使用@PathVariable路径匹配问题

    解决springmvc使用@PathVariable路径匹配问题

    这篇文章主要介绍了解决springmvc使用@PathVariable路径匹配问题,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2021-02-02
  • Spring Cloud详解实现声明式微服务调用OpenFeign方法

    Spring Cloud详解实现声明式微服务调用OpenFeign方法

    这篇文章主要介绍了Spring Cloud实现声明式微服务调用OpenFeign方法,OpenFeign 是 Spring Cloud 家族的一个成员, 它最核心的作用是为 HTTP 形式的 Rest API 提供了非常简洁高效的 RPC 调用方式,希望对大家有所帮助。一起跟随小编过来看看吧
    2022-07-07
  • Mybatis延迟加载原理和延迟加载配置详解

    Mybatis延迟加载原理和延迟加载配置详解

    这篇文章主要介绍了Mybatis延迟加载原理和延迟加载配置详解,MyBatis中的延迟加载,也称为懒加载,是指在进行表的关联查询时,按照设置延迟规则推迟对关联对象的select查询,需要的朋友可以参考下
    2023-10-10
  • SpringBoot整合RocketMQ实现发送同步消息

    SpringBoot整合RocketMQ实现发送同步消息

    RocketMQ 是一款开源的分布式消息中间件,由阿里巴巴开源,它具有高可用性、高性能、低延迟等特点,广泛应用于阿里巴巴集团内部以及众多外部企业的业务系统中,本文给大家介绍了SpringBoot整合RocketMQ实现发送同步消息,需要的朋友可以参考下
    2024-04-04

最新评论