עדכון חברות של משתמש במרחב משותף ב-Google Chat

במדריך הזה מוסבר איך משתמשים בשיטה patch במשאב membership של Google Chat API כדי לשנות מאפיינים של החברוּת במרחב המשותף, כמו שינוי התפקיד למנהל/ת של המרחב המשותף או החלפת המנהל/ת של המרחב המשותף למשתמש/ת.

המשאב Membership מייצג אם משתמש אנושי או אפליקציית Google Chat הוזמנו למרחב משותף, אם הוא חלק ממנו או נעדר ממנו.

Python

  • Python 3.6 ואילך
  • הכלי pip לניהול חבילות
  • ספריות הלקוח העדכניות של Google ל-Python. כדי להתקין או לעדכן אותן, מריצים את הפקודה הבאה בממשק שורת הפקודה:

    pip3 install --upgrade google-api-python-client google-auth-oauthlib
    
  • פרויקט ב-Google Cloud עם ממשק Google Chat API פעיל ומוגדר. במאמר איך יוצרים אפליקציה ל-Google Chat מוסבר איך עושים זאת.
  • הרשאות שהוגדרו לאפליקציית Chat. כדי לעדכן מינוי צריך אימות משתמש עם היקף ההרשאה chat.memberships, או אם מייבאים נתונים ל-Chat, צריך להשתמש בהיקף ההרשאה chat.import.

Node.js

  • Node.js ו-npm
  • ספריות הלקוח העדכניות של Google ל-Node.js. כדי להתקין אותם, מריצים את הפקודה הבאה בממשק שורת הפקודה:

    npm install @google-cloud/local-auth @googleapis/chat
    
  • פרויקט ב-Google Cloud עם ממשק Google Chat API פעיל ומוגדר. במאמר איך יוצרים אפליקציה ל-Google Chat מוסבר איך עושים זאת.
  • הרשאות שהוגדרו לאפליקציית Chat. כדי לעדכן מינוי צריך אימות משתמש עם היקף ההרשאה chat.memberships, או אם מייבאים נתונים ל-Chat, צריך להשתמש בהיקף ההרשאה chat.import.

Apps Script

עדכון המינוי

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

  • צריך לציין את היקף ההרשאה של chat.memberships.
  • קוראים ל-method patch במשאב Membership ומעבירים את name של המינוי לצורך עדכון, וגם updateMask ו-body שמציינים את המאפיינים המעודכנים של המינוי.
  • ב-updateMask מפורטים ההיבטים של המינוי שרוצים לעדכן, והוא כולל:
    • role: תפקיד המשתמש במרחב משותף ב-Chat, שקובע מה הם הפעולות שמותר לבצע במרחב המשותף. הערכים האפשריים הם:
      • ROLE_MEMBER: אחד מהמשתתפים במרחב המשותף. למשתמש יש הרשאות בסיסיות, למשל שליחת הודעות למרחב המשותף. בשיחות קבוצתיות אישיות וללא שם, לכולם יש את התפקיד הזה.
      • ROLE_MANAGER: המנהל/ת של המרחב המשותף. למשתמש יש את כל ההרשאות הבסיסיות, בנוסף להרשאות ניהול שמאפשרות לו לנהל את המרחב המשותף, כמו הוספה או הסרה של חברים. האפשרות זמינה רק במרחבים שבהם spaceType הוא SPACE (מרחבים עם שמות).

איך הופכים אנשים רגילים למנהלים של המרחב המשותף

בדוגמה הבאה, משתמש רגיל במרחב המשותף מוגדר כמנהל של המרחב המשותף. כדי לעשות את זה, מזינים את הערך role בתור ROLE_MANAGER ב-body, שמציין את מאפייני החברות המעודכנים:

