高度なチャット サービス

Chat スペース、メンバー、メッセージを管理する。

高度なチャット サービスを使用すると、Google Apps Script で Google Chat API を使用できます。この API を使用すると、スクリプトで Chat スペースの検索、作成、変更、スペースへのメンバーの追加または削除、テキスト、カード、添付ファイル、リアクションを含むメッセージの読み取りまたは投稿を行えます。

前提条件

これは、使用前に有効にする必要がある拡張サービスです。

リファレンス

このサービスの詳細については、Chat API リファレンス ドキュメントをご覧ください。Apps Script のすべての高度なサービスと同様に、Chat サービスでは、公開 API と同じオブジェクト、メソッド、パラメータを使用します。

サンプルコード

これらのサンプルでは、高度なサービスを使用して一般的な Google Chat API アクションを実行する方法を示します。

ユーザー認証情報を使用してメッセージを投稿する

次の例は、ユーザーに代わって Chat スペースにメッセージを投稿する方法を示しています。

  1. Apps Script プロジェクトの appsscript.json ファイルに chat.messages.create 認証スコープを追加します。

    "oauthScopes": [
      "https://www.googleapis.com/auth/chat.messages.create"
    ]
    
  2. 次のような関数を Apps Script プロジェクトのコードに追加します。

    advanced/chat.gs
    /**
     * Posts a new message to the specified space on behalf of the user.
     * @param {string} spaceName The resource name of the space.
     */
    function postMessageWithUserCredentials(spaceName) {
      try {
        const message = { text: "Hello world!" };
        Chat.Spaces.Messages.create(message, spaceName);
      } catch (err) {
        // TODO (developer) - Handle exception
        console.log("Failed to create message with error %s", err.message);
      }
    }

アプリの認証情報を含むメッセージを投稿する

次の例は、アプリに代わって Chat スペースにメッセージを投稿する方法を示しています。サービス アカウントで高度な Chat サービスを使用する場合、appsscript.json で認可スコープを指定する必要はありません。サービス アカウントを使用した認証の詳細については、Google Chat 用アプリとして認証するをご覧ください。

advanced/chat.gs
/**
 * Posts a new message to the specified space on behalf of the app.
 * @param {string} spaceName The resource name of the space.
 */
function postMessageWithAppCredentials(spaceName) {
  try {
    // See https://developers.google.com/chat/api/guides/auth/service-accounts
    // for details on how to obtain a service account OAuth token.
    const appToken = getToken_();
    const message = { text: "Hello world!" };
    Chat.Spaces.Messages.create(
      message,
      spaceName,
      {},
      // Authenticate with the service account token.
      { Authorization: `Bearer ${appToken}` },
    );
  } catch (err) {
    // TODO (developer) - Handle exception
    console.log("Failed to create message with error %s", err.message);
  }
}

スペースを取得する

次の例は、Chat スペースに関する情報を取得する方法を示しています。

  1. Apps Script プロジェクトの appsscript.json ファイルに chat.spaces.readonly 認証スコープを追加します。

    "oauthScopes": [
      "https://www.googleapis.com/auth/chat.spaces.readonly"
    ]
    
  2. 次のような関数を Apps Script プロジェクトのコードに追加します。

    advanced/chat.gs
    /**
     * Gets information about a Chat space.
     * @param {string} spaceName The resource name of the space.
     */
    function getSpace(spaceName) {
      try {
        const space = Chat.Spaces.get(spaceName);
        console.log("Space display name: %s", space.displayName);
        console.log("Space type: %s", space.spaceType);
      } catch (err) {
        // TODO (developer) - Handle exception
        console.log("Failed to get space with error %s", err.message);
      }
    }

スペースを作成

次の例は、Chat スペースを作成する方法を示しています。

  1. Apps Script プロジェクトの appsscript.json ファイルに chat.spaces.create 認証スコープを追加します。

    "oauthScopes": [
      "https://www.googleapis.com/auth/chat.spaces.create"
    ]
    
  2. 次のような関数を Apps Script プロジェクトのコードに追加します。

    advanced/chat.gs
    /**
     * Creates a new Chat space.
     */
    function createSpace() {
      try {
        const space = { displayName: "New Space", spaceType: "SPACE" };
        Chat.Spaces.create(space);
      } catch (err) {
        // TODO (developer) - Handle exception
        console.log("Failed to create space with error %s", err.message);
      }
    }

メンバーシップの一覧表示

次の例は、Chat スペースのすべてのメンバーを一覧表示する方法を示しています。

  1. Apps Script プロジェクトの appsscript.json ファイルに chat.memberships.readonly 認証スコープを追加します。

    "oauthScopes": [
      "https://www.googleapis.com/auth/chat.memberships.readonly"
    ]
    
  2. 次のような関数を Apps Script プロジェクトのコードに追加します。

    advanced/chat.gs
    /**
     * Lists all the members of a Chat space.
     * @param {string} spaceName The resource name of the space.
     */
    function listMemberships(spaceName) {
      let response;
      let pageToken = null;
      try {
        do {
          response = Chat.Spaces.Members.list(spaceName, {
            pageSize: 10,
            pageToken: pageToken,
          });
          if (!response.memberships || response.memberships.length === 0) {
            pageToken = response.nextPageToken;
            continue;
          }
          for (const membership of response.memberships) {
            console.log(
              "Member: %s, Role: %s",
              membership.member.displayName,
              membership.role,
            );
          }
          pageToken = response.nextPageToken;
        } while (pageToken);
      } catch (err) {
        // TODO (developer) - Handle exception
        console.log("Failed with error %s", err.message);
      }
    }

トラブルシューティング

Error 400: invalid_scope エラーと Some requested scopes cannot be shown エラー メッセージが表示された場合は、Apps Script プロジェクトの appsscript.json ファイルで承認スコープが指定されていません。ほとんどの場合、Apps Script はスクリプトに必要なスコープを自動的に判断しますが、Chat の高度なサービスを使用する場合は、スクリプトで使用する承認スコープを Apps Script プロジェクトのマニフェスト ファイルに手動で追加する必要があります。明示的なスコープの設定をご覧ください。

このエラーを解決するには、oauthScopes 配列の一部として、適切な認証スコープを Apps Script プロジェクトの appsscript.json ファイルに追加します。たとえば、spaces.messages.create メソッドを呼び出すには、次のように追加します。

"oauthScopes": [
  "https://www.googleapis.com/auth/chat.messages.create"
]

制限事項と考慮事項

高度なチャット サービスでは、次の機能はサポートされていません。

メッセージの添付ファイルをダウンロードしたり、デベロッパー プレビュー メソッドを呼び出したりするには、代わりに UrlFetchApp を使用します。