Skip to content

租户任务评论管理 - (IFeishuTenantV2TaskComments)

功能描述

任务评论管理接口,实现评论创建、回复、更新、删除、获取详情等功能。支持为任务创建评论或回复评论,并可以获取评论的详细信息。管理员可以通过此接口管理组织内任务的评论内容,支持分页查询和排序。该接口使用租户令牌进行认证,具有管理员权限,可以操作组织内所有任务的评论。

参考文档

https://open.feishu.cn/document/task-v2/comment/overview

函数列表

函数名称功能描述认证方式HTTP 方法
CreateCommentAsync为一个任务创建评论,或者回复该任务的某个评论租户令牌POST
GetCommentByIdAsync给定一个评论的ID,返回评论的详情,包括内容、创建人、创建时间和更新时间等信息租户令牌GET
UpdateCommentByIdAsync更新一条评论,支持部分字段更新租户令牌PATCH
DeleteCommentByIdAsync删除一条评论,删除后将无法进行任何操作,也无法恢复租户令牌DELETE
GetCommentPageListAsync给定一个资源,返回该资源的评论列表,支持分页和排序租户令牌GET

函数详细内容

创建评论

函数签名

csharp
Task<FeishuApiResult<CommentOpreationResult>?> CreateCommentAsync(
       [Body] CreateCommentRequest createCommentRequest,
       [Query("user_id_type")] string user_id_type = Consts.User_Id_Type,
       CancellationToken cancellationToken = default);

认证:租户令牌

参数

  • createCommentRequest (CreateCommentRequest): 创建评论请求体,包含评论内容、关联资源信息等
  • user_id_type (string): 用户ID类型,默认值为Consts.User_Id_Type
  • cancellationToken (CancellationToken): 取消操作令牌对象

响应

json
{
  "code": 0,
  "data": {
    "comment": {
      "comment_id": "7198104824246747156",
      "resource_id": "d300a75f-c56a-4be9-80d1-e47653028ceb",
      "resource_type": "task",
      "content": "这是一个管理员评论",
      "created": "2024-01-01T10:00:00Z",
      "updated": "2024-01-01T10:00:00Z",
      "reply_to_comment_id": null,
      "create_user": {
        "user_id": "admin_123",
        "name": "管理员",
        "email": "admin@example.com"
      }
    }
  },
  "msg": "success"
}

说明:为一个任务创建评论,或者回复该任务的某个评论。若要创建一个回复评论,需要在创建时设置reply_to_comment_id字段。被回复的评论和新建的评论必须属于同一个任务。

代码示例

typescript
// 创建新评论
const createCommentRequest = {
  resource_id: "d300a75f-c56a-4be9-80d1-e47653028ceb",
  resource_type: "task",
  content: "管理员备注:这个任务需要优先处理,请相关成员尽快跟进。"
};

const response = await feishuTenantClient.createComment(createCommentRequest);
console.log("管理员评论创建成功:", response.data.comment);

// 创建回复评论
const createReplyRequest = {
  resource_id: "d300a75f-c56a-4be9-80d1-e47653028ceb",
  resource_type: "task",
  content: "已收到通知,正在安排相关人员处理。",
  reply_to_comment_id: "7198104824246747156"
};

const replyResponse = await feishuTenantClient.createComment(createReplyRequest);
console.log("管理员评论回复成功:", replyResponse.data.comment);

// 批量创建评论(例如:为多个任务添加相同的注意事项)
async function addAdminNoticeToTasks(taskIds: string[], notice: string) {
  const results = [];
  
  for (const taskId of taskIds) {
    try {
      const request = {
        resource_id: taskId,
        resource_type: "task",
        content: `【管理员通知】${notice}`
      };
      
      const response = await feishuTenantClient.createComment(request);
      results.push({
        taskId: taskId,
        success: true,
        commentId: response.data.comment.comment_id
      });
      
      console.log(`任务 ${taskId} 添加通知成功`);
      
    } catch (error) {
      results.push({
        taskId: taskId,
        success: false,
        error: error.message
      });
      
      console.log(`任务 ${taskId} 添加通知失败: ${error.message}`);
    }
  }
  
  return results;
}

