飞书推送文件给指定用户

首先要先把文件上传到飞书服务器,获取文件key 。然后调用消息发送API进行文件推送

java 复制代码
        // 上传文件
        String fileKey = uploadFileToFeishu();
        // 将文件推送给用户列表
        sendFileToFeishuUserId(fileKey,userList);
java 复制代码
    /**
     *  上传文件到飞书云端
     * @return
     * @throws Exception
     */
    private String uploadFileToFeishu() throws Exception {
        // 构建client
        Client client = Client.newBuilder("xxx", "xxxxx").build();

        // 创建请求对象
        File file = new File("user_info.xlsx");    //这里填本地文件路径。
        CreateFileReq req = CreateFileReq.newBuilder()
                .createFileReqBody(CreateFileReqBody.newBuilder()
                        .fileType("xls")
                        .fileName("文件名称XXX.xlsx")
                        .duration(3000)
                        .file(file)
                        .build())
                .build();

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

        // 处理服务端错误
        if (!resp.success()) {
            System.out.println(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 null;
        }

        // 业务数据处理
//        System.out.println(Jsons.DEFAULT.toJson(resp.getData()));
        return resp.getData().getFileKey();
    }
java 复制代码
    /**
     * 发送文件给飞书的指定用户
     * @param fileKey   文件key
     * @param userList  用户列表
     * @throws Exception    异常
     */
    private void sendFileToFeishuUserId(String fileKey, List<String> userList) throws Exception {
        // 构建client
        Client client = Client.newBuilder("xxx", "xxx").build();

        for(String userId : userList) {
            // 创建请求对象
            CreateMessageReq req = CreateMessageReq.newBuilder()
                    .receiveIdType("user_id")
                    .createMessageReqBody(CreateMessageReqBody.newBuilder()
                            .receiveId(userId)
                            .msgType("file")
                            .content("{\"file_key\":\"" +fileKey +"\"}")
                            .build())
                    .build();

            // 发起请求
            client.im().v1().message().create(req);
        }



    }
相关推荐
gf13211116 小时前
【python_往飞书群或者话题下发送卡片和发送文件】
java·python·飞书
AppOS1 天前
手把手教你 Openclaw 在 Mac 上本地化部署,保姆级教程!接入飞书打造私人 AI 助手
人工智能·macos·飞书
算家云1 天前
OpenClaw进阶玩法:多飞书机器人部署指南
人工智能·飞书·openclaw
70asunflower1 天前
OpenClaw 飞书机器人集成完全指南
飞书·openclaw·小龙虾
gf13211111 天前
【python_使用指定应用发送飞书卡片】
java·python·飞书
正经教主2 天前
【可接入openclaw】飞书开放平台创建应用及机器人
飞书
CHQIUU2 天前
OpenClaw 飞书配对、QQ 插件升级与全局依赖补全:踩坑记录与处理办法
飞书
小~小2 天前
【OpenClaw】 多 Agents 配置详细教程:从单兵作战到团队协作,飞书掌握多 Agent 协作
飞书·openclaw