列出訊息

本指南說明如何針對以下項目的 Message 資源使用 list 方法: 使用 Google Chat API,查看聊天室中可篩選的分頁訊息清單。

Message 項資源 代表的 文字資訊卡 訊息。你可以 creategetupdatedelete,透過呼叫方式在 Google Chat API 中傳送訊息 對應的方法如要進一步瞭解簡訊和資訊卡訊息,請參閱 Google Chat 訊息總覽

必要條件

Python

  • Python 3.6 以上版本
  • pip 套件管理工具
  • 最新的 Google 用戶端程式庫。安裝或更新 在指令列介面中執行下列指令:
    pip3 install --upgrade google-api-python-client google-auth-oauthlib
    

列出訊息

如要列出訊息 使用者驗證 並在要求中傳遞下列資訊:

下列範例會列出之後在 Chat 聊天室中傳送的訊息 2023 年 3 月 16 日:

Python

  1. 在工作目錄中,建立名為 chat_messages_list.py 的檔案。
  2. 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()
    
  3. 將程式碼中的 SPACE 替換成空格名稱, 您可以從中取得 spaces.list 方法 或聊天室網址傳送

  4. 在工作目錄中建構並執行範例:

    python3 chat_messages_list.py
    

Google Chat API 會傳回指定聊天室中,位於 2023 年 3 月 16 日。