本指南說明如何在 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-oauthlib
- 已啟用並設定 Google Chat API 的 Google Cloud 專案。相關步驟請參閱「建構 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
中加入下列程式碼: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
替換為聊天室名稱,您可以在 Chat API 的spaces.list
方法或聊天室網址取得這項資訊。在工作目錄中,建構並執行範例:
python3 chat_messages_list.py
Google Chat API 會傳回 2023 年 3 月 16 日後在指定聊天室中傳送的訊息清單。