איך מקבלים פרטים על הודעה מסוימת

במדריך הזה מוסבר איך להשתמש בשיטה get() במשאב Message של Google Chat API כדי להחזיר פרטים על הודעת טקסט או כרטיס.

ב-Chat API, הודעה ב-Chat מיוצגת על ידימשאב Message. משתמשי Chat יכולים לשלוח רק הודעות שמכילות טקסט, אבל אפליקציות ל-Chat יכולות להשתמש בהרבה תכונות אחרות של הודעות, כולל הצגת ממשקי משתמש סטטיים או אינטראקטיביים, איסוף מידע מהמשתמשים ושליחת הודעות באופן פרטי. מידע נוסף על התכונות של API להודעות ב-Chat זמין במאמר סקירה כללית על הודעות ב-Google Chat.

דרישות מוקדמות

Node.js

Python

Java

Apps Script

קבלת הודעה עם אימות משתמש

כדי לקבל פרטים על הודעה עם אימות משתמש, צריך להעביר את הפרטים הבאים בבקשה:

  • מציינים את היקף ההרשאות של chat.messages.readonly או chat.messages.
  • מבצעים קריאה ל-method‏ GetMessage().
  • מגדירים את name לשם המשאב של ההודעה שרוצים לאחזר.

בדוגמה הבאה מתקבלת הודעה עם אימות משתמש:

Node.js

chat/client-libraries/cloud/get-message-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 get message 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 and MESSAGE_NAME here
    name: 'spaces/SPACE_NAME/messages/MESSAGE_NAME'
  };

  // Make the request
  const response = await chatClient.getMessage(request);

  // Handle the response
  console.log(response);
}

main().catch(console.error);

Python

chat/client-libraries/cloud/get_message_user_cred.py
from authentication_utils import create_client_with_user_credentials
import google.oauth2.credentials

from google.apps import chat_v1 as google_chat

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

# This sample shows how to get message with user credential
def get_message_with_user_cred():
    # Create a client
    client = create_client_with_user_credentials(SCOPES)

    # Initialize request argument(s)
    request = google_chat.GetMessageRequest(
        # Replace SPACE_NAME and MESSAGE_NAME here
        name = "spaces/SPACE_NAME/messages/MESSAGE_NAME",
    )

    # Make the request
    response = client.get_message(request)

    # Handle the response
    print(response)

get_message_with_user_cred()

Java

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

// This sample shows how to get message with user credential.
public class GetMessageUserCred {

  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))) {
      GetMessageRequest.Builder request = GetMessageRequest.newBuilder()
        // replace SPACE_NAME and MESSAGE_NAME here
        .setName("spaces/SPACE_NAME/members/MESSAGE_NAME");
      Message response = chatServiceClient.getMessage(request.build());

      System.out.println(JsonFormat.printer().print(response));
    }
  }
}

Apps Script

chat/advanced-service/Main.gs
/**
 * This sample shows how to get message 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 getMessageUserCred() {
  // Initialize request argument(s)
  // TODO(developer): Replace SPACE_NAME and MESSAGE_NAME here
  const name = 'spaces/SPACE_NAME/messages/MESSAGE_NAME';

  // Make the request
  const response = Chat.Spaces.Messages.get(name);

  // Handle the response
  console.log(response);
}

כדי להריץ את הדוגמה הזו, מחליפים את הערכים הבאים:

  • SPACE_NAME: המזהה מname המרחב. אפשר לקבל את המזהה באמצעות הקריאה ל-method‏ ListSpaces() או מכתובת ה-URL של המרחב.
  • MESSAGE_NAME: המזהה מההודעה name. אפשר לקבל את המזהה מגוף התגובה שמוחזר אחרי יצירת הודעה באופן אסינכרוני באמצעות Chat API, או באמצעות שם בהתאמה אישית שהוקצה להודעה בזמן היצירה.

ממשק Chat API מחזיר מופע של Message עם פרטים על ההודעה שצוינה.

קבלת הודעה עם אימות אפליקציה

כדי לקבל פרטים על הודעה עם אימות אפליקציה, צריך להעביר את הפרטים הבאים בבקשה:

בדוגמה הבאה מתקבלת הודעה עם אימות אפליקציה:

Node.js

chat/client-libraries/cloud/get-message-app-cred.js
import {createClientWithAppCredentials} from './authentication-utils.js';

// This sample shows how to get message with app credential
async function main() {
  // Create a client
  const chatClient = createClientWithAppCredentials();

  // Initialize request argument(s)
  const request = {
    // Replace SPACE_NAME and MESSAGE_NAME here
    name: 'spaces/SPACE_NAME/messages/MESSAGE_NAME'
  };

  // Make the request
  const response = await chatClient.getMessage(request);

  // Handle the response
  console.log(response);
}

main().catch(console.error);

Python

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

# This sample shows how to get message with app credential
def get_message_with_app_cred():
    # Create a client
    client = create_client_with_app_credentials()

    # Initialize request argument(s)
    request = google_chat.GetMessageRequest(
        # Replace SPACE_NAME and MESSAGE_NAME here
        name = 'spaces/SPACE_NAME/messages/MESSAGE_NAME',
    )

    # Make the request
    response = client.get_message(request=request)

    # Handle the response
    print(response)

get_message_with_app_cred()

Java

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

// This sample shows how to get message with app credential.
public class GetMessageAppCred {

  public static void main(String[] args) throws Exception {
    try (ChatServiceClient chatServiceClient =
        AuthenticationUtils.createClientWithAppCredentials()) {
      GetMessageRequest.Builder request = GetMessageRequest.newBuilder()
        // replace SPACE_NAME and MESSAGE_NAME here
        .setName("spaces/SPACE_NAME/members/MESSAGE_NAME");
      Message response = chatServiceClient.getMessage(request.build());

      System.out.println(JsonFormat.printer().print(response));
    }
  }
}

Apps Script

chat/advanced-service/Main.gs
/**
 * This sample shows how to get message with app credential
 * 
 * It relies on the OAuth2 scope 'https://www.googleapis.com/auth/chat.bot'
 * used by service accounts.
 */