Python

  1. בספריית העבודה, יוצרים קובץ בשם chat_membership_update.py.
  2. יש לכלול את הקוד הבא ב-chat_membership_update.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.memberships"]
    
    def main():
        '''
        Authenticates with Chat API via user credentials,
        then updates a specified space member to change
        it from a regular member to a space manager.
        '''
    
        # 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().members().patch(
    
            # The membership to update, and the updated role.
            #
            # Replace SPACE with a space name.
            # Obtain the space name from the spaces resource of Chat API,
            # or from a space's URL.
            #
            # Replace MEMBERSHIP with a membership name.
            # Obtain the membership name from the membership of Chat API.
            name='spaces/SPACE/members/MEMBERSHIP',
            updateMask='role',
            body={'role': 'ROLE_MANAGER'}
    
          ).execute()
    
        # Prints details about the updated membership.
        print(result)
    
    if __name__ == '__main__':
        main()
    
  3. בקוד, מחליפים את מה שכתוב בשדות הבאים:

    • SPACE: שם של מרחב משותף, שאפשר לקבל מה-method spaces.list ב-Chat API או מכתובת ה-URL של המרחב המשותף.

    • MEMBERSHIP: שם המינוי, שאותו אפשר לקבל דרך ה-method spaces.members.list ב-Chat API.

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

    python3 chat_membership_update.py
    

Node.js

  1. בספריית העבודה, יוצרים קובץ בשם chat_membership_update.js.
  2. יש לכלול את הקוד הבא ב-chat_membership_update.js:

    const chat = require('@googleapis/chat');
    const {authenticate} = require('@google-cloud/local-auth');
    
    /**
    * Updates a membership in a Chat space to change it from
    * a space member to a space manager.
    * @return {!Promise<!Object>}
    */
    async function updateSpace() {
    
      /**
      * Authenticate with Google Workspace
      * and get user authorization.
      */
      const scopes = [
        'https://www.googleapis.com/auth/chat.memberships',
      ];
    
      const authClient =
          await authenticate({scopes, keyfilePath: 'client_secrets.json'});
    
      /**
      * Build a service endpoint for Chat API.
      */
      const chatClient = await chat.chat({version: 'v1', auth: authClient});
    
      /**
      * Use the service endpoint to call Chat API.
      */
      return await chatClient.spaces.patch({
    
        /**
        * The membership to update, and the updated role.
        *
        * Replace SPACE with a space name.
        * Obtain the space name from the spaces resource of Chat API,
        * or from a space's URL.
        *
        * Replace MEMBERSHIP with a membership name.
        * Obtain the membership name from the membership of Chat API.
        */
        name: 'spaces/SPACE/members/MEMBERSHIP',
        updateMask: 'role',
        requestBody: {
          role: 'ROLE_MANAGER'
        }
      });
    }
    
    /**
    * Use the service endpoint to call Chat API.
    */
    updateSpace().then(console.log);
    
  3. בקוד, מחליפים את מה שכתוב בשדות הבאים:

    • SPACE: שם של מרחב משותף, שאפשר לקבל מה-method spaces.list ב-Chat API או מכתובת ה-URL של המרחב המשותף.

    • MEMBERSHIP: שם המינוי, שאותו אפשר לקבל דרך ה-method spaces.members.list ב-Chat API.

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

    python3 chat_membership_update.js
    

Apps Script

הדוגמה הזו מפעילה את Chat API באמצעות Advanced Chat Service.

  1. מוסיפים את היקף ההרשאה chat.memberships לקובץ appsscript.json של פרויקט Apps Script:

    "oauthScopes": [
      "https://www.googleapis.com/auth/chat.memberships"
    ]
    
  2. מוסיפים פונקציה כמו זו לקוד של הפרויקט ב-Apps Script:

    /**
     * Updates a membership from space member to space manager.
     * @param {string} memberName The resource name of the membership.
    */
    function updateMembershipToSpaceManager(memberName) {
      try {
        const body = {'role': 'ROLE_MANAGER'};
        Chat.Spaces.Members.patch(memberName, body);
      } catch (err) {
        // TODO (developer) - Handle exception
        console.log('Failed to create message with error %s', err.message);
      }
    }
    

ה-Google Chat API משנה את התפקיד שנבחר למנהל של המרחב המשותף, ומחזיר מופע של Membership שכולל את השינוי.

איך מגדירים שמנהל/ת המרחב המשותף יהיה חבר/ה רגיל/ת של המרחב המשותף

בדוגמה הבאה, מנהל/ת המרחב המשותף משתמש/ת באופן קבוע במרחב המשותף. כדי לעשות זאת, מציינים את הערך role בתור ROLE_MEMBER ב-body, שמציין את מאפייני החברות המעודכנים:

