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);
		}
	}
}

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

最后效果

相关推荐
铁蛋AI编程实战2 分钟前
通义千问 3.5 Turbo GGUF 量化版本地部署教程:4G 显存即可运行,数据永不泄露
java·人工智能·python
晚霞的不甘13 分钟前
CANN 编译器深度解析:UB、L1 与 Global Memory 的协同调度机制
java·后端·spring·架构·音视频
SunnyDays101115 分钟前
使用 Java 冻结 Excel 行和列:完整指南
java·冻结excel行和列
摇滚侠26 分钟前
在 SpringBoot 项目中,开发工具使用 IDEA,.idea 目录下的文件需要提交吗
java·spring boot·intellij-idea
云姜.31 分钟前
java多态
java·开发语言·c++
李堇34 分钟前
android滚动列表VerticalRollingTextView
android·java
猫头虎1 小时前
如何解决 OpenClaw “Pairing required” 报错:两种官方解决方案详解
网络·windows·网络协议·macos·智能路由器·pip·scipy
泉-java1 小时前
第56条:为所有导出的API元素编写文档注释 《Effective Java》
java·开发语言
zfoo-framework1 小时前
帧同步和状态同步
java
charlotte102410241 小时前
高并发:关于在等待学校教务系统选课时的碎碎念
java·运维·网络