このガイドでは、Google Chat API の Reaction
リソースの create
メソッドを使用して、メッセージにリアクション(👍?、🚲?、背景など)を追加する方法について説明します。
Reaction
リソースは、人々がメッセージにリアクションするために使用できる絵文字を表します(👍?、🚲?、feedback など)。
前提条件
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
メソッドまたはスペースの URL から取得できます。MESSAGE
: メッセージ名。Chat API と非同期でメッセージを作成した後に返されたレスポンスの本文から取得するか、作成時にメッセージに割り当てられたカスタム名を使用して取得できます。
作業ディレクトリで、サンプルをビルドして実行します。
python3 chat_reaction_create.py
Chat API は、作成されたリアクションの詳細を含む Reaction
のインスタンスを返します。