Python

  1. בספריית העבודה, יוצרים קובץ בשם chat_membership_update.py.
  2. יש לכלול את הקוד הבא ב-chat_membership_update.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.memberships"]
    
    def main():
        '''
        Authenticates with Chat API via user credentials,
        then updates a specified space member to change
        it from a regular member to a space manager.
        '''
    
        # 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().members().patch(
    
            # The membership to update, and the updated role.
            #
            # Replace SPACE with a space name.
            # Obtain the space name from the spaces resource of Chat API,
            # or from a space's URL.
            #
            # Replace MEMBERSHIP with a membership name.
            # Obtain the membership name from the membership of Chat API.
            name='spaces/SPACE/members/MEMBERSHIP',
            updateMask='role',
            body={'role': 'ROLE_MEMBER'}
    
          ).execute()
    
        # Prints details about the updated membership.
        print(result)
    
    if __name__ == '__main__':
        main()
    
  3. בקוד, מחליפים את מה שכתוב בשדות הבאים:

    • SPACE: שם של מרחב משותף, שאפשר לקבל מה-method spaces.list ב-Chat API או מכתובת ה-URL של המרחב המשותף.

    • MEMBERSHIP: שם המינוי, שאותו אפשר לקבל דרך ה-method spaces.members.list ב-Chat API.

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

    python3 chat_membership_update.py
    

Node.js

  1. בספריית העבודה, יוצרים קובץ בשם chat_membership_update.js.
  2. יש לכלול את הקוד הבא ב-chat_membership_update.js:

    const chat = require('@googleapis/chat');
    const {authenticate} = require('@google-cloud/local-auth');
    
    /**
    * Updates a membership in a Chat space to change it from
    * a space manager to a space member.
    * @return {!Promise<!Object>}
    */
    async function updateSpace() {
    
      /**
      * Authenticate with Google Workspace
      * and get user authorization.
      */
      const scopes = [
        'https://www.googleapis.com/auth/chat.memberships',
      ];
    
      const authClient =
          await authenticate({scopes, keyfilePath: 'client_secrets.json'});
    
      /**
      * Build a service endpoint for Chat API.
      */
      const chatClient = await chat.chat({version: 'v1', auth: authClient});
    
      /**
      * Use the service endpoint to call Chat API.
      */
      return await chatClient.spaces.patch({
    
        /**
        * The membership to update, and the updated role.
        *
        * Replace SPACE with a space name.
        * Obtain the space name from the spaces resource of Chat API,
        * or from a space's URL.
        *
        * Replace MEMBERSHIP with a membership name.
        * Obtain the membership name from the membership of Chat API.
        */
        name: 'spaces/SPACE/members/MEMBERSHIP',
        updateMask: 'role',
        requestBody: {
          role: 'ROLE_MEMBER'
        }
      });
    }
    
    /**
    * Use the service endpoint to call Chat API.
    */
    updateSpace().then(console.log);
    
  3. בקוד, מחליפים את מה שכתוב בשדות הבאים:

    • SPACE: שם של מרחב משותף, שאפשר לקבל מה-method spaces.list ב-Chat API או מכתובת ה-URL של המרחב המשותף.

    • MEMBERSHIP: שם המינוי, שאותו אפשר לקבל דרך ה-method spaces.members.list ב-Chat API.

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

    python3 chat_membership_update.js
    

Apps Script

הדוגמה הזו מפעילה את Chat API באמצעות Advanced Chat Service.

  1. מוסיפים את היקף ההרשאה chat.memberships לקובץ appsscript.json של פרויקט Apps Script:

    "oauthScopes": [
      "https://www.googleapis.com/auth/chat.memberships"
    ]
    
  2. מוסיפים פונקציה כמו זו לקוד של הפרויקט ב-Apps Script:

    /**
     * Updates a membership from space manager to space member.
     * @param {string} memberName The resource name of the membership.
    */
    function updateMembershipToSpaceMember(memberName) {
      try {
        const body = {'role': 'ROLE_MEMBER'};
        Chat.Spaces.Members.patch(memberName, body);
      } catch (err) {
        // TODO (developer) - Handle exception
        console.log('Failed to create message with error %s', err.message);
      }
    }
    

ה-Google Chat API משנה את התפקיד שנבחר למנהל של המרחב המשותף, ומחזיר מופע של Membership שכולל את השינוי.