【Java】企业微信机器人自动发送群消息
1.先在群里添加机器人,然后获取机器人的webhook地址:
2.有多种方式发送群消息,可以采用curl,也可以采用发送https请求的方式,我这里采用okhttp发送http请求,pom如下:
<!-- https://mvnrepository.com/artifact/com.squareup.okhttp3/okhttp -->
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.9.0</version>
</dependency>
调用okhttp核心代码如下:
/**
* @content:要发送的消息
* WECHAT_GROUP:机器人的webhook
*/
public static String callWeChatBot(String content) {
OkHttpClient client = new OkHttpClient()
.newBuilder()
.build();
MediaType mediaType = MediaType.parse("application/json");
RequestBody body = RequestBody.create(content,mediaType);
Request request = new Request.Builder()
.url(WECHAT_GROUP)
.method("POST", body)
.addHeader("Content-Type", "application/json")
.build();
Response response = null;
try {
response = client.newCall(request).execute();
} catch (IOException e) {
e.printStackTrace();
}
return response.message();
}
3.生成核心方法的参数,如果发送markdown格式的消息:
public static String generalBotBodyInfo(File f1, File f2, String cusenv, String myenv) {
String content = "**信息摘要:**
" +
">文件1:<font color=\"info\">" + f1.getName() + "</font>
" +
">服务器路径:<font color=\"info\">" + f1.getAbsolutePath() + "</font>
" +
">文件传输环境:<font color=\"info\">" + myenv + "</font>
" +
">客户接受环境:<font color=\"info\">" + cusenv + "</font>
" +
">时间:<font color=\"info\">" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + "</font>";
String textTemplate = "{
" +
" "msgtype": "markdown",
" +
" "markdown": {
" +
" "content": "" + content + "",
" +
" }
" +
"}";
return textTemplate;
}
如果发送text格式的消息:
public static String generalBotBodyAT() {
String textTemplate = "{
" +
" "msgtype": "text",
" +
" "text": {
" +
" "content": "今天下午大暴雨",
" +
" "mentioned_list":["@all"],
" +
" }
" +
"}";
return textTemplate;
}
如果发送图片,不能超过2M,支持的格式为JPG,PNG格式:
发送图片需要对图片进行base64编码并计算图片的md5值,把计算的方法也一并献上,需要注意图片不要过大,不然base64编码的结果会超级长,甚至超过String的最大长度,java.util.Base64这个工具类有现成的,直接用就行
public static String getFileBase64(String path){
try {
FileInputStream inputStream = new FileInputStream(new File(path));
byte [] bs = new byte[inputStream.available()];
inputStream.read(bs);
return Base64.getEncoder().encodeToString(bs);
} catch (FileNotFoundException e) {
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}
return null;
}
计算md5值方法多种多样,如果你发送的图片是固定的,建议算好后直接用常量保存就行,比如我发送的是个表情包,就提前算好了。如果你是windows系统可以用好压之类的工具直接查看文件的md5,如果你是mac os系统,可以这样: 如果图片是动态的,可以用java现成的工具类直接计算它的md5,pom如下:
<!-- https://mvnrepository.com/artifact/commons-codec/commons-codec -->
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.10</version>
</dependency>
代码:
public static String getFileMD5(String path) {
try {
FileInputStream inputStream = new FileInputStream(new File(path));
byte[] buf = new byte[inputStream.available()];
inputStream.read(buf);
return DigestUtils.md5Hex(buf);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
以上。
