Cloud Functions を使用して HTTP Google Chat アプリを作成する

このページでは、HTTP Chat アプリを作成する方法について説明します。このアーキテクチャを実装する方法はいくつかあります。Google Cloud では、Cloud Functions、Cloud Run、App Engine を使用できます。このクイックスタートでは、Chat アプリがユーザーのメッセージに応答するために使用する Cloud Functions の関数を作成してデプロイします。

このアーキテクチャでは、次の図に示すように、HTTP を使用して Google Cloud またはオンプレミス サーバーと統合するように Chat を構成します。

オンプレミス サーバーでウェブサービスを使用する Chat アプリのアーキテクチャ。

上の図では、HTTP Chat アプリを操作するユーザーに次の情報のフローがあります。

  1. ユーザーが、Chat のダイレクト メッセージまたは Chat スペースで、Chat アプリにメッセージを送信します。
  2. HTTP リクエストは、Chat アプリのロジックを含むクラウドまたはオンプレミス システムのウェブサーバーに送信されます。
  3. Chat アプリのロジックは、必要に応じて Google Workspace サービス(カレンダー、スプレッドシートなど)、他の Google サービス(マップ、YouTube、Vertex AI など)、その他のウェブサービス(プロジェクト管理システムやチケット発行ツールなど)と統合できます。
  4. ウェブサーバーが HTTP レスポンスを Chat の Chat アプリサービスに返します。
  5. レスポンスがユーザーに送信されます。
  6. 必要に応じて、Chat アプリは Chat API を呼び出して、非同期でメッセージの投稿などのオペレーションを実行できます。

このアーキテクチャでは、システムにすでに存在する既存のライブラリとコンポーネントを柔軟に使用できます。これらの Chat アプリはさまざまなプログラミング言語を使用して設計できるためです。

目標

  • 環境を設定する。
  • Cloud Functions の関数を作成してデプロイする。
  • アプリを Chat に公開します。
  • アプリをテストします。

前提条件

環境を設定する

Google API を使用する前に、Google Cloud プロジェクトで有効にする必要があります。1 つの Google Cloud プロジェクトで 1 つ以上の API を有効にできます。
  • Google Cloud コンソールで、Google Chat API、Cloud Build API、Cloud Functions API、Cloud Pub/Sub API、Cloud Logging API、Artifact Registry API、Cloud Run API を有効にします。

    API を有効にする

Cloud 関数を作成してデプロイする

送信者の表示名とアバター画像を含む Chat カードを生成する Cloud Functions の関数を作成してデプロイします。Chat アプリがメッセージを受信すると、関数が実行され、カードが返されます。

Chat 用アプリ用の関数を作成してデプロイする手順は次のとおりです。

Node.js

  1. Google Cloud コンソールで、[Cloud Functions] ページに移動します。

    Cloud Functions に移動

    Chat アプリのプロジェクトが選択されていることを確認します。

  2. [ 関数を作成] をクリックします。

  3. [関数の作成] ページで、関数を設定します。

    1. [環境] で [第 2 世代] を選択します。
    2. [関数名] に「QuickStartChatApp」と入力します。
    3. [リージョン] でリージョンを選択します。
    4. [認証] で [認証が必要] を選択します。
    5. [次へ] をクリックします。
  4. [ランタイム] で、最新バージョンの Node.js を選択します。

  5. [ソースコード] で [インライン エディタ] を選択します。

  6. [エントリ ポイント] でデフォルトのテキストを削除し、「helloChat」と入力します。

  7. index.js の内容を次のコードに置き換えます。

    node/avatar-app/index.js
    /**
     * Google Cloud Function that responds to messages sent from a
     * Google Chat room.
     *
     * @param {Object} req Request sent from Google Chat room
     * @param {Object} res Response to send back
     */
    exports.helloChat = function helloChat(req, res) {
      if (req.method === 'GET' || !req.body.message) {
        res.send('Hello! This function is meant to be used in a Google Chat ' +
          'Room.');
      }
    
      const sender = req.body.message.sender.displayName;
      const image = req.body.message.sender.avatarUrl;
    
      const data = createMessage(sender, image);
    
      res.send(data);
    };
    
    /**
     * Creates a card with two widgets.
     * @param {string} displayName the sender's display name
     * @param {string} imageUrl the URL for the sender's avatar
     * @return {Object} a card with the user's avatar.
     */
    function createMessage(displayName, imageUrl) {
      const cardHeader = {
        title: `Hello ${displayName}!`,
      };
    
      const avatarWidget = {
        textParagraph: {text: 'Your avatar picture: '},
      };
    
      const avatarImageWidget = {
        image: {imageUrl},
      };
    
      const avatarSection = {
        widgets: [
          avatarWidget,
          avatarImageWidget,
        ],
      };
    
      return {
        text: 'Here\'s your avatar',
        cardsV2: [{
          cardId: 'avatarCard',
          card: {
            name: 'Avatar Card',
            header: cardHeader,
            sections: [avatarSection],
          }
        }],
      };
    }

  8. [Deploy] をクリックします。

