整合 Lark 机器人

使用 LarksuiteNotificationUtils

tio-utils 已经内置了 LarksuiteNotificationUtils 工具类,能够非常方便地推送消息到 Lark 群。以下是使用示例:

import com.litongjava.tio.utils.notification.LarksuiteNotificationUtils;
import okhttp3.Response;
import java.io.IOException;

try (Response response = LarksuiteNotificationUtils.sendWarm(EnvUtils.get("warm.notification.webhook.url"), model)) {
  if (!response.isSuccessful()) {
    try {
      log.info("消息推送失败: {}", response.body().string());
    } catch (IOException e1) {
      e1.printStackTrace();
    }
  }
}

在这个例子中,LarksuiteNotificationUtils 提供了一个简单的方法来发送消息到指定的 Lark webhook URL。你可以通过 EnvUtils.get() 获取你的 webhook 地址,并使用 sendWarm() 方法推送消息。

使用 Lark 官方 SDK (lark oapi-sdk)

Lark 官方为 Java 提供了 oapi-sdk,可以更加灵活地与 Lark 的 API 进行集成。首先,你需要在项目中添加以下依赖:

<dependency>
  <groupId>com.larksuite.oapi</groupId>
  <artifactId>oapi-sdk</artifactId>
  <version>2.2.10</version>
</dependency>

接下来,编写发送消息的工具类:

import com.jfinal.kit.Kv;
import com.lark.oapi.Client;
import com.lark.oapi.service.im.v1.enums.CreateMessageReceiveIdTypeEnum;
import com.lark.oapi.service.im.v1.model.CreateMessageReq;
import com.lark.oapi.service.im.v1.model.CreateMessageReqBody;
import com.litongjava.tio.utils.json.JsonUtils;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class LarkBotQuestionUtils {
  public static final String APP_ID = "cli_xxxxx"; // 替换为你的APP ID
  public static final String APP_SECRET = "xxxx";  // 替换为你的APP Secret
  public static final String RECEIVE_ID = "xxxx";  // 替换为接收消息的ID

  public static void send(String text) {

    // 初始化客户端
    Client client = Client.newBuilder(APP_ID, APP_SECRET).build();

    // 构建消息体
    String content = JsonUtils.toJson(Kv.by("text", text));

    CreateMessageReqBody reqBody = CreateMessageReqBody.newBuilder()
        .receiveId(RECEIVE_ID)
        .msgType("text")
        .content(content)
        .build();

    // 构建消息请求
    CreateMessageReq req = CreateMessageReq.newBuilder()
        .receiveIdType(CreateMessageReceiveIdTypeEnum.CHAT_ID)
        .createMessageReqBody(reqBody)
        .build();

    try {
      // 发送消息
      CreateMessageResp resp = client.im().v1().message().create(req);
      if (resp.getError() != null) {
        log.error("发送消息到 Lark 机器人失败: {}", resp.getError());
      }
    } catch (Exception e) {
      log.error("消息发送异常", e);
    }
  }
}

单元测试

为了确保 LarkBotQuestionUtils 正常工作,可以使用 JUnit 编写一个简单的单元测试:

import org.junit.Test;

public class LarkBotQuestionUtilsTest {

  @Test
  public void test() {
    LarkBotQuestionUtils.send("你好吗?");
  }
}

该测试会向指定的 Lark 机器人发送 "你好吗?" 这条消息,确保 Lark 机器人的集成正常工作。