本指南介绍了如何对 Google Chat API 的 Message
资源使用 list
方法,以查看聊天室中可过滤的分页消息列表。
Message
资源表示 Google Chat 中的文本或卡片消息。您可以通过调用相应的方法,在 Google Chat API 中对消息执行 create
、get
、update
或 delete
操作。如需详细了解文本和卡片消息,请参阅 Google Chat 消息概览。
前提条件
Python
- Python 3.6 或更高版本
- pip 软件包管理工具
适用于 Python 的最新 Google 客户端库。如需安装或更新这些软件包,请在命令行界面中运行以下命令:
pip3 install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib oauth2client
已发布的 Chat 应用。如需创建和发布 Chat 应用,请参阅构建 Google Chat 应用。
为 Chat 应用配置授权。要列出消息,您必须进行
chat.messages.readonly
或chat.messages
授权范围的用户身份验证。
列出消息
如需列出包含用户身份验证的消息,请在请求中传递以下内容:
- 指定
chat.messages.readonly
或chat.messages
授权范围。 - 对
Message
资源调用list
方法。
以下示例列出了 2023 年 3 月 16 日之后在 Chat 聊天室中发送的消息:
Python
- 在您的工作目录中,创建一个名为
chat_messages_list.py
的文件。 在
chat_messages_list.py
中添加以下代码:import os.path from google.auth.transport.requests import Request from google.oauth2.credentials import Credentials from google_auth_oauthlib.flow import InstalledAppFlow from googleapiclient.discovery import build from googleapiclient.errors import HttpError # 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 details about the created membership. print(result) if __name__ == '__main__': main()
在代码中,将
SPACE
替换为聊天室名称,您可以通过 Chat API 中的spaces.list
方法或聊天室网址获取该名称。在您的工作目录中,构建并运行示例:
python3 chat_messages_list.py
Google Chat API 会返回 2023 年 3 月 16 日之后在指定聊天室中发送的消息列表。
相关主题
- 设置邮件的格式。
- 删除消息。
- 了解某封邮件的详细信息。
- 更新消息。
- 发送消息。