יצירת מרחב משותף עם שם ב-Google Chat

במדריך הזה מוסבר איך ליצור מרחב עם שם באמצעות method‏ create() במשאב Space של Google Chat API.

מרחב עם שם (שבו spaceType הוא SPACE) הוא מקום שבו אנשים שולחים הודעות, משתפים קבצים ועובדים ביחד. מרחבים עם שם יכולים לכלול אפליקציות ל-Chat. למרחבים עם שם יש מנהלי מרחב שיכולים להחיל הגדרות אדמיניסטרטיביות ותיאורים, ולהוסיף או להסיר אנשים ואפליקציות.

כדי ליצור סוגים שונים של מרחבים ב-Chat (כולל צ'אטים ישירים או צ'אטים קבוצתיים), משתמשים בשיטה setUp() במקור המידע Space כדי ליצור את המרחב ולהוסיף לו משתתפים בו-זמנית. מידע נוסף זמין במאמר בנושא הגדרת מרחב.

אחרי שיוצרים מרחב עם שם, המשתמש המאומת הוא המשתמש היחיד במרחב. כדי להוסיף משתמשים למרחב, קוראים לשיטה create() במשאב Membership עבור כל אדם או אפליקציה שרוצים להוסיף. אפשר גם להשתמש בשיטה setUp() כדי ליצור מרחב עם שם ולהוסיף אליו משתתפים בו-זמנית.

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

Node.js

Python

Java

Apps Script

יצירת מרחב עם שם בתור משתמש

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

  • מציינים את היקף ההרשאות של chat.spaces.create או chat.spaces.
  • מבצעים קריאה ל-method‏ CreateSpace() ומעבירים את space כאירוע של Space עם השדות הבאים:
    • spaceType הוגדרה לערך SPACE.
    • displayName מוגדר לשם המרחב שגלוי למשתמש.
    • אפשר גם להגדיר מאפיינים אחרים, כמו:
      • spaceDetails – תיאור שגלוי למשתמשים וקבוצת הנחיות לגבי המרחב.
      • predefinedPermissionSettings – הרשאות מוגדרות מראש למרחב. לדוגמה, אתם יכולים להגדיר שכל המשתתפים או רק מנהלי המרחב יוכלו לפרסם הודעות.

כך יוצרים מרחב עם שם:

Node.js

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

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

// This sample shows how to create a named 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: {
      spaceType: 'SPACE',
      // Replace DISPLAY_NAME here.
      displayName: 'DISPLAY_NAME'
    }
  };

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

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

main().catch(console.error);

Python

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

def create_space_with_user_cred():
    # Create a client
    client = create_client_with_user_credentials(SCOPES)

    # Initialize request argument(s)
    request = google_chat.CreateSpaceRequest(
        space = {
            "space_type": 'SPACE',
            # Replace DISPLAY_NAME here.
            "display_name": 'DISPLAY_NAME'
        }
    )

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

    # Handle the response
    print(response)

create_space_with_user_cred()

Java

chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateSpaceUserCred.java
import com.google.chat.v1.ChatServiceClient;
import com.google.chat.v1.CreateSpaceRequest;
import com.google.chat.v1.Space;

// This sample shows how to create space with user credential.
public class CreateSpaceUserCred {

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

  public static void main(String[] args) throws Exception {
    try (ChatServiceClient chatServiceClient =
        AuthenticationUtils.createClientWithUserCredentials(
          ImmutableList.of(SCOPE))) {
      CreateSpaceRequest.Builder request = CreateSpaceRequest.newBuilder()
        .setSpace(Space.newBuilder()
          .setSpaceType(Space.SpaceType.SPACE)
          // Replace DISPLAY_NAME here.
          .setDisplayName("DISPLAY_NAME"));
      Space response = chatServiceClient.createSpace(request.build());

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

Apps Script

chat/advanced-service/Main.gs
/**
 * This sample shows how to create space with user credential
 * 
 * It relies on the OAuth2 scope 'https://www.googleapis.com/auth/chat.spaces.create'
 * referenced in the manifest file (appsscript.json).
 */
function createSpaceUserCred() {
  // Initialize request argument(s)
  const space = {
    spaceType: 'SPACE',
    // TODO(developer): Replace DISPLAY_NAME here
    displayName: 'DISPLAY_NAME'
  };

  // Make the request
  const response = Chat.Spaces.create(space);

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

יצירת מרחב עם שם כאפליקציית Chat

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

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

  • מציינים את היקף ההרשאה של chat.app.spaces.create או chat.app.spaces.
  • מפעילים את השיטה create במשאב Space.
  • מגדירים את spaceType לערך SPACE.
  • מגדירים את הערך Set displayName לשם המרחב שגלוי למשתמשים. בדוגמה הבאה, הערך displayName מוגדר ל-API-made.
  • מציינים את מספר הלקוח של דומיין Google Workspace באמצעות השדה customer.
  • אפשר גם להגדיר מאפיינים אחרים של המרחב, כמו spaceDetails (תיאור שגלוי למשתמשים וקבוצת הנחיות למרחב).

יצירה של מפתח 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

כך יוצרים מרחב עם שם:

Python

  1. בספריית העבודה, יוצרים קובץ בשם chat_space_create_named_app.py.
  2. מוסיפים את הקוד הבא אל chat_space_create_named_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.create"]
    
    def main():
        '''
        Authenticates with Chat API using app authentication,
        then creates a Chat 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().create(
    
          # Details about the space to create.
          body = {
    
            # To create a named space, set spaceType to SPACE.
            'spaceType': 'SPACE',
    
            # The user-visible name of the space.
            'displayName': 'API-made',
    
            # The customer ID of the Workspace domain.
            'customer': 'CUSTOMER'
          }
    
          ).execute()
    
        # Prints details about the created space.
        print(result)
    
    if __name__ == '__main__':
        main()
    
  3. בקוד, מחליפים את הפרטים הבאים:

    • API_KEY: מפתח ה-API שיצרתם כדי לבנות את נקודת הקצה של השירות עבור Chat API.

    • CUSTOMER: מזהה הלקוח של הדומיין של המרחב בפורמט customer/{customer}, כאשר {customer} הוא ID ממקור הלקוח של Admin SDK. כדי ליצור חלל באותו ארגון Google Workspace שבו נמצאת אפליקציית Chat, משתמשים ב-customers/my_customer.

  4. בספריית העבודה, מבצעים build ומריצים את הדוגמה:

    python3 chat_space_create_named_app.py

פותחים את המרחב ב-Google Chat.

כדי לעבור למרחב, משתמשים במזהה המשאב של המרחב כדי ליצור את כתובת ה-URL של המרחב. אפשר למצוא את מזהה מקור המידע של המרחב name בגוף התשובה של Google Chat. לדוגמה, אם ה-name של המרחב הוא spaces/1234567, אפשר לעבור למרחב באמצעות כתובת ה-URL הבאה: https://mail.google.com/chat/u/0/#chat/space/1234567.

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

  • כשיוצרים מרחב באמצעות אימות אפליקציות, אפליקציית Chat שעוברת אימות מצורפת כחברה במרחב, אבל בניגוד לאימות משתמשים, היא לא מצורפת כמנהלת המרחב. כברירת מחדל, כל החברים במרחב יכולים להסיר את אפליקציית Chat. כדי לאפשר רק למנהלי המרחב להסיר את אפליקציית Chat, צריך להגדיר את permissionSettings.manageApps ל-managersAllowed.