// 使用批量添加功能
const taskIds = ["task_1", "task_2", "task_3"];
const notice = "请在本周内完成进度更新,如有问题请及时反馈。";
const results = await addAdminNoticeToTasks(taskIds, notice);

console.log("批量添加结果:", results);
const successCount = results.filter(r => r.success).length;
console.log(`成功添加 ${successCount}/${taskIds.length} 个任务的通知`);

获取评论详情

函数签名

csharp
Task<FeishuApiResult<CommentOpreationResult>?> GetCommentByIdAsync(
      [Path] string comment_id,
      [Query("user_id_type")] string user_id_type = Consts.User_Id_Type,
      CancellationToken cancellationToken = default);

认证:租户令牌

参数

  • comment_id (string): 要获取评论详情的评论ID,示例值:"7198104824246747156"
  • user_id_type (string): 用户ID类型,默认值为Consts.User_Id_Type
  • cancellationToken (CancellationToken): 取消操作令牌对象

响应

json
{
  "code": 0,
  "data": {
    "comment": {
      "comment_id": "7198104824246747156",
      "resource_id": "d300a75f-c56a-4be9-80d1-e47653028ceb",
      "resource_type": "task",
      "content": "这是一个管理员评论",
      "created": "2024-01-01T10:00:00Z",
      "updated": "2024-01-01T15:30:00Z",
      "reply_to_comment_id": null,
      "create_user": {
        "user_id": "admin_123",
        "name": "管理员",
        "email": "admin@example.com"
      }
    }
  },
  "msg": "success"
}

说明:给定一个评论的ID,返回评论的详情,包括内容,创建人,创建时间和更新时间等信息。

代码示例

typescript
const response = await feishuTenantClient.getCommentById("7198104824246747156");
const comment = response.data.comment;

console.log("管理员评论详情:");
console.log(`评论ID: ${comment.comment_id}`);
console.log(`内容: ${comment.content}`);
console.log(`创建者: ${comment.create_user.name} (${comment.create_user.email})`);
console.log(`创建时间: ${comment.created}`);
console.log(`更新时间: ${comment.updated}`);
console.log(`所属任务: ${comment.resource_id}`);
console.log(`是否为回复: ${comment.reply_to_comment_id ? '是' : '否'}`);

// 检查评论是否被编辑过
const createdTime = new Date(comment.created);
const updatedTime = new Date(comment.updated);
const wasEdited = updatedTime > createdTime;

if (wasEdited) {
  const editDuration = updatedTime.getTime() - createdTime.getTime();
  const editMinutes = Math.floor(editDuration / (1000 * 60));
  console.log(`评论已被编辑过,编辑时间距离创建: ${editMinutes} 分钟`);
} else {
  console.log("评论未被编辑");
}

// 批量获取多个评论的详情
async function getMultipleCommentDetails(commentIds: string[]) {
  const commentDetails = [];
  
  for (const commentId of commentIds) {
    try {
      const response = await feishuTenantClient.getCommentById(commentId);
      const comment = response.data.comment;
      
      commentDetails.push({
        commentId: commentId,
        success: true,
        content: comment.content,
        author: comment.create_user.name,
        createdAt: comment.created,
        isEdited: new Date(comment.updated) > new Date(comment.created)
      });
      
    } catch (error) {
      commentDetails.push({
        commentId: commentId,
        success: false,
        error: error.message
      });
    }
  }
  
  return commentDetails;
}

// 使用批量获取功能
const commentIds = ["comment_1", "comment_2", "comment_3"];
const details = await getMultipleCommentDetails(commentIds);

