需求:实现告警信息推送到企业微信群
介绍:企业微信支持自建应用推送消息和机器人推送消息,根据不同需求都可实现。
方案一:机器人推送
在群里建一个机器人,复制该机器人的webhook
例如:https://qyapi./cgi-bin/webhook/send?key=123555asdfgh23456
方案二:应用推送
可通过postman测验
一、管理员创建应用->从而拿到应用的secret对应corpsecret,并且拿到企业ID对应corpid二、后台获取到该应用2个小时有效的access_token三、后台调用接口创建群聊,拿到群聊ID对应chatid,可自己指定四、后台调用接口让应用向群发送消息
下面给出代码演示
pom依赖
<dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpcore</artifactId><version>4.4.6</version></dependency><dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpclient</artifactId><version>4.5.5</version></dependency><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.58</version></dependency>
工具类,异常自己替换掉
import com.alibaba.fastjson.JSON;import com.alibaba.fastjson.JSONArray;import com.alibaba.fastjson.JSONObject;import org.apache.http.*;import org.apache.http.client.config.RequestConfig;import org.apache.http.client.entity.UrlEncodedFormEntity;import org.apache.http.client.methods.*;import org.apache.http.entity.StringEntity;import org.apache.http.impl.client.CloseableHttpClient;import org.apache.http.impl.client.HttpClientBuilder;import org.apache.http.impl.client.HttpClients;import org.apache.http.message.BasicNameValuePair;import org.apache.http.util.EntityUtils;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import java.io.IOException;import java.io.UnsupportedEncodingException;import java.nio.charset.Charset;import java.util.ArrayList;import java.util.Collections;import java.util.List;import java.util.Map;import java.util.stream.Collectors;public class HttpUtils {public static final Logger LOGGER = LoggerFactory.getLogger(HttpUtils.class);private static final RequestConfig CONFIG = RequestConfig.custom().setConnectTimeout(30000).setSocketTimeout(50000).build();private static List<Integer> httpOkCode=new ArrayList<>(10);static{httpOkCode.add( HttpStatus.SC_OK );httpOkCode.add( HttpStatus.SC_CREATED );httpOkCode.add( HttpStatus.SC_ACCEPTED );httpOkCode.add( HttpStatus.SC_NON_AUTHORITATIVE_INFORMATION );httpOkCode.add( HttpStatus.SC_NO_CONTENT );httpOkCode.add( HttpStatus.SC_RESET_CONTENT );httpOkCode.add( HttpStatus.SC_PARTIAL_CONTENT );httpOkCode.add( HttpStatus.SC_MULTI_STATUS );}/*** 执行一个HTTP GET请求,返回请求响应的HTML** @param url 请求的URL地址* @return 返回请求响应的HTML* @throws IOException*/public static String doGet(String url, Map<String, String> params) throws IOException {CloseableHttpClient client = HttpClientBuilder.create().setDefaultRequestConfig(CONFIG).build();if (params != null) {url = url + "?" + map2Str(params);}HttpGet httpGet = new HttpGet(url);try {HttpResponse httpResponse = client.execute(httpGet);if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {return EntityUtils.toString(httpResponse.getEntity(), "utf-8");} else {LOGGER.info("HTTP接口调用状态码为{},非200、非201,调用接口:{}\n参数:{}\n", httpResponse.getStatusLine().getStatusCode(), url, params);}} finally {if (client != null) {client.close();}}return "";}/*** 执行一个HTTP POST请求,返回请求响应的HTML** @param url 请求的URL地址* @return 返回请求响应的HTML* @throws IOException*/public static String doPost(String url, Map<String, Object> params) throws IOException {CloseableHttpClient client = HttpClientBuilder.create().build();HttpPost httpPost = new HttpPost(url);if (params != null) {StringEntity entity = new StringEntity(JSON.toJSONString(params), Charset.forName("UTF-8"));httpPost.setEntity(entity);}httpPost.setHeader("Content-type", "application/json; charset=utf-8");try {HttpResponse httpResponse = client.execute(httpPost);if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK|| httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED) {HttpEntity responseEntityentity = httpResponse.getEntity();return EntityUtils.toString(responseEntityentity, "utf-8");} else {LOGGER.info("HTTP接口调用状态码为{},非200、非201,调用接口:{}\n参数:{}\n", httpResponse.getStatusLine().getStatusCode(), url, params);}} finally {if (client != null) {client.close();}}return "";}}
机器人
import java.io.IOException;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;/*** Created by ZhiWen on /5/20 14:06* 通过企业微信群的机器人向群内发送消息*/public class SendWeChatByBot {private static SendWeChatByBot bot= new SendWeChatByBot();private final String webhook = "https://qyapi./cgi-bin/webhook/send?key=33fc3a3b-c0fb-4046-89dd-ecb99f7c7ba3";private SendWeChatByBot() {};public static SendWeChatByBot getBot() {return bot;}/*** 发送文本消息* @param message* @throws IOException*/public void sendText(String message) throws IOException {ArrayList all = new ArrayList(1);all.add("@all");sendText(message, all);}/*** 发送文本消息并@用户* @param message* @param mentionedList* @throws IOException*/public void sendText(String message, List mentionedList) throws IOException {Map<String, Object> body = new HashMap<>(2);Map<String, Object> text = new HashMap<>(2);text.put("content", message);text.put("mentioned_list", mentionedList);body.put("msgtype", "text");body.put("text", text);String result = HttpUtils.doPost(webhook, body);}/*** 发送Markdown消息* @param message* @param level* @throws IOException*/public void sendMarkDown(String message, Integer level) throws IOException {Map<String, Object> body = new HashMap<>(2);Map<String, String> markdown = new HashMap<>(1);String content = "**嘀嘀嘀,收到报警信息,请相关同事注意。**\n " +"><font color=\"info\">警报级别:</font><font color=\"warning\">"+level+"</font>\n " +"><font color=\"info\">警报日志:</font>"+message;markdown.put("content", content);body.put("msgtype", "markdown");body.put("markdown", markdown);String result = HttpUtils.doPost(webhook, body);}}
应用
import com.alibaba.fastjson.JSON;import java.io.IOException;import java.util.HashMap;import java.util.Map;/*** Created by ZhiWen on /5/19 15:28* 通过自建应用向企业微信发送消息*/public class SendWeChatByApp {private String accessToken;private static SendWeChatByApp sendWeChat = new SendWeChatByApp();private SendWeChatByApp() {}public static SendWeChatByApp getInstance() {return sendWeChat;}private String getAccessToken() {String corpId = "";String corpSecret = "";return getAccessToken(corpId, corpSecret);}/*** 获取秘钥 需要添加缓存机制* @param corpId* @param corpSecret* @return*/public String getAccessToken(String corpId, String corpSecret) {String url = String.format("https://qyapi./cgi-bin/gettoken?corpid=%s&corpsecret=%s", corpId, corpSecret);System.out.println(url);String jsonResult = HttpUtils.doGet(url);Map<String, String> map = JSON.parseObject(jsonResult, Map.class);String token = map.get("access_token");System.out.println(token);return token;}/*** 发送群聊消息* @param token* @param param* @throws IOException*/public void appChatSend(String token, Map<String, Object> param) throws IOException {String url = String.format("https://qyapi./cgi-bin/appchat/send?access_token=%s", token);String result = HttpUtils.doPost(url, param);}/*** 创建群聊请求体** @param chatId 群聊ID* @param message 发送的消息* @return*/public Map<String, Object> appChatTextBody(String chatId, String message) {Map<String, Object> body = new HashMap<>(4);Map<String, String> text = new HashMap<>(1);text.put("content", message);body.put("chatid", chatId);body.put("msgtype", "text");body.put("text", text);return body;}}
Test
public static void main(String[] args) throws IOException {/*String message = "通过应用自动向企业微信群发送报警信息\n请相关人员查阅并修复!";SendWeChatByApp sendWeChat = SendWeChatByApp.getInstance();String accessToken = sendWeChat.getAccessToken("j4j55ffs4345", "Cfsg-A34_uncKu-Hf35qo-z2345_df__NVg");Map<String, Object> body = sendWeChat.appChatTextBody("dfhaksfhafsduaoenfSJFAOFJAjfsl", message);sendWeChat.appChatSend(accessToken,body);*/String msg = "我是一个机器人,我给大家拜个年!\n红包红包\n";SendWeChatByBot bot = SendWeChatByBot.getBot();//bot.sendText(msg);bot.sendMarkDown(msg,2);}
最后把API地址给到https://work./api/doc/90000/90135/90664
准备到知乎写故事了