[钉钉通知系列]SVN提交后自动推送消息到钉钉群

钉钉设置机器人配置

1、进入配置机器人入口

2、添加机器人





3、测试WebHook请求

本人使用Postman进行测试

4、配置SVN


4.1 配置 Pre-commit hook

  • 设置提交内容必须包含注释
  • 配置参数
@echo off
setlocal
set REPOS=%1
set TXN=%2
rem check that logmessage contains at least 10 characters
svnlook log %REPOS% -t %TXN% | findstr "....." > nul
if %errorlevel% gtr 0 goto err
exit 0
:err
echo 上传失败!请添加注释. 注释长度至少为5个字符. Commit aborted! 1>&2
exit 1

4.2 配置 Post-commit hook

set REPOS=%1
set REV=%2
set tttt=%date:~0,10% %time:~0,8%
for /f "tokens=1,2 delims=:" %%a in ('svnlook author -r %REV% %REPOS%') do (
    if not defined AUTHOR set AUTHOR=%%a
)
for /f "tokens=1,2 delims=:" %%a in ('svnlook dirs-changed %REPOS%') do (
    if not defined CHANGEDDIRS set CHANGEDDIRS=%%a
)
for /f "tokens=1,2 delims=:" %%a in ('svnlook log -r %REV% %REPOS%') do (
    if not defined MESSAGE set MESSAGE=%%a
)
set CONTENT="提交时间:%tttt% \n提交版本:%REV% \n作者:%AUTHOR%\n提交备注:%MESSAGE%\n修改目录:%CHANGEDDIRS% "
java -cp D:\svnHook.jar com.wolf.util.Request 钉钉令牌 %CONTENT%

5 配置Java请求文件

由于钉钉提供的接口是https协议,curl需要支持https,因此通过java代码发起Post请求,打包成可运行的jar,然后用post-commit hook调用,传入信息即可。

package com.wolf.util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;

import javax.net.ssl.HttpsURLConnection;

public class Request {
	public static void main(String[] args) throws Exception {
		String token = args[0];
		String content = args[1];
		content = "{\"msgtype\": \"text\",\"text\": {\"content\": \""+content+"\"}}";
		httpsRequest("https://oapi.dingtalk.com/robot/send?access_token="+token, "POST", content);
		System.out.println("OK");
		System.exit(0);
	}

	/**
	 * 发送https请求
	 */
	public static String httpsRequest(String requestUrl, String requestMethod, String outputStr) throws Exception {
		HttpsURLConnection conn = null;
		BufferedReader bufferedReader = null;
		try {
			URL url = new URL(requestUrl);
			conn = (HttpsURLConnection) url.openConnection();
			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.setUseCaches(false);
			conn.setRequestMethod(requestMethod);
			conn.setRequestProperty("content-type", "application/json");
			if (null != outputStr) {
				OutputStream outputStream = conn.getOutputStream();
				outputStream.write(outputStr.getBytes("utf-8"));
				outputStream.close();
			}
			bufferedReader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
			String str = null;
			StringBuffer buffer = new StringBuffer();
			while ((str = bufferedReader.readLine()) != null) {
				buffer.append(str);
			}
			return buffer.toString();
		} catch (Exception e) {
			throw e;
		} finally {
			if (conn != null) {
				conn.disconnect();
			}
			if (bufferedReader != null) {
				try {
					bufferedReader.close();
				} catch (IOException e) {
				}
			}
		}
	}
}

结果如下:

posted @ 2017-05-10 14:20  简玄冰  阅读(10189)  评论(13编辑  收藏  举报