本指南介绍了如何对以下资源的 Message
资源使用 list
方法:
Google Chat API,以查看聊天室中可过滤的分页消息列表。
通过
Message
资源
代表
文本
或
卡片
消息。您可以
在 Google Chat API 中通过调用 create
、get
、update
或 delete
消息
相应的方法有关短信和卡片消息的详情,请参阅
Google Chat 消息概览。
前提条件
Python
- Business 或 Enterprise 有权访问以下内容的 Google Workspace 账号: Google Chat。
- Python 3.6 或更高版本
- pip 软件包管理工具
- 最新的 Google 客户端库。若要安装或更新这些应用
在命令行界面中运行以下命令:
pip3 install --upgrade google-api-python-client google-auth-oauthlib
- 设置您的环境:
- 创建 Google Cloud 项目。
- 配置 OAuth 权限请求页面。
- 启用并配置 Google Chat API,指定一个名称, 图标和说明。
-
为桌面应用创建 OAuth 客户端 ID 凭据。为了运行此示例中的示例,
指南中,以 JSON 文件 (
client_secrets.json
) 的形式将凭据保存到您的 本地目录中。
- 选择支持用户身份验证的授权范围。
列出消息
列出带有 用户身份验证, 请在请求中传递以下内容:
- 指定
chat.messages.readonly
或chat.messages
授权范围。 - 调用
list
方法 在Message
资源。
以下示例列出了 Chat 聊天室中发送 2023 年 3 月 16 日:
Python
- 在您的工作目录中,创建一个名为
chat_messages_list.py
的文件。 在
chat_messages_list.py
中添加以下代码:from google_auth_oauthlib.flow import InstalledAppFlow from googleapiclient.discovery import build # Define your app's authorization scopes. # When modifying these scopes, delete the file token.json, if it exists. SCOPES = ["https://www.googleapis.com/auth/chat.messages.readonly"] def main(): ''' Authenticates with Chat API via user credentials, then lists messages in a space sent after March 16, 2023. ''' # Authenticate with Google Workspace # and get user authorization. flow = InstalledAppFlow.from_client_secrets_file( 'client_secrets.json', SCOPES) creds = flow.run_local_server() # Build a service endpoint for Chat API. chat = build('chat', 'v1', credentials=creds) # Use the service endpoint to call Chat API. result = chat.spaces().messages().list( # The space for which to list messages. parent = 'spaces/SPACE', # An optional filter that returns messages # created after March 16, 2023. filter = 'createTime > "2023-03-16T00:00:00-00:00"' ).execute() # Prints the list of messages. print(result) if __name__ == '__main__': main()
在代码中,将
SPACE
替换为聊天室名称, 您可以从spaces.list
方法 或通过聊天室网址发送。在您的工作目录中,构建并运行该示例:
python3 chat_messages_list.py
Chat API 会返回在指定聊天室中发送的消息列表
2023 年 3 月 16 日之后如果请求中没有任何消息,
Chat API 响应返回一个空对象。使用
REST/HTTP 接口,则响应包含一个空的 JSON 对象 {}
。