Python

  1. Google Cloud コンソールで、[Cloud Functions] ページに移動します。

    Cloud Functions に移動

    Chat アプリのプロジェクトが選択されていることを確認します。

  2. [ 関数を作成] をクリックします。

  3. [関数の作成] ページで、関数を設定します。

    1. [環境] で [第 2 世代] を選択します。
    2. [関数名] に「QuickStartChatApp」と入力します。
    3. [リージョン] でリージョンを選択します。
    4. [認証] で [認証が必要] を選択します。
    5. [次へ] をクリックします。
  4. [ランタイム] で、最新バージョンの Python を選択します。

  5. [ソースコード] で [インライン エディタ] を選択します。

  6. [エントリ ポイント] でデフォルトのテキストを削除し、「hello_chat」と入力します。

  7. main.py の内容を次のコードに置き換えます。

    python/avatar-app/main.py
    from typing import Any, Mapping
    
    import flask
    import functions_framework
    
    
    # Google Cloud Function that responds to messages sent in
    # Google Chat.
    #
    # @param {Object} req Request sent from Google Chat.
    # @param {Object} res Response to send back.
    @functions_framework.http
    def hello_chat(req: flask.Request) -> Mapping[str, Any]:
      if req.method == "GET":
        return "Hello! This function must be called from Google Chat."
    
      request_json = req.get_json(silent=True)
    
      display_name = request_json["message"]["sender"]["displayName"]
      avatar = request_json["message"]["sender"]["avatarUrl"]
    
      response = create_message(name=display_name, image_url=avatar)
    
      return response
    
    
    # Creates a card with two widgets.
    # @param {string} name the sender's display name.
    # @param {string} image_url the URL for the sender's avatar.
    # @return {Object} a card with the user's avatar.
    def create_message(name: str, image_url: str) -> Mapping[str, Any]:
      avatar_image_widget = {"image": {"imageUrl": image_url}}
      avatar_text_widget = {"textParagraph": {"text": "Your avatar picture:"}}
      avatar_section = {"widgets": [avatar_text_widget, avatar_image_widget]}
    
      header = {"title": f"Hello {name}!"}
    
      cards = {
          "text": "Here's your avatar",
          "cardsV2": [
              {
                  "cardId": "avatarCard",
                  "card": {
                      "name": "Avatar Card",
                      "header": header,
                      "sections": [avatar_section],
                  },
              }
          ]
      }
    
      return cards

  8. [Deploy] をクリックします。

