Skip to content

扩展库对接飞书

概述

本文展示了调用扩展库发起飞书消息通知

飞书集成请查看第三方集成

实现方式

定义入参对象

java
public class FeishuImMsgReq {
    private String receiveType;
    private String receiveId;
    private String msgType;
    private String content;
    getter...
    setter...
}

定义飞书返回消息

java
public class FeishuImMessageRsp {
    private Integer code;
    private String msg;
    private FeishuImMessageInfo data;
    getter...
    setter...
}

定义发送飞书消息静态函数

java
public static FeishuImMessageInfo sendFeishuMessage(FeishuImMsgReq req) {
    Map<String, String> feishuMsgReq = Map.of(
            "receive_type", req.getReceiveType(),
            "receive_id", req.getReceiveId(),
            "msg_type", req.getMsgType(),
            "content", req.getContent(),
            "uuid", UUID.randomUUID().toString()
            );
    // 通过spi 调用飞书租户访问令牌
    String tenantAccessToken = Informat.app().feishuTenantAccessToken();

    String url = "https://open.feishu.cn/open-apis/im/v1/messages?receive_id_type=" + req.getReceiveType();
    // 发起http请求调用飞书发送消息接口
    HttpResponse httpResp = HttpUtil.createPost(url)
            .addHeaders(Map.of(
                    "Authorization", "Bearer " + tenantAccessToken,
                    "Content-Type", "application/json; charset=utf-8"
            ))
            .body(JSON.toJSONString(feishuMsgReq)).execute();
    if (!httpResp.isOk()) {
        throw new RuntimeException(String.format("飞书发送消息网络请求失败:%s, %s", httpResp.getStatus(), httpResp.body()));
    }
    String body = httpResp.body();
    // 调用spi打印返回
    Informat.console().log("FeishuService getAppAccessToken:{}", body);
    FeishuImMessageRsp rsp = JSON.parseObject(body, FeishuImMessageRsp.class);
    Informat.console().log("rsp.Msg", rsp.getMsg());
    if (0 != rsp.getCode()) {
        Informat.console().log("FeishuService getAppAccessToken error, code:{}, msg:{}",
                rsp.getCode(), rsp.getMsg());
        throw new RuntimeException("飞书发送消息失败: " + rsp.getMsg());
    }
    // 返回返回值
    return rsp.getData();
}

本地测试调用api

在本地调用中,需要指定appId、appKey,这两个参数可在织信平台「应用管理-应用设置」中获取

java
public static void main(String[] args) {
    Informat.setServerAddress("https://next.informat.cn/web0");
    Informat.setAppId("appid");
    Informat.setApiKey("apiKey");
    FeishuImMsgReq req = new FeishuImMsgReq();
    // 飞书userId
    req.setReceiveId("xxxxxx");
    req.setReceiveType("user_id");
    req.setMsgType("text");
    req.setContent("{\"text\":\"本地RPC调用Informat Spi Plugin\"}");
    FeishuImMessageInfo msg = sendFeishuMessage(req);
    System.out.println(msg);
}

运行结果

  • 本地调用成功后打包成zip包后上传至扩展库

    上传至扩展库

  • 上传成功后,通过表达式调用扩展库

    表达式调用扩展库

  • 通过脚本调用扩展库

    脚本调用扩展库

  • 最后前往飞书查看结果

    查看结果