Java_钉钉发送私聊消息

Posted 飞廉灬少将

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java_钉钉发送私聊消息相关的知识,希望对你有一定的参考价值。

前言

随着公司体量的越来越庞大,很多时候需要用到部门协同,所以钉钉(DingTalk)应运而生。
钉钉(DingTalk)是阿里巴巴集团打造的企业级智能移动办公平台,引领未来新一代工作方式,将陪伴每一个企业成长,是数字经济时代的企业组织协同办公和应用开发平台,是新生产力工具。
有时候钉钉需要通过定时任务去给某一个人发送私聊消息,当然群聊消息也可以,只不过群消息的前提是先建群,然后在群里添加钉钉机器人,并且工作群一旦多了,消息看的也就没那么及时,所以群消息在某一些场景下没那么便捷,或者可以说没有那么高效。

一、文档地址

Api文档地址:批量发送单聊消息

二、使用步骤

1.创建企业内部应用

2、获取应用AppKey和AppSecret

3.创建机器人

4.开启机器人

5.发布机器人

6.开启应用权限

7.引入JAR包

		<!-- 钉钉对接机器人 -->
        <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>dingtalk</artifactId>
            <version>1.5.24</version>
        </dependency>

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

三、示例代码

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.dingtalkrobot_1_0.Client;
import com.aliyun.dingtalkrobot_1_0.models.BatchSendOTOHeaders;
import com.aliyun.dingtalkrobot_1_0.models.BatchSendOTORequest;
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.OapiGettokenRequest;
import com.dingtalk.api.request.OapiV2DepartmentListsubRequest;
import com.dingtalk.api.request.OapiV2UserGetbymobileRequest;
import com.dingtalk.api.response.OapiGettokenResponse;
import com.dingtalk.api.response.OapiV2DepartmentListsubResponse;
import com.dingtalk.api.response.OapiV2UserGetbymobileResponse;
import com.smallrig.common.response.ding.DeptInfoResp;
import com.taobao.api.ApiException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


/**
 * @author zhushuang
 * @program: nakadai
 * @description: 钉钉发送私聊消息
 * @time 2023/1/13
 */
@Component
@Slf4j
public class DingSendPrivateChatMsgService 


    // 企业凭证,两小时一更新
    private static String enterpriseToken = "";
    // 应用凭证
    private static String appkey = "你的应用AppKey";
    private static String appsecret = "你的应用AppSecret";

    // 获取token,每两小时失效
    public static void getToken() 
        try 
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken");
            OapiGettokenRequest req = new OapiGettokenRequest();
            req.setAppkey(appkey);
            req.setAppsecret(appsecret);
            req.setHttpMethod("GET");
            OapiGettokenResponse rsp = client.execute(req);
            log.info("token:" + rsp.getBody());
            JSONObject json = JSON.parseObject(rsp.getBody());
            enterpriseToken = json.getString("access_token");
         catch (ApiException e) 
            e.printStackTrace();
        
    

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

    /**
     * 发送钉钉消息
     *
     * @param dingUserId 钉钉用户id
     * @param content    发送消息内容
     * @return void
     */
    public static void createDingNotify(String dingUserId, String content) throws Exception 
        if (StringUtils.isBlank(enterpriseToken)) 
            getToken();
        
        Client client = createClient();
        BatchSendOTOHeaders batchSendOTOHeaders = new BatchSendOTOHeaders();
        batchSendOTOHeaders.xAcsDingtalkAccessToken = enterpriseToken;
        BatchSendOTORequest batchSendOTORequest = new BatchSendOTORequest()
                .setRobotCode(appkey)//机器人appkey
                .setUserIds(Arrays.asList(dingUserId))
                .setMsgKey("officialTextMsg")
                .setMsgParam(" \\"content\\": \\"" + content + "\\" ");
        try 
            client.batchSendOTOWithOptions(batchSendOTORequest, batchSendOTOHeaders, new RuntimeOptions());
         catch (TeaException err) 
            if (!Common.empty(err.code) && !Common.empty(err.message)) 
                // err 中含有 code 和 message 属性,可帮助开发定位问题
                log.error(err.code + ":" + err.message);
                // 企业凭证enterpriseToken不合法导致出错时获取新企业凭证并重试
                if (err.code.equals("InvalidAuthentication")) 
                    getToken();
                    createDingNotify(dingUserId, content);
                
            
         catch (Exception e) 
            TeaException err = new TeaException(e.getMessage(), e);
            if (!Common.empty(err.code) && !Common.empty(err.message)) 
                // err中含有code和message 属性,可帮助开发定位问题
                log.error(err.code + ":" + err.message);
            

        
    

    /**
     * 发送钉钉消息
     *
     * @param phone 用户手机号
     * @return void
     */
    public static String getDingdingUserIdByPhone(String phone) 
        try 
            if (StringUtils.isBlank(enterpriseToken)) 
                getToken();
            
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/getbymobile");
            OapiV2UserGetbymobileRequest req = new OapiV2UserGetbymobileRequest();
            req.setMobile(phone);
            OapiV2UserGetbymobileResponse rsp = client.execute(req, enterpriseToken);
            if (rsp != null) 
                OapiV2UserGetbymobileResponse.UserGetByMobileResponse result = rsp.getResult();
                return result == null ? null : result.getUserid();
            
         catch (ApiException e) 
            log.error(e.getErrMsg(), e);
        
        return null;
    


四、成功示例


这里不在将调用代码放出来了,毕竟。。。调用大家都会

原创不易,望一键三连 (^ _ ^)

以上是关于Java_钉钉发送私聊消息的主要内容,如果未能解决你的问题,请参考以下文章

钉钉消息监控

钉钉微应用发送消息

发送钉钉消息

SQL执行WebService

通知神器——java调用钉钉群自定义机器人

钉钉发送工作通知消息