管理评论和回复

评论 是用户针对文件提供的反馈,例如字处理文档的读者建议如何改写句子。评论分为两种类型:锚定评论非锚定评论 。锚定评论与特定文档版本的特定位置(例如字处理文档中的句子)相关联。相反,非锚定评论仅与文档相关联。

回复 附加到评论,表示用户对评论的回应。借助 Google Drive API,您的用户可以向应用创建的文档添加评论和回复。评论和回复统称为 讨论

使用 fields 参数

对于 comments 资源的所有方法(delete 除外),您 必须 设置 fields system parameter,以 指定要在响应中返回的字段。在大多数 Drive 资源方法中,此操作仅在返回非默认字段时是必需的,但对于 comments 资源,此操作是强制性的。如果您省略 fields 参数,该方法会返回错误。如需了解详情,请参阅返回特定字段

评论限制

使用 Drive API 处理锚定评论和非锚定评论时,系统会强制执行以下限制:

评论类型 文件类型
锚定
  • 开发者可以为锚点 规范定义自己的格式。
  • 检索评论时,系统会保存并返回锚点, 但 Google Workspace 编辑器应用会将这些评论视为 非锚定评论。
  • 在检索编辑器中创建的 Google Workspace 文件(例如 Google 文档、Google 表格或 Google 幻灯片)的评论时,anchor 字段包含编辑器特定的 内部锚点数据(例如表格文件中的 workbook-range JSON 字符串)。Drive API 将此数据视为不透明数据,无法解析内部文档区域、单元格坐标或幻灯片元素。如需直接处理这些文件类型中的锚定评论,请使用其各自的 API:Google Docs APIGoogle Sheets APIGoogle Slides API
非锚定
  • Google Workspace 文档支持此类型,并会在 "所有评论"视图中显示这些评论。
  • 非锚定评论不会显示在 Drive 文件预览器中呈现的 PDF 上,但系统会保存这些评论,并且可以通过 Drive API 检索这些评论。

添加锚定评论

添加评论时,您可能需要将其锚定到文件中的某个区域。锚点 用于定义文件中评论所引用的区域。 comments 资源将 anchor 字段定义为 JSON 字符串。

如需添加锚定评论,请执行以下操作:

  1. (可选)对 revisions 资源调用 list 方法,以列出文档的每个 revisionID。仅当您要将评论锚定到最新修订版本以外的任何修订版本时,才需要执行此步骤。如果您想使用最新修订版本,请为 revisionID 使用 head

  2. comments 资源调用 create 方法,并使用 fileId 参数、包含评论的 comments 资源以及应用定义的 JSON 锚点 字符串。

以下代码示例展示了如何创建锚定评论:

Python

import json

from google.oauth2.credentials import Credentials
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError

# --- Configuration ---
# The ID of the file to comment on.
# Example: '1_aBcDeFgHiJkLmNoPqRsTuVwXyZ'
FILE_ID = 'FILE_ID'

# The text content of the comment.
COMMENT_TEXT = 'This is an example of an anchored comment.'

# The line number in your application to anchor the comment to.
# Note: Google Workspace editor apps (such as Google Docs, Sheets, and
# Slides) treat comments created using the Drive API as unanchored
# comments. Custom anchors are intended for your own applications or
# custom file viewers.
ANCHOR_LINE = 10
# --- End of user-configuration section ---

SCOPES = ["https://www.googleapis.com/auth/drive"]

creds = Credentials.from_authorized_user_file("token.json", SCOPES)

def create_anchored_comment():
    """
    Create an anchored comment with a custom application-defined anchor.

    Returns:
        The created comment object or None if an error occurred.
    """
    try:
        # Build the Drive API service
        service = build("drive", "v3", credentials=creds)

        # Define a custom anchor specification for your application.
        # The Drive API stores the anchor as an opaque string. Your custom
        # application or file viewer can parse this JSON string to position
        # the comment in your UI.
        anchor_data = {
            'line': ANCHOR_LINE,
            'revision': 'head'
        }

        # The comment body. The 'anchor' field must be a serialized
        # JSON string.
        comment_body = {
            'content': COMMENT_TEXT,
            'anchor': json.dumps(anchor_data)
        }

        # Create the comment request.
        comment = (
            service.comments()
            .create(fileId=FILE_ID, fields="*", body=comment_body)
            .execute()
        )

        print(f"Comment ID: {comment.get('id')}")
        return comment

    except HttpError as error:
        print(f"An error occurred: {error}")
        return None

create_anchored_comment()

Drive API 会返回 comments 资源对象的实例,其中包含 anchor 字符串。

添加非锚定评论

如需添加非锚定评论,请使用 fileId 参数和包含评论的 comments 资源调用 create 方法。

评论以纯文本形式插入,但响应正文提供了一个 htmlContent字段 ,其中包含格式化以供显示的内容。

以下代码示例展示了如何创建非锚定评论:

Python


from google.oauth2.credentials import Credentials
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError

# --- Configuration ---
# The ID of the file to comment on.
# Example: '1_aBcDeFgHiJkLmNoPqRsTuVwXyZ'
FILE_ID = 'FILE_ID'

