You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

177 lines
7.2 KiB

package com.example.demo.Util;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.demo.domain.vo.coin.ExecutionContext;
import com.example.demo.config.EnvConfig;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
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.Component;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* 飞书报警信息发送工具类
*/
@Component
public class FeiShuAlertUtil {
@Value("${feishu.webhook.url}")
private static String webhookUrl;
private static final String FEISHU_WEBHOOK_URL_PROD = "https://open.feishu.cn/open-apis/bot/v2/hook/1a515b19-b64f-46b7-9486-35842b9539fe";
private static final String FEISHU_WEBHOOK_URL_TEST = webhookUrl;
private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
static {
DATE_FORMAT.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
}
/**
* 发送报警信息到飞书群(紧凑单行格式)
*
* @param context 请求接口
* @param errorFile 错误文件
* @param errorLine 错误行数
* @param errorMsg 错误信息
* @param params 脚本执行时需要手动传参,如果时API请求则无需传,自动获取参数
* @return 是否发送成功
*/
public static boolean sendAlertMessage(ExecutionContext context,
String errorFile, int errorLine,
String errorMsg, String params) {
JSONObject message = new JSONObject();
message.put("msg_type", "post");
JSONObject content = new JSONObject();
JSONObject post = new JSONObject();
JSONObject zhCn = new JSONObject();
String title = "⚠️ 系统异常报警 ⚠️";
zhCn.put("title", title);
List<List<JSONObject>> contentList = new ArrayList<>();
List<JSONObject> elements = new ArrayList<>();
StringBuilder contentBuilder = new StringBuilder();
contentBuilder.append("------------------------------\n\n");
if ("API".equals(context.getExecutionType())) {
contentBuilder.append("**执行类型**: API请求\n\n");
contentBuilder.append("**请求接口**: ").append(context.getApiUrl()).append("\n\n");
contentBuilder.append("**请求参数**: ").append(params).append("\n\n");
contentBuilder.append("**请求方法**: ").append(context.getMethod()).append("\n\n");
if (context.getToken() != null) {
contentBuilder.append("**请求Token**: ")
.append(context.getToken().length() > 10 ?
context.getToken().substring(0, 10) + "..." :
context.getToken())
.append("\n\n");
}
} else {
contentBuilder.append("**执行类型**: 脚本执行\n\n");
contentBuilder.append("**脚本文件**: ").append(context.getScriptFile()).append("\n\n");
contentBuilder.append("**请求参数**: ").append(params).append("\n\n");
}
contentBuilder.append("**错误位置**: ").append(errorFile).append(":").append(errorLine).append("\n\n");
contentBuilder.append("**错误信息**: ").append(errorMsg).append("\n\n");
contentBuilder.append("**执行时间**: ").append(formatDate(context.getExecutionTime())).append("\n\n");
contentBuilder.append("**报警时间**: ").append(formatDate(new Date())).append("\n\n");
contentBuilder.append("------------------------------");
addContentElement(elements, "text", contentBuilder.toString());
contentList.add(elements);
zhCn.put("content", contentList);
post.put("zh_cn", zhCn);
content.put("post", post);
message.put("content", content);
return sendMessage(message);
}
private static String formatDate(Date date) {
// 实现日期格式化方法
return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);
}
private static void addContentElement(List<JSONObject> elements, String tag, String text) {
JSONObject element = new JSONObject();
element.put("tag", tag);
element.put("text", text);
elements.add(element);
}
private static boolean sendMessage(JSONObject message) {
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
String FEISHU_WEBHOOK_URL;
String environment = EnvConfig.ENV;
System.out.println("当前环境变量:" + environment);
if (Objects.equals(environment, "unknown") || environment.equals("dev")) {
FEISHU_WEBHOOK_URL = FEISHU_WEBHOOK_URL_TEST;
} else {
FEISHU_WEBHOOK_URL = FEISHU_WEBHOOK_URL_PROD;
}
HttpPost httpPost = new HttpPost(FEISHU_WEBHOOK_URL);
httpPost.addHeader("Content-Type", "application/json; charset=utf-8");
StringEntity entity = new StringEntity(message.toJSONString(), "UTF-8");
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
String result = EntityUtils.toString(response.getEntity());
JSONObject obj = JSON.parseObject(result);
return obj.getInteger("code") == 0;
}
} catch (IOException e) {
System.out.println("发送飞书异常" + e.getMessage());
e.printStackTrace();
}
return false;
}
/**
* 发送普通信息到飞书群
*
* @param title 消息标题
* @param content 消息内容
* @return 是否发送成功
*/
public static boolean sendNormalMessage(String title, String content) {
JSONObject message = new JSONObject();
message.put("msg_type", "post");
JSONObject messageContent = new JSONObject();
JSONObject post = new JSONObject();
JSONObject zhCn = new JSONObject();
zhCn.put("title", title);
List<List<JSONObject>> contentList = new ArrayList<>();
List<JSONObject> elements = new ArrayList<>();
StringBuilder contentBuilder = new StringBuilder();
contentBuilder.append("------------------------------\n\n");
contentBuilder.append(content).append("\n\n");
contentBuilder.append("**发送时间**: ").append(formatDate(new Date())).append("\n\n");
contentBuilder.append("------------------------------");
addContentElement(elements, "text", contentBuilder.toString());
contentList.add(elements);
zhCn.put("content", contentList);
post.put("zh_cn", zhCn);
messageContent.put("post", post);
message.put("content", messageContent);
return sendMessage(message);
}
}