メッセージの一覧表示

このガイドでは、Google Chat API の Message リソースの list メソッドを使用して、ページ分けされたフィルタ可能なメッセージのリストを表示する方法について説明します。

Message リソースは、Google Chat のテキスト メッセージまたはカード メッセージを表します。Google Chat API でメッセージを creategetupdatedelete のいずれかにするには、対応するメソッドを呼び出します。テキスト メッセージとカード メッセージの詳細については、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 承認スコープを持つユーザー認証が必要です。

メッセージの一覧表示

ユーザー認証を使用してメッセージを一覧表示するには、リクエストに次の内容を渡します。

次の例では、2023 年 3 月 16 日以降に送信された Chat スペース内のメッセージを一覧表示します。

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 details about the created membership.
        print(result)
    
    if __name__ == '__main__':
        main()
    
  3. コードで SPACE をスペース名に置き換えます。スペース名は、Chat API の spaces.list メソッドまたはスペースの URL から取得できます。

  4. 作業ディレクトリで、サンプルをビルドして実行します。

    python3 chat_messages_list.py
    

Google Chat API は、2023 年 3 月 16 日以降に指定されたスペースで送信されたメッセージのリストを返します。