本指南說明如何針對 Google Chat API 的 membership
資源使用 delete
方法,從聊天室 (也就是刪除成員資格) 中移除成員。如果聊天室管理員是聊天室中唯一的聊天室管理員,您就無法移除對方。請先指派其他使用者擔任聊天室管理員,再移除這些成員。
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
授權範圍的使用者驗證。
從聊天室中移除成員
如要從聊天室中移除使用者、Google 群組或 Chat 應用程式:
- 如要移除使用者或 Google 群組,請指定
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" }