console.log("批量评论详情:");
details.forEach(detail => {
  if (detail.success) {
    console.log(`${detail.author}: ${detail.content} (${detail.createdAt})`);
    if (detail.isEdited) console.log("  [已编辑]");
  } else {
    console.log(`评论 ${detail.commentId} 获取失败: ${detail.error}`);
  }
});

更新评论

函数签名

csharp
Task<FeishuApiResult<CommentOpreationResult>?> UpdateCommentByIdAsync(
      [Path] string comment_id,
      [Body] UpdateCommentRequest updateCommentRequest,
      [Query("user_id_type")] string user_id_type = Consts.User_Id_Type,
      CancellationToken cancellationToken = default);

认证:租户令牌

参数

  • comment_id (string): 要更新评论详情的评论ID,示例值:"7198104824246747156"
  • updateCommentRequest (UpdateCommentRequest): 更新评论请求体
  • user_id_type (string): 用户ID类型,默认值为Consts.User_Id_Type
  • cancellationToken (CancellationToken): 取消操作令牌对象

响应

json
{
  "code": 0,
  "data": {
    "comment": {
      "comment_id": "7198104824246747156",
      "resource_id": "d300a75f-c56a-4be9-80d1-e47653028ceb",
      "resource_type": "task",
      "content": "更新后的管理员评论内容",
      "created": "2024-01-01T10:00:00Z",
      "updated": "2024-01-01T16:45:00Z",
      "reply_to_comment_id": null,
      "create_user": {
        "user_id": "admin_123",
        "name": "管理员",
        "email": "admin@example.com"
      }
    }
  },
  "msg": "success"
}

说明:更新一条评论。更新时,将update_fields字段中填写所有要修改的评论的字段名,同时在comment字段中填写要修改的字段的新值即可。

代码示例

typescript
const updateCommentRequest = {
  update_fields: ["content"],
  comment: {
    content: "管理员更新:此任务状态已变更为进行中,预计3天内完成。"
  }
};

const response = await feishuTenantClient.updateCommentById(
  "7198104824246747156",
  updateCommentRequest
);

const updatedComment = response.data.comment;
console.log("管理员评论更新成功:", updatedComment.content);
console.log("更新时间:", updatedComment.updated);

// 批量更新评论(例如:为多个评论添加统一前缀)
async function addAdminPrefixToComments(commentIds: string[], prefix: string) {
  const results = [];
  
  for (const commentId of commentIds) {
    try {
      // 1. 先获取原评论内容
      const originalResponse = await feishuTenantClient.getCommentById(commentId);
      const originalContent = originalResponse.data.comment.content;
      
      // 2. 检查是否已经有前缀,避免重复添加
      if (originalContent.startsWith(prefix)) {
        results.push({
          commentId: commentId,
          success: true,
          action: "skipped",
          reason: "已包含指定前缀"
        });
        continue;
      }
      
      // 3. 添加前缀并更新
      const newContent = `${prefix}${originalContent}`;
      const updateRequest = {
        update_fields: ["content"],
        comment: {
          content: newContent
        }
      };
      
      await feishuTenantClient.updateCommentById(commentId, updateRequest);
      
      results.push({
        commentId: commentId,
        success: true,
        action: "updated",
        originalContent: originalContent,
        newContent: newContent
      });
      
      console.log(`评论 ${commentId} 已添加前缀`);
      
    } catch (error) {
      results.push({
        commentId: commentId,
        success: false,
        error: error.message
      });
      
      console.log(`评论 ${commentId} 更新失败: ${error.message}`);
    }
  }
  
  return results;
}

// 使用批量更新功能
const commentIds = ["comment_1", "comment_2", "comment_3"];
const adminPrefix = "【管理员注】";
const updateResults = await addAdminPrefixToComments(commentIds, adminPrefix);

