עדכון מרחב משותף

במדריך הזה מוסבר איך להשתמש בשיטה patch() במשאב Space של Google Chat API כדי לעדכן מרחב. אפשר לעדכן את המרחב כדי לשנות מאפיינים שלו, כמו השם המוצג שגלוי למשתמשים, התיאור וההנחיות.

אדמינים ב-Google Workspace יכולים להתקשר לשיטת patch() כדי לעדכן חלל קיים בארגון שלהם ב-Google Workspace.

משאב Space מייצג מקום שבו אנשים ואפליקציות ל-Chat יכולים לשלוח הודעות, לשתף קבצים ולשתף פעולה. יש כמה סוגים של מרחבים:

  • צ'אטים ישירים הם שיחות בין שני משתמשים או בין משתמש לבין אפליקציית Chat.
  • צ'אטים קבוצתיים הם שיחות בין שלושה משתמשים או יותר לבין אפליקציות ל-Chat.
  • מרחבים משותפים עם שם הם מקומות קבועים שבהם אנשים יכולים לשלוח הודעות, לשתף קבצים ולעבוד יחד.

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

Node.js

Python

Java

Apps Script

עדכון מרחב כמשתמש

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

  • מציינים את chat.spaces היקף ההרשאה.
  • מבצעים קריאה ל-method‏ UpdateSpace(). בבקשה, מציינים את השדה name של המרחב, את השדה updateMask עם שדה אחד או יותר לעדכון ואת השדה body עם פרטי המרחב המעודכנים.

אתם יכולים לעדכן פרטים כמו השם לתצוגה, סוג המרחב, מצב ההיסטוריה ועוד. כדי לראות את כל השדות שאפשר לעדכן, אפשר לעיין במאמרי העזרה.

כך מעדכנים את השדה displayName במרחב קיים:

Node.js

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

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

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

  // Initialize request argument(s)
  const request = {
    space: {
      // Replace SPACE_NAME here
      name: 'spaces/SPACE_NAME',
      displayName: 'New space display name'
    },
    // The field paths to update. Separate multiple values with commas or use
    // `*` to update all field paths.
    updateMask: {
      // The field paths to update.
      paths: ['display_name']
    }
  };

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

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

main().catch(console.error);

Python

chat/client-libraries/cloud/update_space_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.spaces"]

# This sample shows how to update a space with user credential
def update_space_with_user_cred():
    # Create a client
    client = create_client_with_user_credentials(SCOPES)

    # Initialize request argument(s)
    request = google_chat.UpdateSpaceRequest(
        space = {
            # Replace SPACE_NAME here
            'name': 'spaces/SPACE_NAME',
            'display_name': 'New space display name'
        },
        # The field paths to update. Separate multiple values with commas.
        update_mask = 'displayName'
    )

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

    # Handle the response
    print(response)

update_space_with_user_cred()

Java

chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/UpdateSpaceUserCred.java
import com.google.chat.v1.ChatServiceClient;
import com.google.chat.v1.UpdateSpaceRequest;
import com.google.chat.v1.Space;
import com.google.protobuf.FieldMask;

// This sample shows how to update space with user credential.
public class UpdateSpaceUserCred {

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

