转载请标明出处:http://blog.csdn.net/zhaoyanjun6/article/details/122970426
本文出自【赵彦军的博客】
今天接到一个需求,写一个 gradle 小插件,在执行完某个 gradle 任务后,向钉钉群聊机器人发送一条消息,并自动 @所有人。
首先在钉钉群中创建智能机器人,并获取到 Webhook
链接
有了 Webhook
链接就可以给机器人发消息了。下面我们来自定义 gradle
工具。
在项目的跟目录创建 dingding.gradle
dingding.gradle
代码如下:
import groovy.json.JsonBuilder
import groovy.json.JsonOutput
def dingDingUrl = "https://oapi.dingtalk.com/robot/send?access_token=14xxxxx"
ext.postDingMsg = { String artifactId, String version, String userName, String tips ->
String allTips = "#### 新版本发布提醒(${artifactId})\n" +
'> 项目:' + userName + '发布了最新版本:' + version + '\n\n' +
'> 更新说明:' + tips + '\n\n'
//@所有人
postAll(dingDingUrl, allTips)
}
//发送到群,@所有人
def postAll(url, tips) {
JsonBuilder builder = new JsonBuilder()
builder {
msgtype 'markdown'
markdown {
title '二方库发布提醒'
text tips
}
at {
isAtAll true
}
}
String data = JsonOutput.prettyPrint(builder.toString())
postDingDing(url, data)
}
//调用接口,发送消息
def postDingDing(urlString, msg) {
if (msg == null) {
return
}
HttpURLConnection conn = null
OutputStream outputStream = null
try {
if (conn == null) {
URL url = new URL(urlString)
conn = (HttpURLConnection) url.openConnection()
}
if (conn != null) {
conn.setReadTimeout(15000)
conn.setConnectTimeout(15000)
conn.setDoOutput(true)
conn.setUseCaches(false)
conn.setRequestProperty("Content-Type", "application/json; charset=utf-8")
}
if (conn == null) {
return null
}
if (msg != null && msg.length() > 0) {
DataOutputStream dataOutputStream = new DataOutputStream(conn.getOutputStream())
byte[] t = msg.getBytes("utf-8")
dataOutputStream.write(t)
dataOutputStream.flush()
dataOutputStream.close()
int res = conn.getResponseCode()
println res
if (res == 200) { //成功
InputStream input = conn.getInputStream()
StringBuffer sb = new StringBuffer()
int ss
while ((ss = input.read()) != -1) {
sb.append((char) ss)
}
} else {
println("发送消息失败----" + conn.getResponseCode())
}
}
} catch (EOFException e) {
e.printStackTrace()
} catch (IOException e) {
e.printStackTrace()
} finally {
if (outputStream != null) {
try {
outputStream.close()
} catch (IOException e) {
e.printStackTrace()
}
}
if (conn != null) {
conn.disconnect()
}
}
}
在 app 的 build.gradle
下添加 gradle 依赖
apply from: '../dingding.gradle'
//assembleRelease 任务后面插入 postDingDingTask 任务
afterEvaluate {
// 1. 找到需要依赖自己 Task的构建流程的Task
def mergeResourcesTask = tasks.findByName("assembleRelease")
// 2. 通过 finalizedBy 方法,插入到指定Task之后
mergeResourcesTask.finalizedBy(postDingDingTask)
}
//发送消息
task postDingDingTask {
doLast {
def artifactId = "release"
def version = "1.2.0"
def userName = "小张"
def tip = "修复空指针bug https://www.baidu.com"
postDingMsg(artifactId, version, userName, tip)
}
}
下面我们执行一下 assembleRelease
任务,就可以看到消息提醒了
好了,结束下班。