啊鑫
2024-11-18 16bbd0a2e072bafea1dc254fbbcf86768fb3ea48
钉钉推送消息,通过机器人发送到个人
已添加1个文件
已修改5个文件
156 ■■■■ 文件已修改
src/main/java/com/gs/dingtalk/controller/KMController.java 32 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/com/gs/dingtalk/service/SimpleExample.java 72 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/com/gs/dingtalk/service/impl/SendDingtalkServiceImpl.java 27 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/com/gs/dingtalk/service/impl/SendMessageServiceImpl.java 8 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/com/gs/dingtalk/task/ScheduledTasks.java 12 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/test/java/com/gs/dingtalk/DeviceReceivingApplicationTests.java 5 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/com/gs/dingtalk/controller/KMController.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,32 @@
package com.gs.dingtalk.controller;
import com.gs.dingtalk.config.ResultMessage;
import com.gs.dingtalk.service.SendDingtalkService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("Numerical")
@RequiredArgsConstructor
@CrossOrigin(origins = "*") //跨域请求
public class KMController {
    private final SendDingtalkService sendDingtalkService;
    @PostMapping("/chatSendMessage")
    public ResultMessage setCode() {
        try {
            sendDingtalkService.chatSendMessage();
            return ResultMessage.ok();
        } catch (Exception e) {
            return ResultMessage.error(e);
        }
    }
}
src/main/java/com/gs/dingtalk/service/SimpleExample.java
@@ -1,18 +1,22 @@
package com.gs.dingtalk.service;
import cn.hutool.core.util.StrUtil;
import com.aliyun.dingtalkoauth2_1_0.Client;
import com.aliyun.dingtalkoauth2_1_0.models.GetAccessTokenRequest;
import com.aliyun.dingtalkoauth2_1_0.models.GetAccessTokenResponse;
import com.aliyun.dingtalkrobot_1_0.models.BatchSendOTOHeaders;
import com.aliyun.dingtalkrobot_1_0.models.BatchSendOTORequest;
import com.aliyun.dingtalkrobot_1_0.models.BatchSendOTOResponse;
import com.aliyun.dingtalkrobot_1_0.models.BatchSendOTOResponseBody;
import com.aliyun.tea.TeaException;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.Common;
import com.aliyun.teautil.models.RuntimeOptions;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiMessageCorpconversationAsyncsendV2Request;
import com.dingtalk.api.request.OapiRobotSendRequest;
import com.dingtalk.api.request.OapiV2UserGetbymobileRequest;
import com.dingtalk.api.response.OapiMessageCorpconversationAsyncsendV2Response;
import com.dingtalk.api.response.OapiRobotSendResponse;
import com.dingtalk.api.response.OapiV2UserGetbymobileResponse;
import com.google.gson.Gson;
@@ -32,6 +36,8 @@
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.List;
/**
@@ -100,27 +106,53 @@
    /**
     * å‘送消息
     */
    public DingTalkMessage sendMessage(String userIdList, String message) throws Exception {
    public DingTalkMessage sendMessage(String userIdListStr, String message) throws Exception {
        if (!StrUtil.isNotEmpty(userIdListStr)) {
            return new DingTalkMessage(1, 0L, "null");
        }
        String[] strArray = userIdListStr.split(",");
        List<String> userIdList = Arrays.asList(strArray);
        String accessToken = getAccessToken();
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/message/corpconversation/asyncsend_v2");
        OapiMessageCorpconversationAsyncsendV2Request request = new OapiMessageCorpconversationAsyncsendV2Request();
        request.setAgentId(DataAcquisitionConfiguration.AGENT_ID);
        request.setUseridList(userIdList);
        request.setToAllUser(false);
        com.aliyun.dingtalkrobot_1_0.Client client1 = createClient1();
        BatchSendOTOHeaders batchSendOTOHeaders = new BatchSendOTOHeaders();
        batchSendOTOHeaders.xAcsDingtalkAccessToken = accessToken;
        BatchSendOTORequest batchSendOTORequest = new BatchSendOTORequest()
                .setRobotCode("ding7n8fldhylh2rt2l2")
                .setUserIds(userIdList)
                .setMsgKey("sampleText")
                .setMsgParam("{\"content\": \"" + message + "\"}");
        OapiMessageCorpconversationAsyncsendV2Request.Msg msg = new OapiMessageCorpconversationAsyncsendV2Request.Msg();
        msg.setMsgtype("text");
        msg.setText(new OapiMessageCorpconversationAsyncsendV2Request.Text());
        msg.getText().setContent(message);
        request.setMsg(msg);
        try {
            BatchSendOTOResponse batchSendOTOResponse = client1.batchSendOTOWithOptions(batchSendOTORequest, batchSendOTOHeaders, new RuntimeOptions());
        OapiMessageCorpconversationAsyncsendV2Response rsp = client.execute(request, accessToken);
            BatchSendOTOResponseBody body = batchSendOTOResponse.getBody();
            if (StrUtil.isNotEmpty(body.getProcessQueryKey())) {
                return new DingTalkMessage(0, 0L, "null");
            }
        Gson gson = new Gson();
        } catch (TeaException err) {
            if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                System.out.println(err.code);
                System.out.println(err.message);
        return gson.fromJson(rsp.getBody(), DingTalkMessage.class);
                System.out.println(err.accessDeniedDetail.toString());
            }
        } catch (Exception _err) {
            TeaException err = new TeaException(_err.getMessage(), _err);
            if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                System.out.println(err.code);
                System.out.println(err.message);
            }
        }
        return new DingTalkMessage(1, 0L, "null");
        //return gson.fromJson(rsp.getBody(), DingTalkMessage.class);
    }
    /**
@@ -155,6 +187,13 @@
        return null;
    }
    public static com.aliyun.dingtalkrobot_1_0.Client createClient1() throws Exception {
        Config config = new Config();
        config.protocol = "https";
        config.regionId = "central";
        return new com.aliyun.dingtalkrobot_1_0.Client(config);
    }
    /**
     * ä½¿ç”¨ Token åˆå§‹åŒ–账号Client
     *
@@ -168,6 +207,7 @@
        return new Client(config);
    }
    public OapiV2UserGetbymobileResponse getOapiV2UserGetbymobileResponse(SendDingtalk s, String accessToken) {
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/getbymobile");
        OapiV2UserGetbymobileRequest req = new OapiV2UserGetbymobileRequest();
src/main/java/com/gs/dingtalk/service/impl/SendDingtalkServiceImpl.java
@@ -19,6 +19,7 @@
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
@@ -78,7 +79,7 @@
        List<SendDingtalk> list = list(wrapper);
        getMessage(list);
        getMessage(list, 5);
    }
    @Override
@@ -88,7 +89,7 @@
        List<SendDingtalk> list = list(wrapper);
        getMessage(list);
        getMessage(list, 30);
    }
    @Override
@@ -117,18 +118,26 @@
        });
    }
    private void getMessage(List<SendDingtalk> list) {
    private void getMessage(List<SendDingtalk> list, int Minutes) {
        List<SendMessage> sendMessageList = sendMessageService.getSendMessageList();
        sendMessageList.forEach(s -> {
            String userIdList = list.stream()
                    .filter(dingtalk -> {
                        String[] purviews = dingtalk.getPurview().split(",");
                        return Arrays.asList(purviews).contains(s.getProcNo());
                    }).map(SendDingtalk::getUserId).collect(Collectors.joining(","));
            // èŽ·å–å½“å‰æ—¶é—´çš„ LocalDateTime,忽略秒
            LocalDateTime now = LocalDateTime.now().withSecond(0).withNano(0);
            //钉钉的规则限制 ç»™åŒä¸€å‘˜å·¥ä¸€å¤©åªèƒ½å‘送一条内容相同的消息通知。
            // æ¯”较时间,判断 sendDate æ˜¯å¦å¤§äºŽå½“前时间五分钟
            boolean isGreaterThanFiveMinutes = s.getSendDate().plusMinutes(Minutes).isBefore(now);
            if (!isGreaterThanFiveMinutes) {
                return;
            }
            String userIdList = list.stream().filter(dingtalk -> {
                String[] purviews = dingtalk.getPurview().split(",");
                return Arrays.asList(purviews).contains(s.getProcNo());
            }).map(SendDingtalk::getUserId).collect(Collectors.joining(","));
            String message = s.getLineName() + s.getProcName() + ",请尽快处理";
            DingTalkMessage dingTalkMessage = null;
src/main/java/com/gs/dingtalk/service/impl/SendMessageServiceImpl.java
@@ -9,7 +9,6 @@
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.List;
@Service
@@ -22,11 +21,6 @@
    public List<SendMessage> getSendMessageList() {
        LambdaQueryWrapper<SendMessage> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SendMessage::getFstatus, "待处理");
        List<SendMessage> list = list(queryWrapper);
        List<SendMessage> result = new ArrayList<>();
        result.add(list.get(0));
        return result;
        return list(queryWrapper);
    }
}
src/main/java/com/gs/dingtalk/task/ScheduledTasks.java
@@ -10,7 +10,7 @@
@RequiredArgsConstructor
public class ScheduledTasks {
    private SendDingtalkService sendDingtalkService;
    private final SendDingtalkService sendDingtalkService;
    /**
     * æ¯äº”分钟执行一次
@@ -21,18 +21,12 @@
     * @description TODO
     * @date 2024/9/27 21:48
     */
    @Scheduled(cron = "0 0/5 * * * ?")
    @Scheduled(cron = "0 0/2 * * * ?")
    public void getDeviceRealTimeData() throws Exception {
        sendDingtalkService.sendDingTalkFiveMinute();
    }
    //0/5 * * * * ? *
    @Scheduled(cron = "0/5 * * * * ?")
    public void chatSendMessage() throws Exception {
        sendDingtalkService.chatSendMessage();
    }
    @Scheduled(cron = "0 0/30 * * * ?")
    @Scheduled(cron = "0 0/3 * * * ?")
    public void sendDingTalkthirtyMinute() throws Exception {
        sendDingtalkService.sendDingTalkthirtyMinute();
    }
src/test/java/com/gs/dingtalk/DeviceReceivingApplicationTests.java
@@ -50,6 +50,11 @@
        sendDingtalkService.sendDingTalkFiveMinute();
    }
    @Test
    void sendDingTalkthirtyMinute() throws Exception {
        sendDingtalkService.sendDingTalkthirtyMinute();
    }
    //chatSendMessage
    @Test
    void chatSendMessage() throws Exception {