Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add wechat alarm notify, refactor code #1516

Merged
merged 6 commits into from
Jan 26, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,9 @@ public Page<AlertDefine> getMonitorBindAlertDefines(Specification<AlertDefine> s
public void applyBindAlertDefineMonitors(Long alertId, List<AlertDefineMonitorBind> alertDefineBinds) {
// todo checks whether the alarm definition and monitoring exist
// todo 校验此告警定义和监控是否存在

if (!alertDefineBindDao.existsById(alertId)){
alertDefineBindDao.deleteAlertDefineBindsByAlertDefineIdEquals(alertId);
}
// Delete all associations of this alarm
alertDefineBindDao.deleteAlertDefineBindsByAlertDefineIdEquals(alertId);
// Save the associated
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,15 +20,88 @@
import org.dromara.hertzbeat.common.entity.alerter.Alert;
import org.dromara.hertzbeat.common.entity.manager.NoticeReceiver;
import org.dromara.hertzbeat.common.entity.manager.NoticeTemplate;
import org.dromara.hertzbeat.manager.component.alerter.AlertNotifyHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.URI;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

/**
* @author <a href="mailto:Musk.Chen@fanruan.com">Musk.Chen</a>
*/
final class WeChatAlertNotifyHandlerImpl extends AbstractAlertNotifyHandlerImpl {
private static final Logger log = LoggerFactory.getLogger(WeChatAlertNotifyHandlerImpl.class);
private static final String CORP_ID = "YOUR_CORP_ID";
private static final String CORP_SECRET = "YOUR_CORP_SECRET";
private static final String AGENT_ID = "YOUR_AGENT_ID";
private static final String GET_TOKEN_URL = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=" + CORP_ID + "&corpsecret=" + CORP_SECRET;
private static final String SEND_MESSAGE_URL = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=";
private static final String ACCESS_TOKEN = "access_token";

@Override
public void send(NoticeReceiver receiver, NoticeTemplate noticeTemplate, Alert alert) {
// todo
try {
String accessToken = getAccessToken();
String messageContent = constructMessageContent(receiver, noticeTemplate, alert);
sendMessage(accessToken, messageContent);
} catch (Exception e) {
log.error("Failed to send WeChat alert", e);
}
}

private String getAccessToken() throws Exception {
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(new URI(GET_TOKEN_URL))
.GET()
.build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
JsonParser parser = new JsonParser();
JsonObject jsonObject = parser.parse(response.body()).getAsJsonObject();
String accessToken = null;
if (jsonObject.has(ACCESS_TOKEN)) {
accessToken = jsonObject.get(ACCESS_TOKEN).getAsString();
} else {
// todo 处理错误情况,例如记录日志或抛出异常
log.error("Failed to obtain ACCESS_TOKEN from response: {}", response.body());
}

return accessToken;
}

private String constructMessageContent(NoticeReceiver receiver, NoticeTemplate noticeTemplate, Alert alert) {
// 示例:构造一个文本消息内容
JsonObject messageContent = new JsonObject();
messageContent.addProperty("msgtype", "text");
JsonObject textContent = new JsonObject();

// 这里可以根据NoticeTemplate和Alert信息构造消息内容
String alertMessage = String.format("警告:%s\n详情:%s", alert.getAlertDefineId(), alert.getContent());
textContent.addProperty("content", alertMessage);
messageContent.add("text", textContent);

// 如果需要@某人,可以在这里添加
JsonObject atInfo = new JsonObject();
atInfo.addProperty("isAtAll", false); // 是否@所有人
messageContent.add("at", atInfo);

// 返回JSON字符串
return messageContent.toString();
}

private void sendMessage(String accessToken, String messageContent) throws Exception {
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(new URI(SEND_MESSAGE_URL + accessToken))
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(messageContent))
.build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
// 检查消息是否成功发送
log.info("Message sent response: {}", response.body());
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -211,12 +211,10 @@ public ResponseEntity<Message<Void>> export(MultipartFile file) throws Exception
@Operation(summary = "copy monitors by ids", description = "根据id批量复制monitor")
public ResponseEntity<Message<Void>> duplicateMonitors(
@Parameter(description = "Monitor ID List | 监控任务ID列表", example = "6565463543") @RequestParam List<Long> ids
) throws Exception {
){
if (ids != null && !ids.isEmpty()) {
monitorService.copyMonitors(ids);
}
return ResponseEntity.ok(Message.success("copy success"));
}


}
Loading