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

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

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

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

Python

  • Python 3.6 ומעלה
  • הכלי לניהול חבילות pip
  • ספריות הלקוח העדכניות של Google. כדי להתקין או לעדכן אותם, מריצים את הפקודה הבאה בממשק שורת הפקודה:
    pip3 install --upgrade google-api-python-client google-auth-oauthlib
    

Node.js

  • Node.js 14 ומעלה
  • ה-npm כלי לניהול חבילות
  • ספריות הלקוח העדכניות של Google. כדי להתקין או לעדכן אותם, מריצים את הפקודה הבאה בממשק שורת הפקודה:
    npm install @google-cloud/local-auth @googleapis/chat
    

Apps Script

עדכון מינוי

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

  • מציינים את היקף ההרשאה chat.memberships.
  • קוראים לפונקציה שיטת 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. בקוד, מחליפים את מה שכתוב בשדות הבאים:

  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. בקוד, מחליפים את מה שכתוב בשדות הבאים:

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

    python3 chat_membership_update.js
    

Apps Script

בדוגמה הזו מתבצעת קריאה ל-Chat API באמצעות שירות Chat מתקדם.

  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. בקוד, מחליפים את מה שכתוב בשדות הבאים:

  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. בקוד, מחליפים את מה שכתוב בשדות הבאים:

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

    python3 chat_membership_update.js
    

Apps Script

בדוגמה הזו מתבצעת קריאה ל-Chat API באמצעות שירות Chat מתקדם.

  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 ופירוט של השינוי.