Java接入飞书发送通知消息

添加依赖

xml 复制代码
        <!--飞书推送-->
        <dependency>
            <groupId>com.larksuite.oapi</groupId>
            <artifactId>oapi-sdk</artifactId>
            <version>2.4.22</version>
        </dependency>

创建应用,添加机器人


开通权限

制作卡片

这里配置了一个变量,用来接收具体的消息内容

Java代码

java 复制代码
					//飞书推送消息
					List<String> targetUserIds = new ArrayList<>();//接收消息的open_id
					targetUserIds.add(iDictValue.getDictValue("jcNotice",underTakeId));
					String content = balanceUser+" 平衡的集中采购合同号("+poNo+"),已经生成,请及时处理!";
					feishuUserService.batchPushMessage(targetUserIds, content);
java 复制代码
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.lark.oapi.Client;
import com.lark.oapi.core.response.RawResponse;
import com.lark.oapi.core.token.AccessTokenType;
import com.lark.oapi.core.utils.Jsons;
import com.lark.oapi.service.im.v1.model.CreateMessageReq;
import com.lark.oapi.service.im.v1.model.CreateMessageReqBody;
import com.lark.oapi.service.im.v1.model.CreateMessageResp;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.nio.charset.StandardCharsets;
import java.util.List;

@Service
@Slf4j
public class FeishuUserServiceImpl implements IFeishuUserService{

	@Value("${feishu.app-id}")
	private String appId;

	@Value("${feishu.app-secret}")
	private String appSecret;


	//飞书消息推送
	public void pushMessage(String openId, String content) throws Exception {
		// 构建client
		Client client = Client.newBuilder(appId, appSecret).build();

		// 创建请求对象
		CreateMessageReq req = CreateMessageReq.newBuilder()
			.receiveIdType("open_id")
			.createMessageReqBody(CreateMessageReqBody.newBuilder()
				.receiveId(openId)
				.msgType("text")
				.content("{\"text\":\"" + content + "\"}")
				.build())
			.build();

		// 发起请求
		CreateMessageResp resp = client.im().v1().message().create(req);

		// 处理服务端错误
		if(!resp.success()) {
			log.error(String.format("code:%s,msg:%s,reqId:%s, resp:%s",
				resp.getCode(), resp.getMsg(), resp.getRequestId(), Jsons.createGSON(true, false).toJson(JsonParser.parseString(new String(resp.getRawResponse().getBody(), StandardCharsets.UTF_8)))));
			return;
		}

		// 业务数据处理
		log.info(Jsons.DEFAULT.toJson(resp.getData()));
	}

	//批量推送
	@Override
	public void batchPushMessage(List<String> openIds, String content) {
		// 构建client
		Client client = Client.newBuilder(appId, appSecret).build();

		// 检查参数有效性
		if (openIds == null || openIds.isEmpty()) {
			return;
		}

		if (content == null || content.trim().isEmpty()) {
			return;
		}

		try {
			// 构建接收者ID列表
			JsonArray ids = new JsonArray();
			for (String openId : openIds) {
				ids.add(openId);
			}

			// 构建消息内容
			JsonObject contentObj = new JsonObject();
			contentObj.addProperty("type", "template");
			JsonObject cardData = new JsonObject();
			cardData.addProperty("template_id", "AAqhywvSQImB5");//卡片ID
			JsonObject tampVar = new JsonObject();
			tampVar.addProperty("noticeInfo", content);//消息变量
			cardData.add("template_variable", tampVar);
			contentObj.add("data", cardData);

			// 构建请求体
			JsonObject body = new JsonObject();
			body.addProperty("msg_type", "interactive");
			body.add("open_ids", ids);
			body.add("card", contentObj);

			// 发送请求
			RawResponse rawResponse = client.post(
				"/open-apis/message/v4/batch_send/",
				body,
				AccessTokenType.Tenant
			);

			// 解析响应
			if (rawResponse.getStatusCode() == 200) {
				log.info("批量推送消息成功");
			} else {
				log.error("批量推送消息失败");
			}
		} catch (Exception e) {
			log.error("批量推送消息异常", e);
		}
	}
}

配置文件就是飞书中的应用凭证

最后效果

相关推荐
寻星探路42 分钟前
【深度长文】万字攻克网络原理:从 HTTP 报文解构到 HTTPS 终极加密逻辑
java·开发语言·网络·python·http·ai·https
曹牧3 小时前
Spring Boot:如何测试Java Controller中的POST请求?
java·开发语言
爬山算法4 小时前
Hibernate(90)如何在故障注入测试中使用Hibernate?
java·后端·hibernate
kfyty7254 小时前
集成 spring-ai 2.x 实践中遇到的一些问题及解决方案
java·人工智能·spring-ai
猫头虎4 小时前
如何排查并解决项目启动时报错Error encountered while processing: java.io.IOException: closed 的问题
java·开发语言·jvm·spring boot·python·开源·maven
李少兄4 小时前
在 IntelliJ IDEA 中修改 Git 远程仓库地址
java·git·intellij-idea
忆~遂愿4 小时前
ops-cv 算子库深度解析:面向视觉任务的硬件优化与数据布局(NCHW/NHWC)策略
java·大数据·linux·人工智能
小韩学长yyds4 小时前
Java序列化避坑指南:明确这4种场景,再也不盲目实现Serializable
java·序列化
仟濹4 小时前
【Java基础】多态 | 打卡day2
java·开发语言
Re.不晚5 小时前
JAVA进阶之路——无奖问答挑战2
java·开发语言