钉钉消息推送()

记录一下java实现消息推送

1. 首先添加依赖

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

        <dependency>
            <groupId>commons-codec</groupId>
            <artifactId>commons-codec</artifactId>
            <version>1.11</version>
        </dependency>
</dependencies>

2. 配置钉钉推送application.yml文件

dingding:
  agentId: 25702
  appKey: dingwsjy7bu
  appSecret: eFROKkCe5JQvYOuru0ZXKzSyaBL9RAI-o6KTilfmVn3STg
  messageServerUrl: https://oapi.dingtalk.com/topapi/message
  tokenServerUrl: https://oapi.dingtalk.com/
  getbymobileServerUrl: https://oapi.dingtalk.com/topapi/v2
  secret: SECc10440b6571aa687b056488d93eb418443ac8d89615489d9a0b
  accessToken: 11da3106cd3ebc2e117e0d2e4cd4e91801eb4a481ec6bb2e

创建一个读取这些配置的config类型,如下

/**
 * 读取钉钉相关配置
 *
 * @author lkx
 */
@Component
@ConfigurationProperties(prefix = "dingding")
@Data
public class DingConfig
{

    private String agentId;

    private String appKey;

    private String appSecret;

    private String messageServerUrl;

    private String tokenServerUrl;

    private String getbymobileServerUrl;

   private String secret;

   private String accessToken;
}

3. 创建一个单独的service和实现类

public interface DingMessageService {


    /**
     * 发送钉钉群
     * @param markdown
     */
    void sendCrowdMessage(OapiRobotSendRequest.Markdown markdown);
}

实现类

@Slf4j
@Service
public class DingMessageServiceImpl implements DingMessageService {

    /**
     * DingDing配置
     */
    @Autowired
    private DingConfig dingConfig;



    @Async("threadPool")
    @Override
    public void sendCrowdMessage(OapiRobotSendRequest.Markdown markdown) {

        try {
            Long timestamp = System.currentTimeMillis();
            String stringToSign = timestamp + "\n" + dingConfig.getSecret();
            Mac mac = Mac.getInstance("HmacSHA256");
            mac.init(new SecretKeySpec(dingConfig.getSecret().getBytes("UTF-8"), "HmacSHA256"));
            byte[] signData = mac.doFinal(stringToSign.getBytes("UTF-8"));
            String sign = URLEncoder.encode(new String(Base64.encodeBase64(signData)), "UTF-8");

            String serverUrl = "https://oapi.dingtalk.com/robot/send?access_token=" + dingConfig.getAccessToken() + "&timestamp=" + timestamp + "&sign=" + sign;

            DingTalkClient client = new DefaultDingTalkClient(serverUrl);
            OapiRobotSendRequest request = new OapiRobotSendRequest();
            request.setMsgtype("text");
            OapiRobotSendRequest.Text text = new OapiRobotSendRequest.Text();
            text.setContent("告警");
            request.setText(text);
            OapiRobotSendRequest.At at = new OapiRobotSendRequest.At();
            at.setIsAtAll(true);
            request.setAt(at);
            request.setMsgtype("link");
            OapiRobotSendRequest.Link link = new OapiRobotSendRequest.Link();
            link.setMessageUrl("https://www.dingtalk.com/");
            link.setPicUrl("");
            request.setLink(link);
            request.setMsgtype("markdown");
            request.setMarkdown(markdown);
            OapiRobotSendResponse response = client.execute(request);
        } catch (Exception e) {
            log.error("钉钉发送群消息异常:" + e.getMessage());
        }
    }


}

4. 需要直接注入调用即可

                //推送钉钉
                OapiRobotSendRequest.Markdown markdown = new OapiRobotSendRequest.Markdown();
                markdown.setTitle("物料车电量告警");
                StringBuilder stringBuilder = new StringBuilder();
                stringBuilder
                        .append("### **警告** \n\n")
                        .append("物料车电量告警\n\n")
                        .append("当前有"+size+"辆物料车电池电量低于"+batteryLevel+"%"+",请及时充电\n\n")
                        .append("告警时间:")
                        .append(DateUtils.getTime());
                markdown.setText(stringBuilder.toString());
                dingMessageService.sendCrowdMessage(markdown);

附:yml文件中 secret 和 accessToken 获取方法