console.log("批量更新结果:");
updateResults.forEach(result => {
  if (result.success) {
    console.log(`评论 ${result.commentId}: ${result.action}`);
    if (result.action === "updated") {
      console.log(`  原内容: ${result.originalContent}`);
      console.log(`  新内容: ${result.newContent}`);
    }
  } else {
    console.log(`评论 ${result.commentId} 更新失败: ${result.error}`);
  }
});

// 紧急更新所有包含特定关键词的评论
async function emergencyUpdateCommentsByKeyword(taskId: string, keyword: string, newContent: string) {
  try {
    // 1. 获取任务的所有评论
    const commentsResponse = await feishuTenantClient.getCommentPageList({
      resource_id: taskId,
      page_size: 100
    });
    
    // 2. 筛选包含关键词的评论
    const targetComments = commentsResponse.data.items.filter(
      comment => comment.content.includes(keyword)
    );
    
    console.log(`找到 ${targetComments.length} 个包含关键词 "${keyword}" 的评论`);
    
    // 3. 批量更新
    let updateCount = 0;
    for (const comment of targetComments) {
      try {
        const updateRequest = {
          update_fields: ["content"],
          comment: {
            content: newContent
          }
        };
        
        await feishuTenantClient.updateCommentById(comment.comment_id, updateRequest);
        console.log(`已更新评论: ${comment.comment_id}`);
        updateCount++;
        
      } catch (error) {
        console.log(`更新评论 ${comment.comment_id} 失败: ${error.message}`);
      }
    }
    
    console.log(`紧急更新完成: 成功更新 ${updateCount}/${targetComments.length} 个评论`);
    return { total: targetComments.length, updated: updateCount };
    
  } catch (error) {
    console.error("紧急更新评论失败:", error);
    return { total: 0, updated: 0 };
  }
}

// 使用紧急更新功能
const emergencyResult = await emergencyUpdateCommentsByKeyword(
  "d300a75f-c56a-4be9-80d1-e47653028ceb",
  "紧急",
  "【管理员】此信息已过时,请查看最新的任务更新。"
);

删除评论

函数签名

csharp
Task<FeishuNullDataApiResult?> DeleteCommentByIdAsync(
   [Path] string comment_id,
   [Query("user_id_type")] string user_id_type = Consts.User_Id_Type,
   CancellationToken cancellationToken = default);

认证:租户令牌

参数

  • comment_id (string): 要删除评论详情的评论ID,示例值:"7198104824246747156"
  • user_id_type (string): 用户ID类型,默认值为Consts.User_Id_Type
  • cancellationToken (CancellationToken): 取消操作令牌对象

响应

json
{
  "code": 0,
  "data": null,
  "msg": "success"
}

说明:删除一条评论。评论被删除后,将无法进行任何操作,也无法恢复,请谨慎操作。

代码示例

typescript
// 安全删除管理员评论:先查看详情,确认后删除
async function safeDeleteAdminComment(commentId: string) {
  try {
    // 1. 获取评论详情
    const detailResponse = await feishuTenantClient.getCommentById(commentId);
    const comment = detailResponse.data.comment;
    
    // 2. 显示评论信息供确认
    console.log("准备删除管理员评论:");
    console.log(`评论ID: ${comment.comment_id}`);
    console.log(`内容: ${comment.content}`);
    console.log(`创建者: ${comment.create_user.name}`);
    console.log(`创建时间: ${comment.created}`);
    console.log(`所属任务: ${comment.resource_id}`);
    
    // 3. 确认删除(在实际应用中应显示确认对话框)
    const confirmed = confirm(`确定要删除这条管理员评论吗?\n内容: ${comment.content.substring(0, 50)}...`);
    
    if (confirmed) {
      // 4. 执行删除操作
      const deleteResponse = await feishuTenantClient.deleteCommentById(commentId);
      
      if (deleteResponse.code === 0) {
        console.log(`管理员评论删除成功: ${comment.comment_id}`);
        
        // 记录删除日志
        const deletionLog = {
          commentId: commentId,
          content: comment.content,
          author: comment.create_user.name,
          deletedAt: new Date().toISOString(),
          deletedBy: "管理员操作"
        };
        console.log("删除日志:", deletionLog);
        
        return true;
      } else {
        console.log(`删除失败: ${deleteResponse.msg}`);
        return false;
      }
    } else {
      console.log("取消删除操作");
      return false;
    }
    
  } catch (error) {
    console.log(`删除管理员评论失败: ${error.message}`);
    return false;
  }
}

