แสดงรายการข้อความ

คู่มือนี้อธิบายวิธีใช้เมธอด list() ในทรัพยากร Message ของ Google Chat API เพื่อดูรายการข้อความที่แบ่งหน้าและกรองได้ในพื้นที่ทำงาน

ใน Chat API ข้อความ Chat จะแสดงด้วยMessageทรัพยากร แม้ว่าผู้ใช้ Chat จะส่งได้เฉพาะข้อความที่มีข้อความ แต่ แอปใน Chat สามารถใช้ฟีเจอร์การรับส่งข้อความอื่นๆ ได้อีกมากมาย ซึ่งรวมถึง การแสดงอินเทอร์เฟซผู้ใช้แบบคงที่หรือแบบอินเทอร์แอกทีฟ การรวบรวมข้อมูลจาก ผู้ใช้ และการส่งข้อความแบบส่วนตัว ดูข้อมูลเพิ่มเติมเกี่ยวกับฟีเจอร์การรับส่งข้อความที่ใช้ได้กับ Chat API ได้ที่ภาพรวมของข้อความ Google Chat

ข้อกำหนดเบื้องต้น

Node.js

  • บัญชี Google Workspace สำหรับธุรกิจหรือองค์กร ที่มีสิทธิ์เข้าถึง Google Chat

Python

  • บัญชี Google Workspace สำหรับธุรกิจหรือองค์กร ที่มีสิทธิ์เข้าถึง Google Chat

Java

  • บัญชี Google Workspace สำหรับธุรกิจหรือองค์กร ที่มีสิทธิ์เข้าถึง Google Chat

Apps Script

  • บัญชี Google Workspace สำหรับธุรกิจหรือองค์กร ที่มีสิทธิ์เข้าถึง Google Chat

แสดงข้อความในฐานะผู้ใช้

หากต้องการแสดงข้อความที่มีการตรวจสอบสิทธิ์ผู้ใช้ ให้ส่งข้อมูลต่อไปนี้ในคำขอ

  • ระบุขอบเขตการให้สิทธิ์ chat.messages.readonly หรือ chat.messages
  • เรียกใช้เมธอด ListMessages()

ตัวอย่างต่อไปนี้แสดงรายการข้อความในพื้นที่ใน Chat

Node.js

chat/client-libraries/cloud/list-messages-user-cred.js
import {createClientWithUserCredentials} from './authentication-utils.js';

const USER_AUTH_OAUTH_SCOPES = ['https://www.googleapis.com/auth/chat.messages.readonly'];

// This sample shows how to list messages with user credential
async function main() {
  // Create a client
  const chatClient = await createClientWithUserCredentials(USER_AUTH_OAUTH_SCOPES);

  // Initialize request argument(s)
  const request = {
    // Replace SPACE_NAME here
    parent: 'spaces/SPACE_NAME'
  };

  // Make the request
  const pageResult = chatClient.listMessagesAsync(request);

  // Handle the response. Iterating over pageResult will yield results and
  // resolve additional pages automatically.
  for await (const response of pageResult) {
    console.log(response);
  }
}

main().catch(console.error);

Python

chat/client-libraries/cloud/list_messages_user_cred.py
from authentication_utils import create_client_with_user_credentials
from google.apps import chat_v1 as google_chat

SCOPES = ["https://www.googleapis.com/auth/chat.messages.readonly"]

# This sample shows how to list messages with user credential
def list_messages_with_user_cred():
    # Create a client
    client = create_client_with_user_credentials(SCOPES)

    # Initialize request argument(s)
    request = google_chat.ListMessagesRequest(
        # Replace SPACE_NAME here
        parent = 'spaces/SPACE_NAME',
        # Number of results that will be returned at once
        page_size = 100
    )

    # Make the request
    page_result = client.list_messages(request)

    # Handle the response. Iterating over page_result will yield results and
    # resolve additional pages automatically.
    for response in page_result:
        print(response)

list_messages_with_user_cred()

Java

chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/ListMessagesUserCred.java
import com.google.chat.v1.ChatServiceClient;
import com.google.chat.v1.ListMessagesRequest;
import com.google.chat.v1.ListMessagesResponse;
import com.google.chat.v1.Message;

// This sample shows how to list messages with user credential.
public class ListMessagesUserCred {

  private static final String SCOPE =
    "https://www.googleapis.com/auth/chat.messages.readonly";

  public static void main(String[] args) throws Exception {
    try (ChatServiceClient chatServiceClient =
        AuthenticationUtils.createClientWithUserCredentials(
          ImmutableList.of(SCOPE))) {
      ListMessagesRequest.Builder request = ListMessagesRequest.newBuilder()
        // Replace SPACE_NAME here.
        .setParent("spaces/SPACE_NAME")
        // Number of results that will be returned at once.
        .setPageSize(10);

      // Iterate over results and resolve additional pages automatically.
      for (Message response :
          chatServiceClient.listMessages(request.build()).iterateAll()) {
        System.out.println(JsonFormat.printer().print(response));
      }
    }
  }
}

Apps Script

chat/advanced-service/Main.gs
/**
 * This sample shows how to list messages with user credential
 * 
 * It relies on the OAuth2 scope 'https://www.googleapis.com/auth/chat.messages.readonly'
 * referenced in the manifest file (appsscript.json).
 */
function listMessagesUserCred() {
  // Initialize request argument(s)
  // TODO(developer): Replace SPACE_NAME here
  const parent = 'spaces/SPACE_NAME';

  // Iterate through the response pages using page tokens
  let responsePage;
  let pageToken = null;
  do {
    // Request response pages
    responsePage = Chat.Spaces.Messages.list(parent, {
      pageSize: 10,
      pageToken: pageToken
    });
    // Handle response pages
    if (responsePage.messages) {
      responsePage.messages.forEach((message) => console.log(message));
    }
    // Update the page token to the next one
    pageToken = responsePage.nextPageToken;
  } while (pageToken);
}

