🎯 学习目标:学会团队协作配置:群聊管理、权限控制、消息路由
⏱️ 阅读时间:约 12 分钟
💡 前置要求:无
💬 群聊管理
添加/移除成员
使用方式
# 添加成员"把张三添加到项目群"# 移除成员"把李四从测试群移除"# 批量添加"把产品团队所有人都加到项目群"技能实现
module.exports = {name: 'chat-member-manage',asyncexecute({ chatId, action, userIds }) {try {if (action === 'add') {// 添加成员 - 符合飞书官方 API 格式awaitfeishu_chat_members('create', {chat_id: chatId,user_ids: userIds });return`✅ 已添加 ${userIds.length} 位成员到群聊`; }if (action === 'remove') {// 移除成员 - 符合飞书官方 API 格式awaitfeishu_chat_members('batch_delete', {chat_id: chatId,user_ids: userIds });return`✅ 已从群聊移除 ${userIds.length} 位成员`; } } catch (error) {if (error.code === '99991001') {return'❌ 权限不足,需要群管理员权限'; }throw error; } }};群权限配置
使用方式
# 设置群管理员"设置张三为项目群管理员"# 配置群权限"开启群聊邀请确认"# 修改群设置"关闭群聊消息免打扰"技能实现
module.exports = {name: 'chat-permission',asyncexecute({ chatId, settings }) {try {// 更新群设置 - 符合飞书官方 API 格式awaitfeishu_chat('patch', {chat_id: chatId,settings: {mention_all_permission: settings.mentionAllPermission, // @所有人权限edit_permission: settings.editPermission, // 修改群信息权限invite_permission: settings.invitePermission// 邀请权限 } });return'✅ 群权限已更新'; } catch (error) {if (error.code === '99991001') {return'❌ 权限不足,需要群主权限'; }throw error; } }};🔐 权限控制
基于角色的访问控制(RBAC)
module.exports = {name: 'rbac-manager',asyncinit() {try {// 定义角色const roles = {admin: {permissions: ['read', 'write', 'delete', 'manage_users'] },editor: {permissions: ['read', 'write'] },viewer: {permissions: ['read'] } };// 用户 - 角色映射const userRoles = newMap();return {// 分配角色assignRole: async (userId, roleId) => { userRoles.set(userId, roleId);return`✅ 已为用户 ${userId} 分配角色 ${roleId}`; },// 检查权限checkPermission: async (userId, permission) => {const roleId = userRoles.get(userId) || 'viewer';const role = roles[roleId];if (role.permissions.includes(permission)) {returntrue; }returnfalse; },// 执行权限检查的操作executeWithPermission: async (userId, permission, action) => {const hasPermission = awaitthis.checkPermission(userId, permission);if (!hasPermission) {thrownewError(`权限不足:需要 ${permission} 权限`); }returnawaitaction(); } }; } catch (error) {console.error('RBAC 初始化失败:', error);throw error; } }};群聊权限策略
module.exports = {name: 'group-policy',asyncinit() {try {// 定义群聊策略const policies = {// 只响应应用创建人 @ 机器人的消息(推荐)allowlist: {match: {channel: 'feishu',peer: { kind: 'group', id: '*' } },requireMention: true,allowFrom: ['ou_admin_id'] // 只响应特定用户的消息 },// 响应任何人 @ 机器人的消息mention: {match: {channel: 'feishu',peer: { kind: 'group', id: '*' } },requireMention: true },// 不用 @,所有消息都回复(⚠️ 大群慎用)all: {match: {channel: 'feishu',peer: { kind: 'group', id: '*' } },requireMention: false } };return policies; } catch (error) {console.error('群聊策略初始化失败:', error);throw error; } }};📨 消息路由
智能分发到不同 Agent
module.exports = {name: 'message-router',asyncexecute({ message }) {const text = message.content?.text || '';const sender = message.sender_id;const chatType = message.chat_type;// 1. 根据消息类型路由if (chatType === 'p2p') {// 私聊 → 通用助理returnawaitrouteToAgent('general-assistant', message); }if (chatType === 'group') {// 群聊 → 根据内容判断if (text.includes('技术') || text.includes('bug')) {returnawaitrouteToAgent('tech-expert', message); }if (text.includes('产品') || text.includes('需求')) {returnawaitrouteToAgent('product-expert', message); }if (text.includes('紧急') || text.includes('urgent')) {returnawaitrouteToAgent('urgent-handler', message); }// 默认群聊助理returnawaitrouteToAgent('group-assistant', message); }// 默认路由returnawaitrouteToAgent('general-assistant', message); }};// 路由到指定 AgentasyncfunctionrouteToAgent(agentId, message) {try {const result = awaitsessions_spawn({ agentId,task: `处理消息:${message.content.text}`,runtime: 'subagent' });return result; } catch (error) {console.error(`路由到 Agent ${agentId} 失败:`, error);throw error; }}基于会话状态的路由
module.exports = {name: 'session-router',asyncexecute({ message, sessionId }) {// 获取会话状态const session = awaitgetSession(sessionId);// 如果有进行中的任务,继续该任务if (session.activeTask) {returnawaitcontinueTask(session.activeTask, message); }// 否则根据内容路由returnawaitrouteByContent(message); }};🎯 实用场景
场景 1:项目群管理
module.exports = {name: 'project-group-manager',asyncinit() {try {// 项目群配置const projectGroup = {chatId: 'oc_project_xxx',name: '项目交流群',members: ['ou_1', 'ou_2', 'ou_3'],admins: ['ou_admin'],policy: 'mention'// 需要 @ 才回复 };// 创建群聊const chat = awaitfeishu_chat('create', {name: projectGroup.name,description: '项目交流群',owner_id: projectGroup.admins[0] });// 添加成员awaitfeishu_chat_members('create', {chat_id: chat.chat_id,user_ids: projectGroup.members });// 配置权限awaitfeishu_chat('patch', {chat_id: chat.chat_id,settings: {mention_all_permission: 'admin_only',edit_permission: 'admin_only',invite_permission: 'all_members' } });return`✅ 项目群已创建:${chat.name}`; } catch (error) {console.error('创建项目群失败:', error);throw error; } }};场景 2:跨部门协作
module.exports = {name: 'cross-dept-collab',asyncinit() {try {// 为每个部门创建独立会话const departments = ['产品', '技术', '设计', '运营'];for (const dept of departments) {// 创建部门群const deptChat = awaitcreateDepartmentGroup(dept);// 配置路由规则awaitconfigureRoute(deptChat.chat_id, {agentId: `${dept.toLowerCase()}-expert`,requireMention: true }); }// 创建跨部门协调群const coordChat = awaitfeishu_chat('create', {name: '跨部门协调群',description: '各部门负责人协作群' });// 配置高优先级路由awaitconfigureRoute(coordChat.chat_id, {agentId: 'coordinator',priority: 'high' });return'✅ 跨部门协作配置完成'; } catch (error) {console.error('跨部门协作配置失败:', error);throw error; } }};场景 3:值班轮换
module.exports = {name: 'duty-rotation',asyncinit() {try {// 值班表const dutyRoster = [ { date: '2026-03-21', onDuty: 'ou_1' }, { date: '2026-03-22', onDuty: 'ou_2' }, { date: '2026-03-23', onDuty: 'ou_3' } ];// 每天自动更新值班人员awaitcreateCronJob({cron: '0 9 * * *',task: async () => {const today = formatDate(newDate());const onDuty = dutyRoster.find(d => d.date === today);if (onDuty) {// 更新路由配置awaitupdateRouteConfig({onDutyUser: onDuty.onDuty });// 通知值班人员awaitsendToFeishu({receive_id: onDuty.onDuty,receive_id_type: 'open_id',content: `📋 今天是你的值班日,请留意群消息` }); } } });return'✅ 值班轮换已启用'; } catch (error) {console.error('值班轮换配置失败:', error);throw error; } }};📊 消息路由配置
路由规则优先级
peer | ||
parentPeer | ||
guildId + roles | ||
guildId | ||
teamId | ||
accountId | ||
accountId: "*" | ||
agents.list[].default |
配置示例
{ "bindings": [ // 高优先级:特定群组 { agentId: "project-team", match: { channel: "feishu", peer: { kind: "group", id: "oc_project_xxx" } } }, // 中优先级:特定用户 { agentId: "vip-assistant", match: { channel: "feishu", peer: { kind: "direct", id: "ou_vip_user" } } }, // 低优先级:所有飞书消息 { agentId: "general-assistant", match: { channel: "feishu", accountId: "*" } } ]}✅ 学完这篇你能做什么
学完 Day 18,你将能够:
✅ 管理群聊成员(添加/移除) ✅ 配置群权限(管理员、邀请权限等) ✅ 实现基于角色的访问控制(RBAC) ✅ 配置消息路由到不同 Agent ✅ 处理团队协作相关错误
🔜 下篇预告
Day 19:知识库构建:文档索引、RAG 检索、知识更新
📚 文档索引和切片 🔍 RAG 检索实现 🔄 知识自动同步
💬 互动环节
你在团队协作中遇到过什么权限管理问题?留言分享!
公众号:OpenClaw 研习社系列:OpenClaw 30 天入门到精通作者:OpenClaw 研习社
夜雨聆风