// 使用安全删除功能
const deleteResult = await safeDeleteAdminComment("7198104824246747156");

// 批量清理不当评论
async function cleanupInappropriateComments(taskId: string, inappropriateWords: string[]) {
  try {
    // 1. 获取任务的所有评论
    const commentsResponse = await feishuTenantClient.getCommentPageList({
      resource_id: taskId,
      page_size: 100
    });
    
    // 2. 筛选包含不当词汇的评论
    const inappropriateComments = commentsResponse.data.items.filter(comment => {
      return inappropriateWords.some(word => comment.content.toLowerCase().includes(word.toLowerCase()));
    });
    
    if (inappropriateComments.length === 0) {
      console.log("未发现包含不当词汇的评论");
      return { total: 0, deleted: 0 };
    }
    
    console.log(`发现 ${inappropriateComments.length} 条包含不当词汇的评论:`);
    inappropriateComments.forEach(comment => {
      console.log(`- ${comment.content.substring(0, 50)}... (作者: ${comment.create_user.name})`);
    });
    
    // 3. 确认批量删除
    const confirmed = confirm(`确定要删除这 ${inappropriateComments.length} 条不当评论吗?此操作不可恢复。`);
    
    if (!confirmed) {
      console.log("用户取消了批量删除操作");
      return { total: inappropriateComments.length, deleted: 0 };
    }
    
    // 4. 执行批量删除
    let deletedCount = 0;
    for (const comment of inappropriateComments) {
      try {
        await feishuTenantClient.deleteCommentById(comment.comment_id);
        console.log(`已删除不当评论: ${comment.comment_id}`);
        deletedCount++;
      } catch (error) {
        console.log(`删除评论失败: ${comment.comment_id}, 错误: ${error.message}`);
      }
    }
    
    console.log(`评论清理完成: 成功删除 ${deletedCount}/${inappropriateComments.length} 条评论`);
    return { total: inappropriateComments.length, deleted: deletedCount };
    
  } catch (error) {
    console.error("清理不当评论失败:", error);
    return { total: 0, deleted: 0 };
  }
}

// 使用清理功能
const cleanupWords = ["spam", "广告", "垃圾信息"];
const cleanupResult = await cleanupInappropriateComments(
  "d300a75f-c56a-4be9-80d1-e47653028ceb",
  cleanupWords
);

console.log(`清理结果: 发现 ${cleanupResult.total} 条,删除 ${cleanupResult.deleted} 条`);

获取评论列表

函数签名

csharp
Task<FeishuApiPageListResult<TaskCommentInfo>?> GetCommentPageListAsync(
     [Query("resource_id")] string? resource_id = null,
     [Query("resource_type")] string? resource_type = "task",
     [Query("direction")] string? direction = "asc",
     [Query("page_size")] int page_size = 10,
     [Query("page_token")] string? page_token = null,
     [Query("user_id_type")] string user_id_type = Consts.User_Id_Type,
     CancellationToken cancellationToken = default);

认证:租户令牌

参数

  • resource_id (string): 要获取评论的资源ID,例如任务全局唯一ID,示例值:"d300a75f-c56a-4be9-80d1-e47653028ceb"
  • resource_type (string): 要获取评论列表的资源类型,目前只支持"task",默认为"task",示例值:"task"
  • direction (string): 返回数据的排序方式,"asc"表示从最老到最新顺序返回;"desc"表示从最新到最老顺序返回。默认为"asc"
  • page_size (int): 分页大小,默认值:10
  • page_token (string): 分页标记,第一次请求不填
  • user_id_type (string): 用户ID类型,默认值为Consts.User_Id_Type
  • cancellationToken (CancellationToken): 取消操作令牌对象

