SDK
1、导入依赖
java
<dependency>
<groupId>com.larksuite.oapi</groupId>
<artifactId>oapi-sdk</artifactId>
<version>2.5.3</version>
</dependency>
2、开通权限
https://open.feishu.cn/document/faq/trouble-shooting/how-to-fix-the-99991672-error
java
/**
* 发送飞书文本消息
*
* @param receiveId 接收者ID(如 open_id、chat_id、email 等)
* @param receiveIdType ID类型:open_id | chat_id | email | user_id
* @param text 消息文本内容
*/
public void sendFeiShuTextMessage(String receiveId, String receiveIdType, String text) {
try {
// 1. 构造消息内容 JSON:{"text":"xxx"}
Map<String, String> content = new HashMap<>();
content.put("text", text);
String contentJson = JSONUtil.toJsonStr(content);
// 2. 构建请求体
CreateMessageReq req = CreateMessageReq.newBuilder().receiveIdType(receiveIdType)
.createMessageReqBody(CreateMessageReqBody.newBuilder()
.receiveId(receiveId)
.msgType("text")
.content(contentJson)
.uuid("uuid"))
.build())
.build();
// 3. 调用 SDK 发送
CreateMessageResp resp = feishuClient.im().v1().message().create(req);
// 4. 处理响应
if (resp.success()) {
log.info("飞书文本消息发送成功, messageId: {}", resp.getData().getMessageId());
} else {
log.error("飞书消息发送失败 | code: {} | msg: {} | logId: {}",
resp.getCode(), resp.getMsg(), resp.getRequestId());
throw new RuntimeException("飞书消息发送失败: " + resp.getMsg());
}
} catch (Exception e) {
log.error("发送飞书消息异常", e);
throw new RuntimeException("发送飞书消息异常", e);
}
}
webHook
1、新创建个飞书群,添加人员和机器人
2、获得webhook地址
https://open.feishu.cn/open-apis/bot/v2/hook/xxxxxxx
java
/**
* 发送飞书文本消息
*
* @param text 消息文本内容
*/
public void sendFeiShuTextMessage(String text) {
try {
if (StringUtils.isBlank(feishuWebhookUrl)) {
log.warn("飞书webhook地址未配置,无法发送消息");
return;
}
// 构建飞书消息payload
JSONObject payload = new JSONObject();
// 设置消息类型为文本
payload.set("msg_type", "text");
// 构建消息内容
JSONObject textContent = new JSONObject();
textContent.set("text", text);
payload.set("content", textContent);
log.info("发送飞书消息,webhook地址:{}, 消息内容:{}", feishuWebhookUrl, payload.toStringPretty());
// 调用飞书webhook接口
String response = HttpUtil.post(feishuWebhookUrl, payload.toString());
log.info("飞书消息发送成功,响应结果:{}", response);
JSONObject responseObj = JSONUtil.parseObj(response);
Integer code = responseObj.getInt("code");
if (code != null && code != 0) {
log.error("飞书消息发送失败,错误代码:{}, 错误信息:{}", code, responseObj.getStr("msg"));
}
} catch (Exception e) {
log.error("发送飞书消息异常,消息内容:{}", text, e);
}
}