[Video](https://www.youtube.com/watch?v=GO9_MQLcxGE)

The Advanced Chat service lets you use the
[Google Chat API](https://developers.google.com/chat/api/guides) in Google Apps Script. This API lets
scripts find, create, and modify Chat spaces, add or remove
members to spaces, and read or post messages with text, cards, attachments, and
reactions.

## Prerequisites

- An Apps Script Google Chat app configured on the Chat API configuration page in the Google Cloud console. The app's Apps Script project must use a standard Google Cloud project instead of the default one created automatically for Apps Script projects. To create a compatible Google Chat app, see [Build a Google Chat app with Google Apps Script](https://developers.google.com/workspace/chat/quickstart/apps-script-app).
- Authentication configured for the Chat app. Performing an action on behalf of a user requires [user authentication](https://developers.google.com/chat/api/guides/auth/users). Performing an action as the Chat app requires [app authentication with a service account](https://developers.google.com/chat/api/guides/auth/service-accounts). To check which form of authentication a Chat API method supports, see [Types of required authentication for Google Chat API calls](https://developers.google.com/chat/api/guides/auth#asynchronous-chat-calls).

This is an advanced service that you must
[turn on before use](https://developers.google.com/apps-script/guides/services/advanced).

## Reference

For more information about this service, see the
[Chat API reference documentation](https://developers.google.com/chat/api/reference/rest).
Like all advanced services in Apps Script, the
Chat service uses the same objects, methods, and parameters as
the public API.

## Sample code

These samples show you how to perform common
[Google Chat API](https://developers.google.com/chat/api/guides)
actions using the advanced service.

### Post a message with user credentials

The following example demonstrates how to post a message to a
Chat space on behalf of the user.

1. Add the `chat.messages.create` authorization scope to the
   Apps Script project's `appsscript.json` file:

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

2. Add a function like this one to the Apps Script project's
   code:

   advanced/chat.gs [View on GitHub](https://github.com/googleworkspace/apps-script-samples/blob/main/advanced/chat.gs)

   ```javascript
   /**
    * 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);
     }
   }
   ```

### Post a message with app credentials

The following example demonstrates how to post a message to a
Chat space on behalf of the app. Using the advanced
Chat service with a service account doesn't require you to
specify authorization scopes in `appsscript.json`. For details about
authentication with service accounts, see
[Authenticate as a Google Chat app](https://developers.google.com/chat/api/guides/auth/service-accounts).
advanced/chat.gs [View on GitHub](https://github.com/googleworkspace/apps-script-samples/blob/main/advanced/chat.gs)

```javascript
/**
 * 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);
  }
}
```

### Get a space

The following example demonstrates how to get information about a
Chat space.

1. Add the `chat.spaces.readonly` authorization scope to the
   Apps Script project's `appsscript.json` file:

       "oauthScopes": [
         "https://www.googleapis.com/auth/chat.spaces.readonly"
       ]

2. Add a function like this one to the Apps Script project's
   code:

   advanced/chat.gs [View on GitHub](https://github.com/googleworkspace/apps-script-samples/blob/main/advanced/chat.gs)

   ```javascript
   /**
    * 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);
     }
   }
   ```

### Create a space

The following example demonstrates how to create a Chat space.

1. Add the `chat.spaces.create` authorization scope to the
   Apps Script project's `appsscript.json` file:

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

2. Add a function like this one to the Apps Script project's
   code:

   advanced/chat.gs [View on GitHub](https://github.com/googleworkspace/apps-script-samples/blob/main/advanced/chat.gs)

   ```javascript
   /**
    * 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);
     }
   }
   ```

### List memberships

The following example demonstrates how to list all the members of a
Chat space.

1. Add the `chat.memberships.readonly` authorization scope to the
   Apps Script project's `appsscript.json` file:

       "oauthScopes": [
         "https://www.googleapis.com/auth/chat.memberships.readonly"
       ]

2. Add a function like this one to the Apps Script project's
   code:

   advanced/chat.gs [View on GitHub](https://github.com/googleworkspace/apps-script-samples/blob/main/advanced/chat.gs)

   ```javascript
   /**
    * 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);
     }
   }
   ```

### Search messages

The following example demonstrates how to search for unread messages for the
calling user in all Chat spaces.

1. Add the `chat.messages.readonly` and the `chat.users.readstate.readonly`
   authorization scopes to the Apps Script project's
   `appsscript.json` file:

       "oauthScopes": [
         "https://www.googleapis.com/auth/chat.messages.readonly",
         "https://www.googleapis.com/auth/chat.users.readstate.readonly"
       ]

2. Add a function like this one to the Apps Script project's
   code:

   advanced/chat.gs [View on GitHub](https://github.com/googleworkspace/apps-script-samples/blob/main/advanced/chat.gs)

   ```javascript
   /**
    * Searches for unread messages for the caller user in all Chat spaces.
    */
   function searchMessages() {
     let response;
     let pageToken = null;
     try {
       do {
         response = Chat.Spaces.Messages.search(
           {
             filter: 'is_unread()'
           },
           'spaces/-',
           {
             pageSize: 10,
             pageToken: pageToken,
           }
         );
         if (!response.results || response.results.length === 0) {
           pageToken = response.nextPageToken;
           continue;
         }
         for (const result of response.results) {
           const message = result.message;
           console.log(
             "**%s at %s in %s:**\n%s",
             message.sender.name,
             message.createTime,
             message.space.name,
             message.text,
           );
         }
         pageToken = response.nextPageToken;
       } while (pageToken);
     } catch (err) {
       // TODO (developer) - Handle exception
       console.log("Failed with error %s", err.message);
     }
   }
   ```

## Troubleshoot

If you encounter `Error 400: invalid_scope` with the error message
`Some requested scopes cannot be shown`,
it means you haven't specified any authorization scopes in the
Apps Script project's `appsscript.json` file. In most cases,
Apps Script automatically determines what scopes a script needs,
but when you use the Chat advanced service, you must manually add
the authorization scopes that your script uses to your
Apps Script project's manifest file. See
[Setting explicit scopes](https://developers.google.com/apps-script/concepts/scopes#setting_explicit_scopes).

To resolve the error, add the appropriate authorization scopes
to the Apps Script project's `appsscript.json` file as part of
the `oauthScopes` array. For example, to call the
[`spaces.messages.create`](https://developers.google.com/chat/api/reference/rest/v1/spaces.messages/create)
method, add the following:

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

## Limits and considerations

The Advanced Chat service doesn't support:

- The Chat API method [`media.download`](https://developers.google.com/chat/api/reference/rest/v1/media/download).
- Chat API methods available in [Developer Preview](https://developers.google.com/workspace/preview)

To download a message attachment or call a developer preview method, use
[`UrlFetchApp`](https://developers.google.com/apps-script/reference/url-fetch/url-fetch-app) instead.