本指南說明如何針對 Google Chat API 的 membership
資源使用 delete
方法,從聊天室 (也稱為刪除成員) 中移除使用者或 Chat 應用程式。如果聊天室管理員是聊天室中唯一的聊天室管理員,則無法移除聊天室。請先指派其他使用者擔任聊天室管理員,再移除這些成員資格。
Membership
資源表示是否要邀請真人使用者或 Google Chat 應用程式加入或離開聊天室。
必要條件
Python
- Python 3.6 以上版本
- pip 套件管理工具
最新的 Python 專用 Google 用戶端程式庫。如要安裝或更新,請在指令列介面中執行下列指令:
pip3 install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib oauth2client
已發布的 Chat 應用程式。如要建立及發布 Chat 應用程式,請參閱「建構 Google Chat 應用程式」。
已設定 Chat 應用程式的授權。如要刪除成員資格,使用者必須具有
chat.memberships
或chat.memberships.app
授權範圍的使用者驗證,該使用者有權刪除指定成員資格。
從聊天室中移除使用者或 Chat 應用程式
如要從聊天室中移除使用者或 Chat 應用程式,請按照下列步驟操作:
- 如要移除使用者,請指定
chat.memberships
授權範圍。如要移除即時通訊應用程式,請指定chat.memberships.app
授權範圍 (應用程式只能刪除自己的成員資格,其他應用程式無法刪除)。最佳做法是選擇仍能讓應用程式正常運作的最大範圍。 - 呼叫
membership
資源上的delete
方法。 - 傳遞會籍的
name
,以便刪除。如果成員資格屬於聊天室中唯一的聊天室管理員,在刪除這個成員資格前,請先指派其他使用者做為聊天室管理員。
刪除會員資格的方法如下:
Python
- 在工作目錄中,建立名為
chat_membership_delete.py
的檔案。 在
chat_membership_delete.py
中加入下列程式碼:import os.path from google.auth.transport.requests import Request from google.oauth2.credentials import Credentials from google_auth_oauthlib.flow import InstalledAppFlow from googleapiclient.discovery import build from googleapiclient.errors import HttpError # 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.app"] def main(): ''' Authenticates with Chat API via user credentials, then deletes the specified membership. ''' # 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().delete( # The membership to delete. # # Replace SPACE with a space name. # Obtain the space name from the spaces resource of Chat API, # or from a space's URL. # # Replace MEMBER with a membership name. # Obtain the membership name from the memberships resource of # Chat API. To delete a Chat app's membership, replace MEMBER # with app; an alias for the app calling the API. name='spaces/SPACE/members/MEMBER' ).execute() # Print Chat API's response in your command line interface. # When deleting a membership, the response body is empty. print(result) if __name__ == '__main__': main()
在程式碼中,替換以下內容:
SPACE
:可從 Chat API 的spaces.list
方法或聊天室網址取得的聊天室名稱。MEMBER
:會員名稱,可從 Chat API 的spaces.members.list
方法取得。如要刪除應用程式的會員,請將MEMBER
替換為app
。
在工作目錄中建構並執行範例:
python3 chat_membership_delete.py
如果成功,回應主體會傳回含有 'state': 'NOT_A_MEMBER'
的成員資格,表示該成員已不在聊天室中。
{ "name": "spaces/SPACE/members/MEMBER", "state": "NOT_A_MEMBER" }