# The text content of the comment.
COMMENT_TEXT = 'This is an example of an unanchored comment.'
# --- End of user-configuration section ---

SCOPES = ["https://www.googleapis.com/auth/drive"]

creds = Credentials.from_authorized_user_file("token.json", SCOPES)

def create_unanchored_comment():
    """
    Create an unanchored comment on a file in Drive.

    Returns:
        The created comment object or None if an error occurred.
    """
    try:
        # Build the Drive API service
        service = build("drive", "v3", credentials=creds)

        # The comment body. For an unanchored comment,
        # omit the 'anchor' property.
        comment_body = {
            'content': COMMENT_TEXT
        }

        # Create the comment request.
        comment = (
            service.comments()
            .create(fileId=FILE_ID, fields="*", body=comment_body)
            .execute()
        )

        print(f"Comment ID: {comment.get('id')}")
        return comment

    except HttpError as error:
        print(f"An error occurred: {error}")
        return None

create_unanchored_comment()
comments

为评论添加回复

如需为评论添加回复,请对 replies资源使用 create方法,并使用fileIdcommentId参数。请求正文使用 content 字段添加回复。

回复以纯文本形式插入,但响应正文提供了一个 htmlContent 字段,其中包含格式化以供显示的内容。

该方法会返回 fields 字段中列出的字段。

请求

在此示例中,我们提供了 fileIdcommentId 路径参数以及多个字段。

POST https://www.googleapis.com/drive/v3/files/FILE_ID/comments/COMMENT_ID/replies?fields=id,comment

请求正文

{
  "content": "This is a reply to a comment."
}

解决评论

只有通过发布对评论的回复,才能解决评论。

如需解决评论,请对 replies 资源使用 create 方法,并使用 fileIdcommentId 参数。

请求正文使用 action字段来解决 评论。您还可以设置 content 字段,以添加关闭评论的回复。

解决评论后,Drive 会将 comments 资源标记为 resolved: true。与已删除的评论不同,已解决 的评论可以包含 htmlContentcontent 字段。

当您的应用解决评论时,界面应指明评论已得到处理。例如,您的应用可能会:

  • 禁止进一步回复,并使所有之前的回复以及原始评论变暗。
  • 隐藏已解决的评论。

请求

在此示例中,我们提供了 fileIdcommentId 路径参数以及多个字段。

POST https://www.googleapis.com/drive/v3/files/FILE_ID/comments/COMMENT_ID/replies?fields=id,comment

请求正文

{
  "action": "resolve",
  "content": "This comment has been resolved."
}

获取评论

如需获取文件的评论,请对 comments 资源使用 get 方法,并使用 fileIdcommentId 参数。如果您不知道评论 ID,可以使用 list all comments list方法列出所有评论。

该方法会返回 comments 资源的实例。

如需在结果中包含已删除的评论,请将 includeDeleted query parameter 设置为 true

请求

在此示例中,我们提供了 fileIdcommentId 路径参数以及多个字段。

GET https://www.googleapis.com/drive/v3/files/FILE_ID/comments/COMMENT_ID?fields=id,comment,modifiedTime,resolved

列出评论

如需列出文件的评论,请对 comments 资源使用 list 方法,并使用 fileId 参数。该方法会返回评论列表。

传递以下查询参数以自定义评论的分页或过滤评论:

  • includeDeleted:设置为 true 以包含已删除的评论。已删除的评论不包含 htmlContentcontent 字段。

  • pageSize:每页返回的评论数上限。

  • pageToken:从之前的列表调用收到的页面令牌。提供此令牌以检索后续页面。

  • startModifiedTime:结果评论的 modifiedTime 字段的最小值。

请求

在此示例中,我们提供了 fileId 路径参数、includeDeleted 查询参数以及多个字段。

GET https://www.googleapis.com/drive/v3/files/FILE_ID/comments?includeDeleted=true&fields=(id,comment,kind,modifiedTime,resolved)

更新评论

如需更新文件的评论,请对 comments 资源使用 update 方法,并使用 fileIdcommentId 参数。请求正文使用 content 字段更新评论。

布尔值 resolved 字段在 comments 资源中是只读的。只有通过发布对评论的回复,才能解决评论。如需了解详情,请参阅解决 评论

该方法会返回 fields 查询参数中列出的字段。

请求

在此示例中,我们提供了 fileIdcommentId 路径参数以及多个字段。

PATCH https://www.googleapis.com/drive/v3/files/FILE_ID/comments/COMMENT_ID?fields=id,comment

请求正文

{
  "content": "This comment is now updated."
}

删除评论

如需删除文件的评论,请对comments资源使用 delete方法,并使用fileIdcommentId 参数。

删除评论后,Drive 会将评论资源标记为 deleted: true。已删除的评论不包含 htmlContentcontent 字段。

请求

在此示例中,我们提供了 fileIdcommentId 路径参数。

DELETE https://www.googleapis.com/drive/v3/files/FILE_ID/comments/COMMENT_ID