  public static void main(String[] args) throws Exception {
    try (ChatServiceClient chatServiceClient =
        AuthenticationUtils.createClientWithUserCredentials(
          ImmutableList.of(SCOPE))) {
      UpdateSpaceRequest.Builder request = UpdateSpaceRequest.newBuilder()
        .setSpace(Space.newBuilder()
          // Replace SPACE_NAME here.
          .setName("spaces/SPACE_NAME")
          .setDisplayName("New space display name"))
        .setUpdateMask(FieldMask.newBuilder()
          // The field paths to update.
          .addPaths("display_name"));
      Space response = chatServiceClient.updateSpace(request.build());

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

Apps Script

chat/advanced-service/Main.gs
/**
 * This sample shows how to update a space with user credential
 * 
 * It relies on the OAuth2 scope 'https://www.googleapis.com/auth/chat.spaces'
 * referenced in the manifest file (appsscript.json).
 */
function updateSpaceUserCred() {
  // Initialize request argument(s)
  // TODO(developer): Replace SPACE_NAME here
  const name = 'spaces/SPACE_NAME';
  const space = {
    displayName: 'New space display name'
  };
  // The field paths to update. Separate multiple values with commas or use
  // `*` to update all field paths.
  const updateMask = 'displayName';

  // Make the request
  const response = Chat.Spaces.patch(space, name, {
    updateMask: updateMask
  });

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

כדי להריץ את הדוגמה הזו, מחליפים את SPACE_NAME במזהה מהשדה name של המרחב. אפשר לקבל את המזהה על ידי הפעלת השיטה ListSpaces() או מכתובת ה-URL של המרחב.

‫Google Chat API מחזיר מופע של Space שמשקף את העדכונים.

עדכון המרחב כאדמינים ב-Google Workspace

אדמינים ב-Google Workspace יכולים להתקשר לשיטה UpdateSpace() כדי לעדכן כל חלל בארגון שלהם ב-Google Workspace.

כדי להפעיל את ה-method הזה כאדמינים ב-Google Workspace, צריך לבצע את הפעולות הבאות:

  • קוראים ל-method באמצעות אימות משתמש, ומציינים היקף הרשאות שתומך בקריאה ל-method באמצעות הרשאות אדמין.
  • בבקשה, מציינים את פרמטר השאילתה useAdminAccess כ-true.

מידע נוסף ודוגמאות זמינים במאמר ניהול מרחבים ב-Google Chat כאדמינים ב-Google Workspace.

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

כדי לאמת אפליקציה, צריך אישור אדמין חד-פעמי.

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

  • מציינים את chat.app.spaces היקף ההרשאה. באמצעות אימות אפליקציות, אפשר לעדכן רק מרחבים שנוצרו על ידי אפליקציות ל-Chat.
  • מפעילים את השיטה patch על מקור המידע Space. בבקשה, מציינים את השדה name של המרחב, את השדה updateMask עם שדה אחד או יותר לעדכון ואת body עם פרטי המרחב המעודכנים.

אתם יכולים לעדכן דברים כמו השם לתצוגה, סוג המרחב, מצב ההיסטוריה, הגדרות ההרשאות ועוד. כדי לראות את כל השדות שאפשר לעדכן, אפשר לעיין במאמרי העזרה.

יצירה של מפתח 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) בפרטי הכניסה של הפרויקט.
    • לוחצים על Restrict key כדי לעדכן את ההגדרות המתקדמות ולהגביל את השימוש במפתח ה-API. פרטים נוספים זמינים במאמר החלת הגבלות על מפתחות API.

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

כך מעדכנים את השדה spaceDetails במרחב קיים:

Python

  1. בספריית העבודה, יוצרים קובץ בשם chat_space_update_app.py.
  2. מוסיפים את הקוד הבא אל chat_space_update_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.spaces"]
    
    def main():
        '''
        Authenticates with Chat API using app authentication,
        then updates the specified space description and guidelines.
        '''
    
        # 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().patch(
    
          # The space to update, and the updated space details.
          #
          # Replace {space} with a space name.
          # Obtain the space name from the spaces resource of Chat API,
          # or from a space's URL.
          name='spaces/SPACE',
          updateMask='spaceDetails',
          body={
    
            'spaceDetails': {
              'description': 'This description was updated with Chat API!',
              'guidelines': 'These guidelines were updated with Chat API!'
            }
    
          }
    
        ).execute()
    
        # Prints details about the updated space.
        print(result)
    
    if __name__ == '__main__':
        main()
    
  3. בקוד, מחליפים את הפרטים הבאים:

    • API_KEY: מפתח ה-API שיצרתם כדי לבנות את נקודת הקצה של השירות עבור Chat API.
    • SPACE עם שם המרחב, שאפשר לקבל באמצעות השיטה spaces.list ב-Chat API או מכתובת ה-URL של המרחב.
  4. בספריית העבודה, מבצעים build ומריצים את הדוגמה:

    python3 chat_space_update_app.py

‫Google Chat API מחזיר מופע של Space resource שמשקף את העדכונים.

מגבלות ושיקולים