Java

  1. Google Cloud コンソールで、[Cloud Functions] ページに移動します。

    Cloud Functions に移動

    Chat アプリのプロジェクトが選択されていることを確認します。

  2. [ 関数を作成] をクリックします。

  3. [関数の作成] ページで、関数を設定します。

    1. [環境] で [第 2 世代] を選択します。
    2. [関数名] に「QuickStartChatApp」と入力します。
    3. [リージョン] でリージョンを選択します。
    4. [認証] で [認証が必要] を選択します。
    5. [次へ] をクリックします。
  4. [ランタイム] で、Java の最新バージョンを選択します。

  5. [ソースコード] で [インライン エディタ] を選択します。

  6. [エントリ ポイント] でデフォルトのテキストを削除し、「HelloChat」と入力します。

  7. src/main/java/com/example/Example.java から src/main/java/HelloChat.java に名前を変更しました。

  8. HelloChat.java の内容を次のコードに置き換えます。

    java/avatar-app/src/main/java/HelloChat.java
    import com.google.api.services.chat.v1.model.CardWithId;
    import com.google.api.services.chat.v1.model.GoogleAppsCardV1Card;
    import com.google.api.services.chat.v1.model.GoogleAppsCardV1CardHeader;
    import com.google.api.services.chat.v1.model.GoogleAppsCardV1Image;
    import com.google.api.services.chat.v1.model.GoogleAppsCardV1Section;
    import com.google.api.services.chat.v1.model.GoogleAppsCardV1TextParagraph;
    import com.google.api.services.chat.v1.model.GoogleAppsCardV1Widget;
    import com.google.api.services.chat.v1.model.Message;
    import com.google.cloud.functions.HttpFunction;
    import com.google.cloud.functions.HttpRequest;
    import com.google.cloud.functions.HttpResponse;
    import com.google.gson.Gson;
    import com.google.gson.JsonObject;
    import java.util.List;
    
    public class HelloChat implements HttpFunction {
      private static final Gson gson = new Gson();
    
      @Override
      public void service(HttpRequest request, HttpResponse response) throws Exception {
        JsonObject body = gson.fromJson(request.getReader(), JsonObject.class);
    
        if (request.getMethod().equals("GET") || !body.has("message")) {
          response.getWriter().write("Hello! This function must be called from Google Chat.");
          return;
        }
    
        JsonObject sender = body.getAsJsonObject("message").getAsJsonObject("sender");
        String displayName = sender.has("displayName") ? sender.get("displayName").getAsString() : "";
        String avatarUrl = sender.has("avatarUrl") ? sender.get("avatarUrl").getAsString() : "";
        Message message = createMessage(displayName, avatarUrl);
    
        response.getWriter().write(gson.toJson(message));
      }
    
      Message createMessage(String displayName, String avatarUrl) {
        GoogleAppsCardV1CardHeader cardHeader = new GoogleAppsCardV1CardHeader();
        cardHeader.setTitle(String.format("Hello %s!", displayName));
    
        GoogleAppsCardV1TextParagraph textParagraph = new GoogleAppsCardV1TextParagraph();
        textParagraph.setText("Your avatar picture: ");
    
        GoogleAppsCardV1Widget avatarWidget = new GoogleAppsCardV1Widget();
        avatarWidget.setTextParagraph(textParagraph);
    
        GoogleAppsCardV1Image image = new GoogleAppsCardV1Image();
        image.setImageUrl(avatarUrl);
    
        GoogleAppsCardV1Widget avatarImageWidget = new GoogleAppsCardV1Widget();
        avatarImageWidget.setImage(image);
    
        GoogleAppsCardV1Section section = new GoogleAppsCardV1Section();
        section.setWidgets(List.of(avatarWidget, avatarImageWidget));
    
        GoogleAppsCardV1Card card = new GoogleAppsCardV1Card();
        card.setName("Avatar Card");
        card.setHeader(cardHeader);
        card.setSections(List.of(section));
    
        CardWithId cardWithId = new CardWithId();
        cardWithId.setCardId("previewLink");
        cardWithId.setCard(card);
    
        Message message = new Message();
        message.setText("Here's your avatar");
        message.setCardsV2(List.of(cardWithId));
    
        return message;
      }
    }

  9. pom.xml の内容を次のコードに置き換えます。

    java/avatar-app/pom.xml
    <project xmlns="http://maven.apache.org/POM/4.0.0"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
      <modelVersion>4.0.0</modelVersion>
    
      <groupId>cloudfunctions</groupId>
      <artifactId>http-function</artifactId>
      <version>1.0-SNAPSHOT</version>
    
      <properties>
        <maven.compiler.target>11</maven.compiler.target>
        <maven.compiler.source>11</maven.compiler.source>
      </properties>
    
      <dependencies>
        <dependency>
          <groupId>com.google.cloud.functions</groupId>
          <artifactId>functions-framework-api</artifactId>
          <version>1.0.1</version>
        </dependency>
    
        <!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.9.1</version>
        </dependency>
    
        <!-- https://mvnrepository.com/artifact/com.google.apis/google-api-services-chat -->
        <dependency>
          <groupId>com.google.apis</groupId>
          <artifactId>google-api-services-chat</artifactId>
          <version>v1-rev20230115-2.0.0</version>
        </dependency>
      </dependencies>
    
      <!-- Required for Java 11 functions in the inline editor -->
      <build>
        <plugins>
          <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.8.1</version>
            <configuration>
              <excludes>
                <exclude>.google/</exclude>
              </excludes>
            </configuration>
          </plugin>
        </plugins>
      </build>
    </project>

  10. [Deploy] をクリックします。

Cloud Functions の詳細ページが開き、関数に 2 つの進行状況インジケーターが表示されます。1 つはビルド用で、もう 1 つはサービス用です。両方の進行状況インジケーターが表示されなくなり、チェックマークに変わると、関数がデプロイされて準備が整います。

関数の呼び出しを Google Chat に許可する

