1. 创建钉钉群机器人

通过钉钉PC客户端进入,选择钉钉群,依次进入:“群设置”/“智能群助手”/“添加机器人”,之后选择“自定义”方式,通过Webhook接入自定义服务。
image.png
说明:此处安全设置以“自定义关键词”为例,设定后,只有包含关键词的消息内容才会被正常发送。

2. 获取机器人令牌

设置群机器人成功后,依次进入:“群设置”/“智能群助手”,之后选择自定义的机器人,即可查看到Webook地址信息,其中就包含令牌参数信息(https://oapi.dingtalk.com/robot/send?access_token=31f7005ecd6ec1775d085b4cbdc18a4639d999063a9ff3ead38d245b7e7xxxxx)。
image.png

3. 应用程序集成

通过Webhook提供的${access_token}可通过多种方式,向钉钉群发送消息,包括:HttpClient、OkHttp、Dingtalk SDK等。
应用工程依赖:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5. <modelVersion>4.0.0</modelVersion>
  6. <groupId>dingtalk-webhook-demo</groupId>
  7. <artifactId>org.polaris.dingtalk.webhook</artifactId>
  8. <version>1.0.0</version>
  9. <properties>
  10. <!-- 操作json格式数据的相应的框架 -->
  11. <fastjson.version>1.2.29</fastjson.version>
  12. <!-- 日志框架log4j,以及升级版 logback对应的版本号 -->
  13. <logback.version>1.1.11</logback.version>
  14. <slf4j.version>1.7.25</slf4j.version>
  15. </properties>
  16. <repositories>
  17. <repository>
  18. <id>sonatype-nexus-staging</id>
  19. <name>Sonatype Nexus Staging</name>
  20. <url>https://oss.sonatype.org/service/local/staging/deploy/maven2/</url>
  21. <releases>
  22. <enabled>true</enabled>
  23. </releases>
  24. <snapshots>
  25. <enabled>true</enabled>
  26. </snapshots>
  27. </repository>
  28. </repositories>
  29. <dependencies>
  30. <dependency>
  31. <groupId>com.alibaba</groupId>
  32. <artifactId>fastjson</artifactId>
  33. <version>${fastjson.version}</version>
  34. </dependency>
  35. <dependency>
  36. <groupId>com.squareup.okhttp</groupId>
  37. <artifactId>okhttp</artifactId>
  38. <version>2.7.5</version>
  39. </dependency>
  40. <dependency>
  41. <groupId>com.aliyun</groupId>
  42. <artifactId>alibaba-dingtalk-service-sdk</artifactId>
  43. <version>1.0.1</version>
  44. </dependency>
  45. <dependency>
  46. <groupId>org.apache.httpcomponents</groupId>
  47. <artifactId>httpclient</artifactId>
  48. <version>4.5.3</version>
  49. <exclusions>
  50. <exclusion>
  51. <artifactId>commons-logging</artifactId>
  52. <groupId>commons-logging</groupId>
  53. </exclusion>
  54. </exclusions>
  55. </dependency>
  56. <!-- 日志jar包依赖 -->
  57. <dependency>
  58. <groupId>org.slf4j</groupId>
  59. <artifactId>slf4j-api</artifactId>
  60. <version>${slf4j.version}</version>
  61. </dependency>
  62. <dependency>
  63. <groupId>ch.qos.logback</groupId>
  64. <artifactId>logback-classic</artifactId>
  65. <version>${logback.version}</version>
  66. <scope>${scope}</scope>
  67. <exclusions>
  68. <exclusion>
  69. <artifactId>slf4j-api</artifactId>
  70. <groupId>org.slf4j</groupId>
  71. </exclusion>
  72. </exclusions>
  73. </dependency>
  74. <dependency>
  75. <groupId>ch.qos.logback</groupId>
  76. <artifactId>logback-core</artifactId>
  77. <version>${logback.version}</version>
  78. <scope>${scope}</scope>
  79. </dependency>
  80. </dependencies>
  81. </project>

1. HttpClient

  1. public class SendMsgToDingtalkHttpClient {
  2. private static final Logger log = LoggerFactory.getLogger(SendMsgToDingtalkHttpClient.class);
  3. public static final String WEBHOOK_TOKEN = "https://oapi.dingtalk.com/robot/send?access_token=31f7005ecd6ec1775d085b4cbdc18a4639d999063a9ff3ead38d245b7xxxxx";
  4. public static void main(String args[]) throws IOException {
  5. // 配置了Webhook机器人关键字“告警测试”,则消息中需要携带,否则无法发出
  6. // 更多配置请参考:https://ding-doc.dingtalk.com/doc#/serverapi2/qf2nxq
  7. HttpClient httpclient = HttpClients.createDefault();
  8. HttpPost httppost = new HttpPost(WEBHOOK_TOKEN);
  9. httppost.addHeader("Content-Type", "application/json; charset=utf-8");
  10. // 构建一个json格式字符串textMsg,其内容是接收方需要的参数和消息内容
  11. String textMsg = "{\"msgtype\":\"text\",\"text\":{\"content\":\"告警测试:This is a warning test.\"},\"at\":{\"atMobiles\":[\"13632608950\"],\"isAtAll\":false}}";
  12. StringEntity se = new StringEntity(textMsg, "utf-8");
  13. httppost.setEntity(se);
  14. HttpResponse response = httpclient.execute(httppost);
  15. if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
  16. String result = EntityUtils.toString(response.getEntity(), "utf-8");
  17. log.info(result);
  18. } else {
  19. log.error("error code:" + response.getStatusLine().getStatusCode());
  20. }
  21. }
  22. }

