本文详解如何正确调用 Google Chat API 的 spaces.messages.list 方法获取空间消息重点解决因参数误用如错误使用 name 而非 parent导致的 AttributeError 问题并提供可运行的 Python 示例与关键注意事项。 本文详解如何正确调用 google chat api 的 spaces.messages.list 方法获取空间消息重点解决因参数误用如错误使用 name 而非 parent导致的 attributeerror 问题并提供可运行的 python 示例与关键注意事项。Google Chat API 的 spaces.messages.list 方法用于检索指定空间Space中最近的聊天消息。初学者常因混淆 REST API 文档与 Python 客户端库的参数映射而报错——典型错误是直接将 API Explorer 中的 name 字段照搬为 .list(namespaces/...)但 Python 客户端库实际要求使用 parent 参数传入空间资源路径。正确调用方式如下from google.auth.transport.requests import Requestfrom google_auth_oauthlib.flow import InstalledAppFlowfrom google.auth.credentials import Credentialsfrom googleapiclient.discovery import buildimport osdef get_messages_in_space(space_id: str) - dict: 获取指定 space 中的最新消息列表 creds None SCOPES [ https://www.googleapis.com/auth/chat.spaces.readonly, https://www.googleapis.com/auth/chat.messages.readonly ] # 加载已保存的 token if os.path.exists(token.json): creds Credentials.from_authorized_user_file(token.json, SCOPES) # 若凭证无效或过期尝试刷新或重新授权 if not creds or not creds.valid: if creds and creds.expired and creds.refresh_token: creds.refresh(Request()) else: flow InstalledAppFlow.from_client_secrets_file( credentials.json, SCOPES) creds flow.run_local_server(port0) with open(token.json, w) as token: token.write(creds.to_json()) # 构建服务客户端 chat_service build(chat, v1, credentialscreds) try: # ? 关键修正使用 parentspaces/{space_id}而非 name 参数 result chat_service.spaces().messages().list( parentfspaces/{space_id}, pageSize25 # 可选限制单次返回条数1–100 ).execute() messages result.get(messages, []) print(f共获取 {len(messages)} 条消息) for msg in messages[:5]: # 打印前5条简要信息 sender msg.get(sender, {}).get(displayName, Unknown) text msg.get(text, [无文本]) print(f- [{sender}] {text[:60]}{... if len(text) 60 else }) return result except Exception as e: print(f请求失败{e}) return {}def main(): # 替换为你的实际 Space ID例如spaces/AAAAmXyZ123 SPACE_ID spaces/AAAAmXyZ123 get_messages_in_space(SPACE_ID)重要注意事项 文心快码 文心快码Comate是百度推出的一款AI辅助编程工具