egg_server/routes/bot/groupAgent/groupManager.ts
zhaoyingbo b992ee0b21
Some checks failed
Egg Server MIflow / build-image (push) Failing after 5m7s
feat(group-agent): 新增支持群组问答
2024-09-25 09:14:10 +00:00

75 lines
2.1 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { getChatId, LarkAction, LarkEvent } from "@egg/lark-msg-tool"
import db from "../../../db"
import { Context } from "../../../types"
import { genGroupAgentSuccessMsg } from "../../../utils/genMsg"
/**
* 发送群组选择器
* @param ctx - 上下文数据包含body和larkService
*/
const sendGroupSelector = async ({ larkService, body }: Context.Data) => {
const chatId = getChatId(body)!
const { data: innerList } = await larkService.chat.getInnerList()
// 组织群组数据
const groups = innerList.map((v) => ({
text: v.name,
value: `${v.chat_id}|${v.name}`,
}))
larkService.message.sendTemp("chat_id", chatId, "ctp_AA00oqPWPTdc", {
groups,
})
}
/**
* 获取当前群组
* @param ctx - 上下文数据包含body和larkService
*/
const getCurrentGroup = async (ctx: Context.Data, needSendMsg = true) => {
const body = ctx.body as LarkEvent.Data
const chatId = getChatId(body)!
const group = await db.groupAgentConfig.get(
body.event.sender.sender_id.user_id
)
if (!needSendMsg) return group
if (!group) {
await sendGroupSelector(ctx)
return
}
const msg = genGroupAgentSuccessMsg(`当前群组:${group.chat_name}`)
ctx.larkService.message.send("chat_id", chatId, "interactive", msg)
}
/**
* 设置群组上下文
* @param ctx - 上下文数据包含body, larkService和logger
*/
const setChatGroupContext = async (ctx: Context.Data) => {
const { larkService, logger } = ctx
const body = ctx.body as LarkAction.Data
const targetId = body?.action?.option?.split?.("|")[0]
const targetName = body?.action?.option?.split?.("|")[1]
if (!targetId || !targetName) {
logger.error(
`invalid targetId or targetName: ${JSON.stringify(body?.action)}`
)
}
// 更新群组数据
await db.groupAgentConfig.upsert({
user_id: body.user_id,
chat_id: targetId,
chat_name: targetName,
})
// 更新成功消息
const successMsg = genGroupAgentSuccessMsg(`已将群组切换至 ${targetName}`)
larkService.message.update(body.open_message_id, successMsg)
}
const groupManager = {
sendGroupSelector,
setChatGroupContext,
getCurrentGroup,
}
export default groupManager