1. 创建钉钉群机器人
通过钉钉PC客户端进入,选择钉钉群,依次进入:“群设置”/“智能群助手”/“添加机器人”,之后选择“自定义”方式,通过Webhook接入自定义服务。
说明:此处安全设置以“自定义关键词”为例,设定后,只有包含关键词的消息内容才会被正常发送。
2. 获取机器人令牌
设置群机器人成功后,依次进入:“群设置”/“智能群助手”,之后选择自定义的机器人,即可查看到Webook地址信息,其中就包含令牌参数信息(https://oapi.dingtalk.com/robot/send?access_token=31f7005ecd6ec1775d085b4cbdc18a4639d999063a9ff3ead38d245b7e7xxxxx)。
3. 应用程序集成
通过Webhook提供的${access_token}可通过多种方式,向钉钉群发送消息,包括:HttpClient、OkHttp、Dingtalk SDK等。
应用工程依赖:
<?xml version="1.0" encoding="UTF-8"?><project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>dingtalk-webhook-demo</groupId><artifactId>org.polaris.dingtalk.webhook</artifactId><version>1.0.0</version><properties><!-- 操作json格式数据的相应的框架 --><fastjson.version>1.2.29</fastjson.version><!-- 日志框架log4j,以及升级版 logback对应的版本号 --><logback.version>1.1.11</logback.version><slf4j.version>1.7.25</slf4j.version></properties><repositories><repository><id>sonatype-nexus-staging</id><name>Sonatype Nexus Staging</name><url>https://oss.sonatype.org/service/local/staging/deploy/maven2/</url><releases><enabled>true</enabled></releases><snapshots><enabled>true</enabled></snapshots></repository></repositories><dependencies><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>${fastjson.version}</version></dependency><dependency><groupId>com.squareup.okhttp</groupId><artifactId>okhttp</artifactId><version>2.7.5</version></dependency><dependency><groupId>com.aliyun</groupId><artifactId>alibaba-dingtalk-service-sdk</artifactId><version>1.0.1</version></dependency><dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpclient</artifactId><version>4.5.3</version><exclusions><exclusion><artifactId>commons-logging</artifactId><groupId>commons-logging</groupId></exclusion></exclusions></dependency><!-- 日志jar包依赖 --><dependency><groupId>org.slf4j</groupId><artifactId>slf4j-api</artifactId><version>${slf4j.version}</version></dependency><dependency><groupId>ch.qos.logback</groupId><artifactId>logback-classic</artifactId><version>${logback.version}</version><scope>${scope}</scope><exclusions><exclusion><artifactId>slf4j-api</artifactId><groupId>org.slf4j</groupId></exclusion></exclusions></dependency><dependency><groupId>ch.qos.logback</groupId><artifactId>logback-core</artifactId><version>${logback.version}</version><scope>${scope}</scope></dependency></dependencies></project>
1. HttpClient
public class SendMsgToDingtalkHttpClient {private static final Logger log = LoggerFactory.getLogger(SendMsgToDingtalkHttpClient.class);public static final String WEBHOOK_TOKEN = "https://oapi.dingtalk.com/robot/send?access_token=31f7005ecd6ec1775d085b4cbdc18a4639d999063a9ff3ead38d245b7xxxxx";public static void main(String args[]) throws IOException {// 配置了Webhook机器人关键字“告警测试”,则消息中需要携带,否则无法发出// 更多配置请参考:https://ding-doc.dingtalk.com/doc#/serverapi2/qf2nxqHttpClient httpclient = HttpClients.createDefault();HttpPost httppost = new HttpPost(WEBHOOK_TOKEN);httppost.addHeader("Content-Type", "application/json; charset=utf-8");// 构建一个json格式字符串textMsg,其内容是接收方需要的参数和消息内容String textMsg = "{\"msgtype\":\"text\",\"text\":{\"content\":\"告警测试:This is a warning test.\"},\"at\":{\"atMobiles\":[\"13632608950\"],\"isAtAll\":false}}";StringEntity se = new StringEntity(textMsg, "utf-8");httppost.setEntity(se);HttpResponse response = httpclient.execute(httppost);if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {String result = EntityUtils.toString(response.getEntity(), "utf-8");log.info(result);} else {log.error("error code:" + response.getStatusLine().getStatusCode());}}}
2. OkHttp
public class SendMsgToDingtalkOkHttp {private static final Logger log = LoggerFactory.getLogger(SendMsgToDingtalkOkHttp.class);private static final MediaType JSON = MediaType.parse("application/json;charset=utf-8");public static final String ALERT_MSG_ROBOT_ID = "https://oapi.dingtalk.com/robot/send?access_token=31f7005ecd6ec1775d085b4cbdc18a4639d999063a9ff3ead38d245b7e7xxxxx";public static void main(String[] args) {// 配置了Webhook机器人关键字“告警测试”,则消息中需要携带,否则无法发出// 更多配置请参考:https://ding-doc.dingtalk.com/doc#/serverapi2/qf2nxqString msg = String.format("告警测试:%s", "This is a warning test.");if (sendMsg(ALERT_MSG_ROBOT_ID, msg)) {log.info("发送消息到钉钉成功!");}}/*** 发送机器人消息*/public static boolean sendMsg(String robotId, String msg) {JSONObject text = new JSONObject();text.put("content", msg);JSONObject object = new JSONObject();object.put("msgtype", "text");object.put("text", text);OkHttpClient okHttpClient = new OkHttpClient();RequestBody requestBody = RequestBody.create(JSON, object.toJSONString());Request request = new Request.Builder().url(robotId).post(requestBody).build();try {Response response = okHttpClient.newCall(request).execute();return response.isSuccessful();} catch (Exception e) {log.error(String.format("发送Webhook[%s,%s]失败:" + e.getMessage(), robotId, msg));return false;}}}
3. Dingtalk SDK
public class SendMsgToDingtalkSDK {private static final Logger log = LoggerFactory.getLogger(SendMsgToDingtalkSDK.class);private static final MediaType JSON = MediaType.parse("application/json;charset=utf-8");public static final String ALERT_MSG_ROBOT_ID = "https://oapi.dingtalk.com/robot/send?access_token=31f7005ecd6ec1775d085b4cbdc18a4639d999063a9ff3ead38d245b7e7xxxxx";public static void main(String[] args) throws ApiException {// 配置了Webhook机器人关键字“告警测试”,则消息中需要携带,否则无法发出// 更多配置请参考:https://ding-doc.dingtalk.com/doc#/serverapi2/qf2nxq// 图片消息需要确保图片路径可访问String msg = "#### xxx大数据平台 @13632608950\n" +"> 内存使用率:84%\n\n" +"> \n" +"> ###### 10点20分发布 [告警测试](https://www.seniverse.com/) \n";if (sendMsg(ALERT_MSG_ROBOT_ID, msg)) {log.info("发送消息到钉钉成功!");}}/*** 发送机器人消息*/public static boolean sendMsg(String robotId, String msg) throws ApiException {DingTalkClient client = new DefaultDingTalkClient(robotId);OapiRobotSendRequest request = new OapiRobotSendRequest();request.setMsgtype("markdown");OapiRobotSendRequest.Markdown markdown = new OapiRobotSendRequest.Markdown();markdown.setTitle("告警测试");markdown.setText(msg);request.setMarkdown(markdown);OapiRobotSendResponse response = client.execute(request);return response.isSuccess();}}
