本指南說明如何在 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-oauthlib
- 已啟用並設定 Google Chat API 的 Google Cloud 專案。相關步驟請參閱「建構 Google Chat 應用程式」。
已針對 Chat 應用程式設定授權。如要刪除成員資格,使用者必須具有
chat.memberships
或chat.memberships.app
授權範圍的使用者驗證,且該使用者有權刪除指定成員資格。
從聊天室中移除使用者或 Chat 應用程式
如何從聊天室中移除使用者或 Chat 應用程式:
- 如要移除使用者,請指定
chat.memberships
授權範圍。如要移除 Chat 應用程式,請指定chat.memberships.app
授權範圍 (應用程式只能刪除自己的成員資格,無法從其他應用程式刪除)。最佳做法是選擇最嚴格的範圍,確保應用程式仍可正常運作。 - 呼叫
membership
資源上的delete
方法。 - 傳遞要刪除的會員資格
name
。如果成員是聊天室中唯一的聊天室管理員,請先指派其他使用者擔任聊天室管理員,再刪除這個成員資格。
刪除會員資格的方法如下:
Python
- 在工作目錄中,建立名為
chat_membership_delete.py
的檔案。 在
chat_membership_delete.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.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" }