本指南說明如何在 Google Chat API 的 Reaction
資源上使用 create
方法,以便對訊息新增回應,例如 👍?、🚲? 以及 Θ。
Reaction
資源代表可供使用者回應訊息的表情符號,例如 👍?、🚲? 以及 Θ。
先備知識
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.messages.reactions.create
、chat.messages.reactions
或chat.messages
授權範圍的使用者驗證。
對訊息新增回應
如要建立訊息的回應,請在要求中傳遞以下內容:
- 指定
chat.messages.reactions.create
、chat.messages.reactions
或chat.messages
授權範圍。 - 呼叫
Reaction
資源上的create
方法。 - 將
parent
設為要回應的訊息資源名稱。 - 將
body
(要求主體) 設為Reaction
的執行個體,其中unicode
欄位是以萬國碼 (Unicode) 字串表示的標準表情符號。
以下範例使用 😀? 表情符號回應訊息:
Python
- 在工作目錄中,建立名為
chat_reaction_create.py
的檔案。 在
chat_reaction_create.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.messages.reactions.create"] def main(): ''' Authenticates with Chat API via user credentials, then creates a reaction to a message. ''' # 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().messages().reactions().create( # The message to create a reaction to. # # Replace SPACE with a space name. # Obtain the space name from the spaces resource of Chat API, # or from a space's URL. # # Replace MESSAGE with a message name. # Obtain the message name from the response body returned # after creating a message asynchronously with Chat REST API. parent = 'spaces/SPACE/messages/MESSAGE', # The reaction to the message. body = { 'emoji': { # A standard emoji represented by a unicode string. 'unicode': '😀' } } ).execute() # Prints details about the created reaction. print(result) if __name__ == '__main__': main()
請在程式碼中替換下列內容:
SPACE
:訊息張貼所在的聊天室name
,您可以從 Chat API 的spaces.list
方法或聊天室網址取得。MESSAGE
:訊息名稱。使用 Chat API 以非同步方式建立訊息後,可以從回應主體取得的訊息名稱,或是在建立訊息時指派給該訊息的自訂名稱。
在工作目錄中建構並執行範例:
python3 chat_reaction_create.py
Chat API 會傳回 Reaction
的執行個體,用於詳細說明建立的回應。