function getMessageAppCred() {
  // Initialize request argument(s)
  // TODO(developer): Replace SPACE_NAME and MESSAGE_NAME here
  const name = 'spaces/SPACE_NAME/messages/MESSAGE_NAME';
  const parameters = {};

  // Make the request
  const response = Chat.Spaces.Messages.get(name, parameters, getHeaderWithAppCredentials());

  // Handle the response
  console.log(response);
}

כדי להריץ את הדוגמה הזו, מחליפים את הערכים הבאים:

  • SPACE_NAME: המזהה מname המרחב. אפשר לקבל את המזהה באמצעות הקריאה ל-method‏ ListSpaces() או מכתובת ה-URL של המרחב.
  • MESSAGE_NAME: המזהה מההודעה name. אפשר לקבל את המזהה מגוף התגובה שמוחזר אחרי יצירת הודעה באופן אסינכרוני באמצעות Chat API, או באמצעות השם המותאם אישית שהוקצה להודעה בזמן היצירה.

ממשק Chat API מחזיר מופע של Message שמפרט את ההודעה שצוינה.

קבלת הודעה כאפליקציה ל-Chat באישור האדמין

אימות אפליקציה עם היקף הרשאות של chat.app.* דורש אישור אדמין חד-פעמי.

כדי לקבל פרטים על הודעה עם אימות אפליקציה באמצעות Chat REST API, צריך להעביר את הפרטים הבאים בבקשה:

  • מבצעים קריאה ל-method‏ GetMessage().
  • מציינים את chat.app.messages.readonly היקף ההרשאה.
  • מגדירים את name לשם המשאב של ההודעה שרוצים לאחזר.

יצירה של מפתח API

כדי לקרוא ל-method של API בגרסת טרום-השקה למפתחים, צריך להשתמש בגרסת טרום-השקה למפתחים של מסמך גילוי ה-API, שאינה ציבורית. כדי לאמת את הבקשה, צריך להעביר מפתח API.

כדי ליצור את מפתח ה-API, פותחים את פרויקט Google Cloud של האפליקציה ומבצעים את הפעולות הבאות:

  1. במסוף Google Cloud, לוחצים על סמל התפריט > APIs & Services > Credentials.

    כניסה לדף Credentials

  2. לוחצים על Create credentials > API key.
  3. מפתח ה-API החדש מוצג.
    • לוחצים על סמל ההעתקה כדי להעתיק את מפתח ה-API לשימוש בקוד של האפליקציה. מפתח ה-API מופיע גם בקטע API Keys (מפתחות API) בפרטי הכניסה של הפרויקט.
    • כדי למנוע שימוש לא מורשה, מומלץ להגביל את המקומות שבהם אפשר להשתמש במפתח ה-API ואת ממשקי ה-API שאפשר להשתמש בו עבורם. פרטים נוספים זמינים במאמר בנושא הוספת הגבלות על ממשקי API.

כתיבת סקריפט שקורא ל-Chat API

כך מקבלים פרטים על הודעה באמצעות אימות אפליקציה ואישור אדמין ו-Chat REST API:

Python

  1. בספריית העבודה, יוצרים קובץ בשם chat_messages_get_admin_app.py.
  2. מוסיפים את הקוד הבא אל chat_messages_get_admin_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 gets details about a message.
        '''
    
        # 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().get(
    
            # The message to get details about.
            #
            # Replace SPACE_NAME with a space name.
            # Obtain the space name from the spaces resource of Chat API,
            # or from a space's URL.
            name='spaces/SPACE_NAME/messages/MESSAGE_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: המזהה מname של המרחב. אפשר לקבל את המזהה על ידי הפעלת השיטה ListSpaces() או מכתובת ה-URL של המרחב.
    • MESSAGE_NAME: המזהה מתוך name של ההודעה. אפשר לקבל את המזהה מגוף התגובה שמוחזר אחרי יצירת הודעה באופן אסינכרוני באמצעות Chat API, או באמצעות שם בהתאמה אישית שהוקצה להודעה בזמן היצירה.
  4. בספריית העבודה, מבצעים build ומריצים את הדוגמה:

    python3 chat_messages_get_admin_app.py

ממשק Chat API מחזיר מופע של Message עם פרטים על ההודעה שצוינה.