响应

json
{
  "code": 0,
  "data": {
    "items": [
      {
        "comment_id": "7198104824246747156",
        "resource_id": "d300a75f-c56a-4be9-80d1-e47653028ceb",
        "resource_type": "task",
        "content": "管理员评论内容",
        "created": "2024-01-01T10:00:00Z",
        "updated": "2024-01-01T10:00:00Z",
        "reply_to_comment_id": null,
        "create_user": {
          "user_id": "admin_123",
          "name": "管理员",
          "email": "admin@example.com"
        }
      }
    ],
    "page_token": "next_page_token",
    "has_more": true
  },
  "msg": "success"
}

说明:给定一个资源,返回该资源的评论列表。支持分页。评论可以按照创建时间的正序(asc, 从最老到最新),或者逆序(desc,从最老到最新),返回数据。

代码示例

typescript
// 获取任务的所有评论(按时间正序)
const response = await feishuTenantClient.getCommentPageList({
  resource_id: "d300a75f-c56a-4be9-80d1-e47653028ceb",
  resource_type: "task",
  direction: "asc",
  page_size: 20
});

const comments = response.data.items;
console.log(`获取到 ${comments.length} 条评论:`);
comments.forEach((comment, index) => {
  console.log(`${index + 1}. ${comment.create_user.name}: ${comment.content} (${comment.created})`);
  if (comment.reply_to_comment_id) {
    console.log(`   [回复评论: ${comment.reply_to_comment_id}]`);
  }
});

// 分页获取所有评论
async function getAllComments(taskId: string, direction: string = "asc") {
  let pageToken: string | undefined = undefined;
  let allComments = [];
  
  do {
    const pageResponse = await feishuTenantClient.getCommentPageList({
      resource_id: taskId,
      resource_type: "task",
      direction: direction,
      page_size: 100,
      page_token: pageToken
    });
    
    allComments.push(...pageResponse.data.items);
    pageToken = pageResponse.data.page_token;
    
    console.log(`已获取 ${allComments.length} 条评论...`);
  } while (pageToken);
  
  return allComments;
}

// 评论统计分析
async function analyzeTaskComments(taskId: string) {
  const allComments = await getAllComments(taskId);
  
  if (allComments.length === 0) {
    console.log("该任务暂无评论");
    return null;
  }
  
  // 基础统计
  const analysis = {
    totalComments: allComments.length,
    uniqueAuthors: [...new Set(allComments.map(c => c.create_user.user_id))].length,
    dateRange: {
      earliest: new Date(Math.min(...allComments.map(c => new Date(c.created).getTime()))),
      latest: new Date(Math.max(...allComments.map(c => new Date(c.created).getTime())))
    },
    replies: allComments.filter(c => c.reply_to_comment_id !== null).length,
    editedComments: allComments.filter(c => new Date(c.updated) > new Date(c.created)).length
  };
  
  // 按作者统计
  const authorStats = allComments.reduce((acc, comment) => {
    const authorId = comment.create_user.user_id;
    const authorName = comment.create_user.name;
    
    if (!acc[authorId]) {
      acc[authorId] = {
        name: authorName,
        commentCount: 0,
        replyCount: 0,
        editedCount: 0
      };
    }
    
    acc[authorId].commentCount++;
    if (comment.reply_to_comment_id) acc[authorId].replyCount++;
    if (new Date(comment.updated) > new Date(comment.created)) acc[authorId].editedCount++;
    
    return acc;
  }, {});
  
  // 按日期统计
  const dateStats = allComments.reduce((acc, comment) => {
    const date = new Date(comment.created).toLocaleDateString();
    acc[date] = (acc[date] || 0) + 1;
    return acc;
  }, {});
  
  console.log("任务评论分析结果:");
  console.log(`总评论数: ${analysis.totalComments}`);
  console.log(`参与人数: ${analysis.uniqueAuthors}`);
  console.log(`时间范围: ${analysis.dateRange.earliest.toLocaleDateString()} 至 ${analysis.dateRange.latest.toLocaleDateString()}`);
  console.log(`回复评论数: ${analysis.replies}`);
  console.log(`编辑过的评论数: ${analysis.editedComments}`);
  
  console.log("\n按作者统计:");
  Object.values(authorStats).forEach(author => {
    console.log(`${author.name}: ${author.commentCount} 条评论 (${author.replyCount} 条回复, ${author.editedCount} 条已编辑)`);
  });
  
  console.log("\n按日期统计:");
  Object.entries(dateStats).forEach(([date, count]) => {
    console.log(`${date}: ${count} 条评论`);
  });
  
  return {
    analysis: analysis,
    authorStats: authorStats,
    dateStats: dateStats,
    allComments: allComments
  };
}

