本指南說明如何針對 Google Chat API 的 Space
資源使用 create
方法建立已命名聊天室。
Space
資源代表使用者可以和 Chat 應用程式傳送訊息、共用檔案及進行協同合作的位置。聊天室分為以下幾種類型:
- 即時訊息 (DM) 是兩位使用者或使用者和 Chat 應用程式之間的對話。
- 群組通訊是指三位以上使用者和 Chat 應用程式之間的對話。
- 已命名的聊天室是永久的地方,可讓使用者傳送訊息、共用檔案及協同合作。
已命名聊天室是使用者傳送訊息、共用檔案及協作的空間。已命名聊天室可包含 Chat 應用程式。已命名聊天室包含未命名群組對話和即時訊息沒有的額外功能,例如聊天室管理員可以套用管理設定、說明,以及新增或移除使用者和應用程式。建立已命名聊天室後,聊天室的唯一成員是通過驗證的使用者。聊天室不含其他使用者或應用程式,甚至是建立聊天室的 Chat 應用程式。如要新增使用者,請呼叫 Member
資源上的 create
方法,以在聊天室中建立成員資格。如要瞭解如何建立會員資格,請參閱這篇文章。
如要建立內含多位成員的已命名聊天室 (三人以上的未命名群組通訊,或兩個人之間的即時訊息對話,或使用者與呼叫 Chat API 的 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.spaces.create
或chat.spaces
授權範圍的使用者驗證。
建立已命名聊天室
如要建立已命名聊天室,請在要求中傳遞以下內容:
- 指定
chat.spaces.create
或chat.spaces
授權範圍。 - 呼叫
Space
資源上的create
方法。 - 將
spaceType
設為SPACE
。 - 將
displayName
設為使用者可見的聊天室名稱。在以下範例中,displayName
設為API-made
。 - 您也可以選擇設定其他空間屬性,例如
spaceDetails
(使用者可看見的聊天室說明和一組規範規範)。
建立已命名聊天室的方法如下:
Python
- 在工作目錄中,建立名為
chat_space_create_named.py
的檔案。 在
chat_space_create_named.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.spaces.create"] def main(): ''' Authenticates with Chat API via user credentials, then creates a Chat space. ''' # 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().create( # Details about the space to create. body = { # To create a named space, set spaceType to SPACE. 'spaceType': 'SPACE', # The user-visible name of the space. 'displayName': 'API-made' } ).execute() # Prints details about the created membership. print(result) if __name__ == '__main__': main()
在工作目錄中建構並執行範例:
python3 chat_space_create_named.py
已建立已命名的聊天室。如要前往聊天室,請使用空間的資源 ID 建構聊天室網址。您可以在 Google Chat 回應主體中找到來自 name
聊天室的資源 ID。舉例來說,如果空間的 name
為 spaces/1234567
,您可以使用下列網址前往該聊天室:https://mail.google.com/chat/u/0/#chat/space/1234567
。