首先拉人组个群,点击群设置,添加小机器人

然后选择自定义

选择加签,里面的值就是 secret

然后点击完成,出现下图,access_token 后面的就是 accessToken 的值

### 钉钉消息推送 API 配置教程 钉钉消息推送功能是企业内部通信的重要组成部分,通过配置和实现相关 API,可以实现高效的消息通知机制。以下是钉钉消息推送的实现方式和配置方法: #### 1. 配置钉钉开发者平台应用 在钉钉开发者平台上创建一个企业内部应用,并获取以下关键参数: - `appkey`:应用的唯一标识。 - `appsecret`:用于生成签名的密钥。 - `agentid`:应用的 ID,用于指定消息发送的应用。 这些参数需要在项目的配置文件中进行设置[^2]。例如,在 `application.yml` 文件中添加如下内容: ```yaml dingtalk: appkey: dingvxxxx appsecret: 0uyedo8zroBNxxxxxxx agentid: 38xxxxxxx ``` #### 2. 获取 Access Token 钉钉 API 的调用需要使用 `access_token`,该令牌可以通过以下接口获取: ``` GET https://oapi.dingtalk.com/gettoken?appkey=your_appkey&appsecret=your_appsecret ``` 返回结果中包含 `access_token`,有效期为 7200 秒。建议在项目中缓存该令牌,并在过期前重新获取[^1]。 #### 3. 消息推送接口 钉钉提供了多种消息类型(如文本、Markdown、链接等),通过以下接口实现消息推送: ``` POST https://oapi.dingtalk.com/topapi/message/corpconversation/asyncsend_v2?access_token=your_access_token ``` 请求体示例(Markdown 消息): ```json { "agent_id": "3828659278", "userid_list": "钉钉用户ID", "msg": { "msgtype": "markdown", "markdown": { "title": "测试富文本消息", "text": "### 测试标题\n- 项目1\n- 项目2\n\n**加粗文本**" } } } ``` 上述请求中,`agent_id` 是应用的 ID,`userid_list` 是接收消息的用户列表,`msg` 定义了消息的内容和类型。 #### 4. 后端实现步骤 以下是后端实现的主要步骤: ##### 4.1 创建模块 创建一个新的模块(如 `ruoyi-dingtalk`),并在 `pom.xml` 中添加钉钉开放平台 SDK 和其他依赖项。 ##### 4.2 配置文件 在 `application.yml` 中配置钉钉的相关参数,如上文所示。 ##### 4.3 实体类和 DTO 定义消息发送所需的实体类和数据传输对象(DTO)。例如: - `DingTalkMessageDTO`:通用消息发送请求。 - `TextMessageDTO`:文本消息。 - `MarkdownMessageDTO`:Markdown 消息。 ##### 4.4 核心服务类 实现消息发送的核心逻辑。可以参考责任链设计模式,以便支持不同的业务场景(如发送消息或撤回消息)。例如: ```java public class DingTalkService { private static final String SEND_URL = "https://oapi.dingtalk.com/topapi/message/corpconversation/asyncsend_v2?access_token="; public void sendMessage(DingTalkMessageDTO messageDTO, String accessToken) throws Exception { String url = SEND_URL + accessToken; String requestBody = JSON.toJSONString(messageDTO); OkHttpClient client = new OkHttpClient(); RequestBody body = RequestBody.create(requestBody, MediaType.parse("application/json")); Request request = new Request.Builder() .url(url) .post(body) .build(); try (Response response = client.newCall(request).execute()) { if (!response.isSuccessful()) { throw new IOException("Unexpected code " + response); } System.out.println(response.body().string()); } } } ``` #### 5. 消息撤回功能 如果需要实现消息撤回功能,可以在 `SendRequest` 类中增加 `code` 参数,用于区分发送和撤回操作[^3]。例如: ```java @Data @Accessors(chain = true) @AllArgsConstructor @NoArgsConstructor @Builder public class SendRequest { private String code; // "send" 或 "recall" private Long messageTemplateId; private MessageParam messageParam; } ``` ### 注意事项 - 确保 `access_token` 的安全性,避免泄露。 - 根据实际需求选择合适的消息类型(如文本、Markdown、链接等)。 - 调试时可以使用钉钉提供的在线工具验证请求是否正确。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值