0
点赞
收藏
分享

微信扫一扫

Java实现钉钉企业内部单聊机器人批量发送单聊消息

清冷的蓝天天 2022-02-28 阅读 132
java后端

 Java集成钉钉实现企业内部单聊机器人推送功能。

 钉钉开放文档地址:如何接入单聊机器人

/**
 * @创建人 果
 * @描述:批量发送单聊消息
 */
@RestController
@RequestMapping(value = "/robots")
@Api(description = "机器人单聊消息")
@RequiredArgsConstructor
@Slf4j
public class RobotChatController {

    /**
     * 使用 Token 初始化账号Client
     *
     * @return Client
     * @throws Exception
     */
    public static com.aliyun.dingtalkrobot_1_0.Client createClient() throws Exception {
        Config config = new Config();
        config.protocol = "https";
        config.regionId = "central";
        return new com.aliyun.dingtalkrobot_1_0.Client(config);
    }

    @ApiOperation("批量发送单聊消息")
    @PostMapping("/sendBatch")
    public void helloRobots(RobotDTO robotDTO) throws Exception {
        String accessToken = NailUtil.getToken(Constant.ROBOT_DING_APPKEY, Constant.ROBOT_DING_APPSECRET);
        List<String > userIds = new ArrayList<>();
        for (Integer phone : robotDTO.getPhoneList()) {
            //得到userId
            String userId = NailUtil.getUserId(String.valueOf(phone), accessToken);
            userIds.add(userId);
        }
        com.aliyun.dingtalkrobot_1_0.Client client = RobotChatController.createClient();
        BatchSendOTOHeaders batchSendOTOHeaders = new BatchSendOTOHeaders();
        batchSendOTOHeaders.xAcsDingtalkAccessToken = accessToken;
        BatchSendOTORequest batchSendOTORequest = new BatchSendOTORequest()
                .setRobotCode(Constant.ROBOT_DING_APPKEY)
                .setUserIds(userIds)
                .setMsgKey("sampleMarkdown")
                .setMsgParam("{     \"title\": \"测试标题\",     \"text\": \"##  这是一条测试消息\"  }");
        try {
            client.batchSendOTOWithOptions(batchSendOTORequest, batchSendOTOHeaders, new RuntimeOptions());
        } catch (TeaException err) {
            if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                // err 中含有 code 和 message 属性,可帮助开发定位问题
                System.out.println("code:" + err.getCode() + "message:" + err.getMessage());
            }

        } 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)) {
                // err 中含有 code 和 message 属性,可帮助开发定位问题
                System.out.println("code:" + err.getCode() + "message:" + err.getMessage());
            }

        }
    }
}

举报

相关推荐

0 条评论