หากต้องการเรียกใช้ตัวอย่างนี้ ให้แทนที่ SPACE_NAME ด้วยรหัสจาก ฟิลด์ name ของพื้นที่ทำงาน คุณรับรหัสได้โดยการเรียกใช้เมธอด ListSpaces() หรือจาก URL ของพื้นที่ทำงาน

Chat API จะแสดงรายการข้อความ ที่ส่งในพื้นที่ที่ระบุ หากไม่มีข้อความจากคำขอ การตอบกลับของ Chat API จะแสดงออบเจ็กต์ที่ว่างเปล่า เมื่อใช้ REST/HTTP อินเทอร์เฟซ การตอบกลับจะมีออบเจ็กต์ JSON ว่าง {}

แสดงข้อความในฐานะแอป Chat

การตรวจสอบสิทธิ์แอปต้องมีการอนุมัติจากผู้ดูแลระบบแบบครั้งเดียว

หากต้องการแสดงข้อความจากพื้นที่ทำงานที่มีการตรวจสอบสิทธิ์แอป โดยใช้ Chat REST API ให้ส่งข้อมูลต่อไปนี้ในคำขอ

  • ระบุขอบเขตการให้สิทธิ์อย่างใดอย่างหนึ่งต่อไปนี้
    • https://www.googleapis.com/auth/chat.app.messages.readonly
  • เรียกใช้เมธอด list ในmessages ทรัพยากร
  • ส่ง name ของพื้นที่ทำงานเพื่อแสดงรายการข้อความ

สร้างคีย์ API

หากต้องการเรียกเมธอด API ของรุ่นตัวอย่างสำหรับนักพัฒนาซอฟต์แวร์ คุณต้องใช้เอกสารการค้นพบ API เวอร์ชันตัวอย่างสำหรับนักพัฒนาซอฟต์แวร์ที่ไม่ใช่แบบสาธารณะ หากต้องการตรวจสอบสิทธิ์คำขอ คุณต้องส่งคีย์ API

หากต้องการสร้างคีย์ API ให้เปิดโปรเจ็กต์ Google Cloud ของแอป แล้วทำดังนี้

  1. ในคอนโซล Google Cloud ให้ไปที่เมนู > API และบริการ > ข้อมูลเข้าสู่ระบบ

    ไปที่ข้อมูลเข้าสู่ระบบ

  2. คลิกสร้างข้อมูลเข้าสู่ระบบ > คีย์ API
  3. ระบบจะแสดงคีย์ API ใหม่
    • คลิกคัดลอก เพื่อคัดลอกคีย์ API สำหรับใช้ ในโค้ดของแอป คุณยังดูคีย์ API ได้ในส่วน "คีย์ API" ของข้อมูลเข้าสู่ระบบของโปรเจ็กต์ ด้วย
    • เราขอแนะนำให้จำกัดตำแหน่งและ API ที่ใช้คีย์ API ได้เพื่อป้องกันการใช้งานที่ไม่ได้รับอนุญาต ดูรายละเอียดเพิ่มเติมได้ที่ เพิ่มการจำกัด API

เขียนสคริปต์ที่เรียกใช้ Chat API

วิธีแสดงข้อความด้วยการตรวจสอบสิทธิ์ของแอปและ Chat REST API มีดังนี้

Python

  1. สร้างไฟล์ชื่อ chat_messages_list_app.py ในไดเรกทอรีการทำงาน
  2. ใส่โค้ดต่อไปนี้ใน chat_messages_list_app.py

    from google.oauth2 import service_account
    from apiclient.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.app.messages.readonly"]
    
    def main():
        '''
        Authenticates with Chat API using app authentication,
        then lists messages from a specified space.
        '''
    
        # Specify service account details.
        creds = (
            service_account.Credentials.from_service_account_file('credentials.json')
            .with_scopes(SCOPES)
        )
    
        # Build a service endpoint for Chat API.
        chat = build('chat', 'v1', credentials=creds, discoveryServiceUrl='https://chat.googleapis.com/$discovery/rest?version=v1&labels=DEVELOPER_PREVIEW&key=API_KEY')
    
        # Use the service endpoint to call Chat API.
        result = chat.spaces().messages().list(
    
            # The space to list messages from.
            #
            # Replace SPACE_NAME with a space name.
            # Obtain the space name from the spaces resource of Chat API,
            # or from a space's URL.
            parent='spaces/SPACE_NAME'
    
        ).execute()
    
        # Print Chat API's response in your command line interface.
        print(result)
    
    if __name__ == '__main__':
        main()
    
  3. ในโค้ด ให้แทนที่ค่าต่อไปนี้

    • API_KEY: คีย์ API ที่คุณสร้างขึ้นเพื่อสร้าง ปลายทางบริการสำหรับ Chat API

    • SPACE_NAME: ชื่อพื้นที่ ซึ่งคุณรับได้จากเมธอด spaces.list ใน Chat API หรือจาก URL ของพื้นที่

  4. ในไดเรกทอรีการทำงาน ให้สร้างและเรียกใช้ตัวอย่างโดยทำดังนี้

    python3 chat_messages_list_app.py

Chat API จะแสดงรายการข้อความ ที่ส่งในพื้นที่ที่ระบุ หากไม่มีข้อความจากคำขอ การตอบกลับของ Chat API จะแสดงออบเจ็กต์ที่ว่างเปล่า เมื่อใช้ REST/HTTP อินเทอร์เฟซ การตอบกลับจะมีออบเจ็กต์ JSON ว่าง {}