// 使用分析功能
const commentAnalysis = await analyzeTaskComments("d300a75f-c56a-4be9-80d1-e47653028ceb");

// 查找特定用户的评论
function findCommentsByUser(comments: any[], userId: string) {
  return comments.filter(comment => comment.create_user.user_id === userId);
}

// 查找管理员的所有评论
if (commentAnalysis) {
  const adminComments = findCommentsByUser(commentAnalysis.allComments, "admin_123");
  console.log(`管理员共有 ${adminComments.length} 条评论`);
  
  // 查找包含特定关键词的评论
  const keyword = "重要";
  const keywordComments = commentAnalysis.allComments.filter(
    comment => comment.content.includes(keyword)
  );
  console.log(`包含关键词 "${keyword}" 的评论: ${keywordComments.length} 条`);
  
  keywordComments.forEach(comment => {
    console.log(`- ${comment.create_user.name}: ${comment.content}`);
  });
}

管理员评论管理最佳实践

管理员评论监控系统

typescript
class AdminCommentManager {
  private tenantClient: any;
  
  constructor(tenantClient: any) {
    this.tenantClient = tenantClient;
  }
  
  // 监控所有任务的评论活动
  async monitorTaskComments(taskIds: string[]): Promise<any> {
    const monitoringResults = [];
    
    for (const taskId of taskIds) {
      try {
        const analysis = await this.analyzeTaskComments(taskId);
        monitoringResults.push({
          taskId: taskId,
          success: true,
          analysis: analysis
        });
      } catch (error) {
        monitoringResults.push({
          taskId: taskId,
          success: false,
          error: error.message
        });
      }
    }
    
    return monitoringResults;
  }
  
  // 分析单个任务的评论
  private async analyzeTaskComments(taskId: string) {
    const allComments = await this.getAllComments(taskId);
    
    return {
      totalComments: allComments.length,
      uniqueAuthors: [...new Set(allComments.map(c => c.create_user.user_id))].length,
      recentActivity: this.getRecentActivity(allComments),
      suspiciousContent: this.detectSuspiciousContent(allComments),
      engagementLevel: this.calculateEngagementLevel(allComments)
    };
  }
  
  // 获取所有评论
  private async getAllComments(taskId: string) {
    let pageToken: string | undefined = undefined;
    let allComments = [];
    
    do {
      const response = await this.tenantClient.getCommentPageList({
        resource_id: taskId,
        page_size: 100,
        page_token: pageToken
      });
      
      allComments.push(...response.data.items);
      pageToken = response.data.page_token;
    } while (pageToken);
    
    return allComments;
  }
  
  // 获取最近活动
  private getRecentActivity(comments: any[], hours: number = 24) {
    const cutoffTime = new Date();
    cutoffTime.setHours(cutoffTime.getHours() - hours);
    
    return comments.filter(comment => new Date(comment.created) > cutoffTime);
  }
  