Google Chat が関数を呼び出すことを承認するには、Cloud Run 起動元ロールを持つ Google Chat サービス アカウントを追加します。

  1. Google Cloud コンソールで、[Cloud Run] ページに移動します。

    Cloud Run に移動

  2. Cloud Run サービスリストで、受信側関数の横にあるチェックボックスをオンにします。(関数自体はクリックしないでください)。

  3. [権限] をクリックします。[権限] パネルが開きます。

  4. [プリンシパルを追加] をクリックします。

  5. [新しいプリンシパル] に「chat@system.gserviceaccount.com」と入力します。

  6. [ロールを選択] で、[Cloud Run] > [Cloud Run 起動元] を選択します。

  7. [保存] をクリックします。

アプリを Google Chat に公開する

Cloud Functions の関数をデプロイしたら、次の手順で Google Chat アプリに変換します。

  1. Google Cloud コンソールで、メニュー アイコン > [Cloud Functions] をクリックします。

    Cloud Functions に移動

    Cloud Functions を有効にしたプロジェクトが選択されていることを確認します。

  2. 関数のリストで、[QuickStartChatApp] をクリックします。

  3. [トリガー] タブをクリックします。

  4. [HTTPS] の下の URL をコピーします。

  5. 「Google Chat API」を検索して、[Google Chat API]、[管理] の順にクリックします。

    Chat API に移動

  6. [Configuration] をクリックし、Google Chat アプリを設定します。

    1. [アプリ名] に「Quickstart App」と入力します。
    2. [アバターの URL] に「https://developers.google.com/chat/images/quickstart-app-avatar.png」と入力します。
    3. [説明] に「Quickstart app」と入力します。
    4. [機能] で、[1:1 のメッセージを受信する] と [スペースとグループの会話に参加する] を選択します。
    5. [接続設定] で [アプリの URL] を選択し、Cloud Functions の関数トリガーの URL をボックスに貼り付けます。
    6. [Authentication Audience] で、[App URL] を選択します。
    7. [公開設定] で、[ドメイン内の特定のユーザーとグループにこの Google Chat アプリの利用を許可する] を選択し、メールアドレスを入力します。
    8. [ログ] で、[エラーを Logging にロギング] を選択します。
  7. [保存] をクリックします。

Chat 用アプリで、Chat でメッセージを受信して応答する準備が整いました。

Chat 用アプリをテストする

Chat アプリをテストするには、Chat アプリでダイレクト メッセージ スペースを開き、メッセージを送信します。

  1. 自分自身を Trusted Tester として追加したときに指定した Google Workspace アカウントを使用して Google Chat を開きます。

    Google Chat にアクセス

  2. [ チャットを新規作成] をクリックします。
  3. [1 人以上のユーザーを追加] フィールドに、Chat アプリの名前を入力します。
  4. 結果から Chat 用アプリを選択します。ダイレクト メッセージが開きます。

  5. アプリとの新しいダイレクト メッセージで、「Hello」と入力して enter キーを押します。

Chat アプリのレスポンスには、次の図に示すように、送信者の名前とアバター画像を表示するカード メッセージが含まれます。

送信者の表示名とアバター画像を含むカードで応答している Chat アプリの

Trusted Tester を追加する方法と、インタラクティブ機能のテストについて詳しくは、Google Chat アプリのインタラクティブ機能をテストするをご覧ください。

トラブルシューティング

Google Chat アプリまたはカードがエラーを返すと、Chat インターフェースに「エラーが発生しました」というメッセージが表示されます。または「リクエストを処理できません」が表示されます。Chat UI にエラー メッセージが表示されなくても、Chat アプリやカードが予期しない結果(カード メッセージが表示されないなど)を生成することがあります。

Chat UI にエラー メッセージが表示されない場合がありますが、Chat 用アプリのエラーロギングが有効になっている場合は、説明的なエラー メッセージとログデータを使用してエラーを修正できます。エラーの表示、デバッグ、修正については、Google Chat のエラーのトラブルシューティングと修正をご覧ください。

クリーンアップ

このチュートリアルで使用したリソースについて、Google Cloud アカウントに課金されないようにするには、Cloud プロジェクトを削除することをおすすめします。

  1. Google Cloud コンソールで、[リソースの管理] ページに移動します。メニュー アイコン > [IAM と管理] > [リソースの管理] をクリックします。

    Resource Manager に移動

  2. プロジェクト リストで、削除するプロジェクトを選択し、[削除] をクリックします。
  3. ダイアログでプロジェクト ID を入力し、[シャットダウン] をクリックしてプロジェクトを削除します。