2. OkHttp

  1. public class SendMsgToDingtalkOkHttp {
  2. private static final Logger log = LoggerFactory.getLogger(SendMsgToDingtalkOkHttp.class);
  3. private static final MediaType JSON = MediaType.parse("application/json;charset=utf-8");
  4. public static final String ALERT_MSG_ROBOT_ID = "https://oapi.dingtalk.com/robot/send?access_token=31f7005ecd6ec1775d085b4cbdc18a4639d999063a9ff3ead38d245b7e7xxxxx";
  5. public static void main(String[] args) {
  6. // 配置了Webhook机器人关键字“告警测试”,则消息中需要携带,否则无法发出
  7. // 更多配置请参考:https://ding-doc.dingtalk.com/doc#/serverapi2/qf2nxq
  8. String msg = String.format("告警测试:%s", "This is a warning test.");
  9. if (sendMsg(ALERT_MSG_ROBOT_ID, msg)) {
  10. log.info("发送消息到钉钉成功!");
  11. }
  12. }
  13. /**
  14. * 发送机器人消息
  15. */
  16. public static boolean sendMsg(String robotId, String msg) {
  17. JSONObject text = new JSONObject();
  18. text.put("content", msg);
  19. JSONObject object = new JSONObject();
  20. object.put("msgtype", "text");
  21. object.put("text", text);
  22. OkHttpClient okHttpClient = new OkHttpClient();
  23. RequestBody requestBody = RequestBody.create(JSON, object.toJSONString());
  24. Request request = new Request.Builder().url(robotId).post(requestBody).build();
  25. try {
  26. Response response = okHttpClient.newCall(request).execute();
  27. return response.isSuccessful();
  28. } catch (Exception e) {
  29. log.error(String.format("发送Webhook[%s,%s]失败:" + e.getMessage(), robotId, msg));
  30. return false;
  31. }
  32. }
  33. }

3. Dingtalk SDK

  1. public class SendMsgToDingtalkSDK {
  2. private static final Logger log = LoggerFactory.getLogger(SendMsgToDingtalkSDK.class);
  3. private static final MediaType JSON = MediaType.parse("application/json;charset=utf-8");
  4. public static final String ALERT_MSG_ROBOT_ID = "https://oapi.dingtalk.com/robot/send?access_token=31f7005ecd6ec1775d085b4cbdc18a4639d999063a9ff3ead38d245b7e7xxxxx";
  5. public static void main(String[] args) throws ApiException {
  6. // 配置了Webhook机器人关键字“告警测试”,则消息中需要携带,否则无法发出
  7. // 更多配置请参考:https://ding-doc.dingtalk.com/doc#/serverapi2/qf2nxq
  8. // 图片消息需要确保图片路径可访问
  9. String msg = "#### xxx大数据平台 @13632608950\n" +
  10. "> 内存使用率:84%\n\n" +
  11. "> ![screenshot](https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1595400380087&di=1d5656aa2d536eec8c11a827e43610a1&imgtype=0&src=http%3A%2F%2Fimg0.imgtn.bdimg.com%2Fit%2Fu%3D684369095%2C514272752%26fm%3D214%26gp%3D0.jpg)\n" +
  12. "> ###### 10点20分发布 [告警测试](https://www.seniverse.com/) \n";
  13. if (sendMsg(ALERT_MSG_ROBOT_ID, msg)) {
  14. log.info("发送消息到钉钉成功!");
  15. }
  16. }
  17. /**
  18. * 发送机器人消息
  19. */
  20. public static boolean sendMsg(String robotId, String msg) throws ApiException {
  21. DingTalkClient client = new DefaultDingTalkClient(robotId);
  22. OapiRobotSendRequest request = new OapiRobotSendRequest();
  23. request.setMsgtype("markdown");
  24. OapiRobotSendRequest.Markdown markdown = new OapiRobotSendRequest.Markdown();
  25. markdown.setTitle("告警测试");
  26. markdown.setText(msg);
  27. request.setMarkdown(markdown);
  28. OapiRobotSendResponse response = client.execute(request);
  29. return response.isSuccess();
  30. }
  31. }