飞书机器人告警消息开发(Java)

一、机器人配置

1)新建群组

2)添加自定义机器人

二、代码开发

2.1 pom依赖

<!-- HTTP 客户端 -->
<dependency>
  <groupId>org.apache.httpcomponents</groupId>
  <artifactId>httpclient</artifactId>
  <version>4.5.13</version>
</dependency>
<!-- JSON 处理 -->
<dependency>
  <groupId>com.alibaba.fastjson2</groupId>
  <artifactId>fastjson2</artifactId>
  <version>2.0.48</version>
</dependency>

2.2 代码

package org.example;

import com.alibaba.fastjson2.JSON;
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.commons.codec.binary.Base64;
import org.apache.http.util.EntityUtils;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;

public class FeishuAlertUtil {
    private static final String WEBHOOK_URL = "https://open.feishu.cn/open-apis/bot/v2/hook/xxx1";
    private static final String SECRET = "xxx2"; // 机器人安全设置的密钥

    public static void sendAlert(String message) throws Exception {
        long timestamp = System.currentTimeMillis() / 1000;
        String sign = generateSign(SECRET, timestamp);

        // 构建消息体
        Map<String, Object> content = new HashMap<>();
        content.put("text", message);

        Map<String, Object> payload = new HashMap<>();
        payload.put("timestamp", timestamp);
        payload.put("sign", sign);
        payload.put("msg_type", "text");
        payload.put("content", content);

        // 发送请求
        try (CloseableHttpClient client = HttpClients.createDefault()) {
            HttpPost httpPost = new HttpPost(WEBHOOK_URL);
            httpPost.setHeader("Content-Type", "application/json; charset=utf-8");
            httpPost.setEntity(new StringEntity(JSON.toJSONString(payload), StandardCharsets.UTF_8));

            try (CloseableHttpResponse response = client.execute(httpPost)) {
                System.out.println("飞书返回: " + EntityUtils.toString(response.getEntity()));
            }
        }
    }

    private static String generateSign(String secret, long timestamp) throws NoSuchAlgorithmException, InvalidKeyException {
        //把timestamp+"\n"+密钥当做签名字符串
        String stringToSign = timestamp + "\n" + secret;
        //使用HmacSHA256算法计算签名
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(new SecretKeySpec(stringToSign.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
        byte[] signData = mac.doFinal(new byte[]{});
        return new String(Base64.encodeBase64(signData));
    }
}
public class AlertDemo {
    public static void main(String[] args) {
        try {
            FeishuAlertUtil.sendAlert("🚨 服务器CPU使用率超过95%!");
        } catch (Exception e) {
            System.err.println("告警发送失败: " + e.getMessage());
        }
    }
}

三、测试

运行AlertDemo类。

代码运行结果:

飞书返回: {"StatusCode":0,"StatusMessage":"success","code":0,"data":{},"msg":"success"}

Process finished with exit code 0

消息结果:

四、参考文档

自定义机器人使用指南 - 开发指南 - 飞书开放平台

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

走过冬季

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值