  // 检测可疑内容
  private detectSuspiciousContent(comments: any[]) {
    const suspiciousKeywords = ["spam", "广告", "垃圾", "违规"];
    const suspiciousComments = comments.filter(comment => {
      return suspiciousKeywords.some(keyword => 
        comment.content.toLowerCase().includes(keyword.toLowerCase())
      );
    });
    
    return suspiciousComments;
  }
  
  // 计算参与度
  private calculateEngagementLevel(comments: any[]) {
    const totalComments = comments.length;
    const replies = comments.filter(c => c.reply_to_comment_id !== null).length;
    const uniqueAuthors = [...new Set(comments.map(c => c.create_user.user_id))].length;
    
    if (totalComments === 0) return 'none';
    if (totalComments < 5) return 'low';
    if (totalComments < 20) return 'medium';
    return 'high';
  }
  
  // 批量管理员操作
  async performAdminActions(taskIds: string[], action: string, params?: any): Promise<any> {
    const results = [];
    
    for (const taskId of taskIds) {
      try {
        switch (action) {
          case 'addNotice':
            const noticeResult = await this.addAdminNotice(taskId, params.message);
            results.push({ taskId, success: true, result: noticeResult });
            break;
            
          case 'cleanup':
            const cleanupResult = await this.cleanupComments(taskId, params.keywords);
            results.push({ taskId, success: true, result: cleanupResult });
            break;
            
          default:
            throw new Error(`未知的管理操作: ${action}`);
        }
      } catch (error) {
        results.push({ taskId, success: false, error: error.message });
      }
    }
    
    return results;
  }
  
  // 添加管理员通知
  private async addAdminNotice(taskId: string, message: string) {
    const request = {
      resource_id: taskId,
      resource_type: "task",
      content: `【管理员通知】${message}`
    };
    
    const response = await this.tenantClient.createComment(request);
    return response.data.comment;
  }
  
  // 清理评论
  private async cleanupComments(taskId: string, keywords: string[]) {
    const comments = await this.getAllComments(taskId);
    const targetComments = comments.filter(comment => 
      keywords.some(keyword => comment.content.includes(keyword))
    );
    
    let deletedCount = 0;
    for (const comment of targetComments) {
      try {
        await this.tenantClient.deleteCommentById(comment.comment_id);
        deletedCount++;
      } catch (error) {
        console.log(`删除评论失败: ${comment.comment_id}`);
      }
    }
    
    return { found: targetComments.length, deleted: deletedCount };
  }
}

// 使用管理员评论管理系统
const adminCommentManager = new AdminCommentManager(feishuTenantClient);

// 监控多个任务的评论活动
const taskIds = ["task_1", "task_2", "task_3"];
const monitoringResults = await adminCommentManager.monitorTaskComments(taskIds);

console.log("评论监控结果:");
monitoringResults.forEach(result => {
  if (result.success) {
    const analysis = result.analysis;
    console.log(`任务 ${result.taskId}:`);
    console.log(`- 总评论: ${analysis.totalComments}`);
    console.log(`- 参与人数: ${analysis.uniqueAuthors}`);
    console.log(`- 参与度: ${analysis.engagementLevel}`);
    console.log(`- 最近24小时活动: ${analysis.recentActivity.length} 条`);
    console.log(`- 可疑内容: ${analysis.suspiciousContent.length} 条`);
  } else {
    console.log(`任务 ${result.taskId} 监控失败: ${result.error}`);
  }
});

// 批量添加管理员通知
const noticeResults = await adminCommentManager.performAdminActions(taskIds, 'addNotice', {
  message: "请在本周五前完成所有待处理任务,逾期将影响项目进度。"
});

console.log("批量添加通知结果:");
noticeResults.forEach(result => {
  if (result.success) {
    console.log(`任务 ${result.taskId}: 通知添加成功`);
  } else {
    console.log(`任务 ${result.taskId}: 通知添加失败 - ${result.error}`);
  }
});