对接企业微信机器人
首先在企业微信群中添加机器人,创建后会弹出配置说明
保存好webhook url
然后是代码
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tiksage.modular.business.tiksage.entity.vo.MarkdownMessageVO;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
@Service
public class WeChatBotService {
private static String webhook;
@Value("${alert_bot.webhook}")
private void setWebhook(String webhook) {
WeChatBotService.webhook = webhook;
}
public void sendMarkdownMessage(String content) {
// create an httpclient instance
try {
CloseableHttpClient httpClient = HttpClients.createDefault();
// create an httppost request
HttpPost httpPost = new HttpPost(webhook);
httpPost.addHeader("Content-Type", "application/json;charset=utf-8");
// construct a message body
MarkdownMessageVO markdownMessage = new MarkdownMessageVO(content);
ObjectMapper objectMapper = new ObjectMapper();
String jsonMessage = objectMapper.writeValueAsString(markdownMessage);
StringEntity entity = new StringEntity(jsonMessage, "utf-8");
httpPost.setEntity(entity);
// send a request and get a response
CloseableHttpResponse response = httpClient.execute(httpPost);
String responseBody = EntityUtils.toString(response.getEntity(), "utf-8");
System.out.println("Response: " + responseBody);
}catch (Exception e){
e.printStackTrace();
}
}
}
在需要的地方调用就行了
顺便记录一下通过切面将报错信息发到群消息机器人
@Value("${server.env}")
private String env;
@AfterThrowing(pointcut = "execution(* xxx.xxx..*(..))", throwing = "exception")
public void handleException(JoinPoint joinPoint, Exception exception) {
// Check whether the current environment is a production environment
if("production".equals(env)){
try {
// obtain exception information
String errorMessage = exception.getMessage();
String exceptionType = exception.getClass().getName();
String stackTrace = Arrays.toString(exception.getStackTrace());
// get the class name and method name
String className = joinPoint.getSignature().getDeclaringTypeName();
String methodName = joinPoint.getSignature().getName();
// format the message content
String content = String.format(
"实时错误报告,请相关同事注意。\n\n" +
"> 类名: <font color=\"comment\">%s</font>\n" +
"> 方法名: <font color=\"comment\">%s</font>\n" +
"> 异常类型: <font color=\"comment\">%s</font>\n" +
"> 错误消息: <font color=\"comment\">%s</font>\n",
className, methodName, exceptionType, errorMessage
);
LogHelper.log("an error message is reported" + content);
// send a message to the wecom group bot
wChatBotService.sendMarkdownMessage(content);
} catch (Exception e) {
e.printStackTrace();
}
}
}
随便弄个报错测试一下