This guide explains how to use the Google Chat API to manage a user's
availability status and custom status.

To read and update the availability of a Chat user, your app must authenticate
with [user authentication](https://developers.google.com/workspace/chat/authenticate-authorize-chat-user).
Only the authenticated user's availability can be accessed or modified.

## Prerequisites


### Node.js

- A Business or Enterprise [Google Workspace](https://support.google.com/a/answer/6043576) account with access to [Google Chat](https://workspace.google.com/products/chat/).

<!-- -->

- Set up your environment:
  - [Create a Google Cloud project](https://developers.google.com/workspace/guides/create-project).
  - [Configure the OAuth consent screen](https://developers.google.com/workspace/guides/configure-oauth-consent).
  - [Enable and configure the Google Chat API](https://developers.google.com/workspace/chat/configure-chat-api) with a name, icon, and description for your Chat app.
  - Install the Node.js [Cloud Client Library](https://developers.google.com/workspace/chat/libraries?tab=nodejs#cloud-client-libraries).
  - [Create OAuth client ID credentials](https://developers.google.com/workspace/chat/authenticate-authorize-chat-user#step-2:) for a desktop application. To run the sample in this guide, save the credentials as a JSON file named `credentials.json` to your local directory.

  For guidance, complete the steps for setting up your environment in this [quickstart](https://developers.google.com/workspace/chat/api/guides/quickstart/nodejs
  #set-up-environment).
- [Choose an authorization scope](https://developers.google.com/workspace/chat/authenticate-authorize#asynchronous-chat-calls) that supports user authentication.

### Python

- A Business or Enterprise [Google Workspace](https://support.google.com/a/answer/6043576) account with access to [Google Chat](https://workspace.google.com/products/chat/).

<!-- -->

- Set up your environment:
  - [Create a Google Cloud project](https://developers.google.com/workspace/guides/create-project).
  - [Configure the OAuth consent screen](https://developers.google.com/workspace/guides/configure-oauth-consent).
  - [Enable and configure the Google Chat API](https://developers.google.com/workspace/chat/configure-chat-api) with a name, icon, and description for your Chat app.
  - Install the Python [Cloud Client Library](https://developers.google.com/workspace/chat/libraries?tab=python#cloud-client-libraries).
  - [Create OAuth client ID credentials](https://developers.google.com/workspace/chat/authenticate-authorize-chat-user#step-2:) for a desktop application. To run the sample in this guide, save the credentials as a JSON file named `credentials.json` to your local directory.

  For guidance, complete the steps for setting up your environment in this [quickstart](https://developers.google.com/workspace/chat/api/guides/quickstart/python
  #set-up-environment).
- [Choose an authorization scope](https://developers.google.com/workspace/chat/authenticate-authorize#asynchronous-chat-calls) that supports user authentication.

### Java

- A Business or Enterprise [Google Workspace](https://support.google.com/a/answer/6043576) account with access to [Google Chat](https://workspace.google.com/products/chat/).

<!-- -->

- Set up your environment:
  - [Create a Google Cloud project](https://developers.google.com/workspace/guides/create-project).
  - [Configure the OAuth consent screen](https://developers.google.com/workspace/guides/configure-oauth-consent).
  - [Enable and configure the Google Chat API](https://developers.google.com/workspace/chat/configure-chat-api) with a name, icon, and description for your Chat app.
  - Install the Java [Cloud Client Library](https://developers.google.com/workspace/chat/libraries?tab=java#cloud-client-libraries).
  - [Create OAuth client ID credentials](https://developers.google.com/workspace/chat/authenticate-authorize-chat-user#step-2:) for a desktop application. To run the sample in this guide, save the credentials as a JSON file named `credentials.json` to your local directory.

  For guidance, complete the steps for setting up your environment in this [quickstart](https://developers.google.com/workspace/chat/api/guides/quickstart/java
  #set-up-environment).
- [Choose an authorization scope](https://developers.google.com/workspace/chat/authenticate-authorize#asynchronous-chat-calls) that supports user authentication.

### Apps Script

- A Business or Enterprise [Google Workspace](https://support.google.com/a/answer/6043576) account with access to [Google Chat](https://workspace.google.com/products/chat/).

<!-- -->

- Set up your environment:
  - [Create a Google Cloud project](https://developers.google.com/workspace/guides/create-project).
  - [Configure the OAuth consent screen](https://developers.google.com/workspace/guides/configure-oauth-consent).
  - [Enable and configure the Google Chat API](https://developers.google.com/workspace/chat/configure-chat-api) with a name, icon, and description for your Chat app.
  - [Create a standalone Apps Script project](https://developers.google.com/apps-script/guides/projects), and turn on the [Advanced Chat Service](https://developers.google.com/apps-script/advanced/chat).

  For steps to set up your environment, complete this [quickstart](https://developers.google.com/workspace/chat/api/guides/quickstart/apps-script).
- [Choose an authorization scope](https://developers.google.com/workspace/chat/authenticate-authorize#asynchronous-chat-calls) that supports user authentication.


> [!NOTE]
> The code samples in this page use the gRPC API interface with the Google Cloud client libraries. Alternatively, you can use the REST API interface. For more information about the gRPC and REST interfaces, see [Google Chat API overview](https://developers.google.com/workspace/chat/api/reference).

<br />

## Get a user's availability

To read the availability of a Google Chat user, pass the following in your
request:

- Specify the `chat.users.availability.readonly` or `chat.users.availability` authorization scope.
- Call the [`GetAvailability`](https://developers.google.com/workspace/chat/api/reference/rpc/google.chat.v1#google.chat.v1.ChatService.GetAvailability) method.
- Pass the `name` of the availability resource to retrieve. The name must be formatted as `users/{user}/availability`. The user's email address or the `me` alias can be used to refer to the caller. For example, `users/me/availability`.

Here's how to get a user's availability:

### Node.js

    const { ChatServiceClient } = require('@google-apps/chat').v1;

    // Instantiates a client
    const chatServiceClient = new ChatServiceClient();

    async function getAvailability() {
      const request = {
        // The name of the availability resource to retrieve.
        // Format: users/{user}/availability
        // The 'me' alias can be used to refer to the calling user.
        name: 'users/me/availability',
      };

      try {
        const response = await chatServiceClient.getAvailability(request);
        console.log(response);
      } catch (err) {
        console.error('Error retrieving availability:', err);
      }
    }

    getAvailability();

### Python

    from google.apps import chat_v1 as google_chat

    def get_availability():
        # Instantiates a client
        client = google_chat.ChatServiceClient()

        # Prepare request
        request = google_chat.GetAvailabilityRequest(
            # Format: users/{user}/availability
            # The 'me' alias refers to the calling user.
            name="users/me/availability",
        )

        # Call the API
        try:
            response = client.get_availability(request=request)
            print(response)
        except Exception as e:
            print(f"Error retrieving availability: {e}")

    get_availability()

### Java

    import com.google.chat.v1.Availability;
    import com.google.chat.v1.ChatServiceClient;
    import com.google.chat.v1.GetAvailabilityRequest;

    public class GetAvailability {
      public static void main(String[] args) throws Exception {
        // Instantiates a client
        try (ChatServiceClient chatServiceClient = ChatServiceClient.create()) {
          GetAvailabilityRequest request = GetAvailabilityRequest.newBuilder()
              // Format: users/{user}/availability
              // The 'me' alias refers to the calling user.
              .setName("users/me/availability")
              .build();

          Availability response = chatServiceClient.getAvailability(request);
          System.out.println(response);
        }
      }
    }

### Apps Script

    /**
     * Retrieves the calling user's availability details.
     */
    function getUserAvailability() {
      const name = 'users/me/availability';
      try {
        const availability = Chat.Users.Availability.get(name);
        console.log(availability);
      } catch (err) {
        console.error('Failed to get availability: ' + err.message);
      }
    }

The Chat API returns an instance of
[`Availability`](https://developers.google.com/workspace/chat/api/reference/rest/v1/users.availability#Availability)
detailing the user's presence state and custom status.

## Update custom status

To update a user's custom status, pass the following in your request:

- Specify the `chat.users.availability` authorization scope.
- Call the [`UpdateAvailability`](https://developers.google.com/workspace/chat/api/reference/rpc/google.chat.v1#google.chat.v1.ChatService.UpdateAvailability) method.
- Pass the `Availability` resource, specifying the new `customStatus` details.
- Set the `update_mask` parameter to include the `custom_status` field.

Here's how to update a user's custom status:

### Node.js

    const { ChatServiceClient } = require('@google-apps/chat').v1;

    // Instantiates a client
    const chatServiceClient = new ChatServiceClient();

    async function updateCustomStatus() {
      const request = {
        // The Availability resource to update.
        availability: {
          name: 'users/me/availability',
          customStatus: {
            text: 'In a meeting',
            emoji: {
              unicode: '📅'
            }
          }
        },
        // The fields to update. Must contain 'custom_status'.
        updateMask: {
          paths: ['custom_status']
        }
      };

      try {
        const response = await chatServiceClient.updateAvailability(request);
        console.log(response);
      } catch (err) {
        console.error('Error updating status:', err);
      }
    }

    updateCustomStatus();

### Python

    from google.apps import chat_v1 as google_chat
    from google.protobuf import field_mask_pb2

    def update_custom_status():
        # Instantiates a client
        client = google_chat.ChatServiceClient()

        # Define custom status and emoji
        custom_status = google_chat.CustomStatus(
            text="In a meeting",
            emoji=google_chat.Emoji(unicode="📅")
        )

        # Initialize availability object
        availability = google_chat.Availability(
            name="users/me/availability",
            custom_status=custom_status
        )

        # Specify update mask
        update_mask = field_mask_pb2.FieldMask(paths=["custom_status"])

        # Prepare request
        request = google_chat.UpdateAvailabilityRequest(
            availability=availability,
            update_mask=update_mask
        )

        # Call the API
        try:
            response = client.update_availability(request=request)
            print(response)
        except Exception as e:
            print(f"Error updating status: {e}")

    update_custom_status()

### Java

    import com.google.chat.v1.Availability;
    import com.google.chat.v1.ChatServiceClient;
    import com.google.chat.v1.CustomStatus;
    import com.google.chat.v1.Emoji;
    import com.google.chat.v1.UpdateAvailabilityRequest;
    import com.google.protobuf.FieldMask;

    public class UpdateCustomStatus {
      public static void main(String[] args) throws Exception {
        // Instantiates a client
        try (ChatServiceClient chatServiceClient = ChatServiceClient.create()) {
          CustomStatus customStatus = CustomStatus.newBuilder()
              .setText("In a meeting")
              .setEmoji(Emoji.newBuilder().setUnicode("📅"))
              .build();

          Availability availability = Availability.newBuilder()
              .setName("users/me/availability")
              .setCustomStatus(customStatus)
              .build();

          FieldMask updateMask = FieldMask.newBuilder()
              .addPaths("custom_status")
              .build();

          UpdateAvailabilityRequest request = UpdateAvailabilityRequest.newBuilder()
              .setAvailability(availability)
              .setUpdateMask(updateMask)
              .build();

          Availability response = chatServiceClient.updateAvailability(request);
          System.out.println(response);
        }
      }
    }

### Apps Script

    /**
     * Updates the calling user's custom status message.
     */
    function updateCustomStatus() {
      const name = 'users/me/availability';
      const availability = {
        customStatus: {
          text: 'In a meeting',
          emoji: {
            unicode: '📅'
          }
        }
      };
      const updateMask = 'custom_status';

      try {
        const response = Chat.Users.Availability.patch(availability, name, {
          updateMask: updateMask
        });
        console.log(response);
      } catch (err) {
        console.error('Failed to update status: ' + err.message);
      }
    }

The Chat API updates and returns an instance of
[`Availability`](https://developers.google.com/workspace/chat/api/reference/rest/v1/users.availability#Availability)
with the new custom status.

To clear a user's custom status, update availability and omit `customStatus` details.

## Update presence state

Depending on the target presence state, you can update a user's availability
by calling one of the following custom methods:

- **Active** : Call the [`MarkAsActive`](https://developers.google.com/workspace/chat/api/reference/rpc/google.chat.v1#google.chat.v1.ChatService.MarkAsActive) method to set the presence to active. Optional expiration values (`ttl` or `expireTime`) can be provided.
- **Away** : Call the [`MarkAsAway`](https://developers.google.com/workspace/chat/api/reference/rpc/google.chat.v1#google.chat.v1.ChatService.MarkAsAway) method to set the presence to away.
- **Do not disturb** : Call the [`MarkAsDoNotDisturb`](https://developers.google.com/workspace/chat/api/reference/rpc/google.chat.v1#google.chat.v1.ChatService.MarkAsDoNotDisturb) method to silence notifications.

For details, including field descriptions and query templates, view each
method's reference guide.

## Identify availability changes from an event

Your Chat app can subscribe to `google.workspace.chat.availability.v1.updated`
events to get notifications when a user's availability changes. When an
availability update happens, the app receives an event with a payload
containing the `Availability` resource.

## Related topics

- [Identify and specify Google Chat
  users](https://developers.google.com/workspace/chat/identify-reference-users).
- [Subscribe to Google Chat events](https://developers.google.com/workspace/chat/subscribe-events).