import db from "../db"; import { MsgType, ReceiveIDType, ServerResponse } from "../types"; /** * 发送消息 * @param func fetch * @returns */ const manageFetch = async (func: Function) => { try { const res = await func(); const data = (await res.json()) as ServerResponse; console.log("🚀 ~ manageFetch ~ data:", data); return data; } catch (error) { console.log("🚀 ~ manageFetch ~ error:", error); return { code: 1, data: null, msg: "sendMsg fetch error", }; } }; /** * 获取header * @returns header */ const getHeaders = async () => { const tenant_access_token = await db.tenantAccessToken.get(); return { "Content-Type": "application/json", Authorization: `Bearer ${tenant_access_token}`, }; }; /** * 发送卡片 * @param {ReceiveIDType} receive_id_type 消息接收者id类型 open_id/user_id/union_id/email/chat_id * @param {string} receive_id 消息接收者的ID,ID类型应与查询参数receive_id_type 对应 * @param {MsgType} msg_type 消息类型 包括:text、post、image、file、audio、media、sticker、interactive、share_chat、share_user * @param {string} content 消息内容,JSON结构序列化后的字符串。不同msg_type对应不同内容 */ const sendMsg = async ( receive_id_type: ReceiveIDType, receive_id: string, msg_type: MsgType, content: string ) => { const URL = `https://open.f.mioffice.cn/open-apis/im/v1/messages?receive_id_type=${receive_id_type}`; const headers = await getHeaders(); return await manageFetch(() => fetch(URL, { method: "POST", headers, body: JSON.stringify({ receive_id, msg_type, content }), }) ); }; /** * 更新卡片 * @param {string} message_id 消息id * @param {string} content 消息内容,JSON结构序列化后的字符串。不同msg_type对应不同内容 */ const updateCard = async (message_id: string, content: string) => { const URL = `https://open.f.mioffice.cn/open-apis/im/v1/messages/${message_id}`; const headers = await getHeaders(); return await manageFetch(() => fetch(URL, { method: "PATCH", headers, body: JSON.stringify({ content }), }) ); }; /** * 发送某人可见的卡片 * @param {string} chat_id 对话流ID * @param {string} open_id 消息接收者的ID * @param {MsgType} msg_type 消息类型 包括:text、post、image、file、audio、media、sticker、interactive、share_chat、share_user * @param {*} card 消息卡片的描述内容,注意不是String */ const sendEphemeralMsg = async ( chat_id: string, open_id: string, msg_type: MsgType, card: any ) => { const URL = `https://open.f.mioffice.cn/open-apis/ephemeral/v1/send`; const headers = await getHeaders(); return await manageFetch(() => fetch(URL, { method: "POST", headers, body: JSON.stringify({ chat_id, open_id, msg_type, card }), }) ); }; /** * 删除某人可见的卡片 * @param message_id 消息id */ const delEphemeralMsg = async (message_id: string) => { const URL = `https://open.f.mioffice.cn/open-apis/ephemeral/v1/delete`; const headers = await getHeaders(); return await manageFetch(() => fetch(URL, { method: "POST", headers, body: JSON.stringify({ message_id }), }) ); }; const lark = { sendMsg, updateCard, sendEphemeralMsg, delEphemeralMsg, }; export default lark;