Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
738 changes: 738 additions & 0 deletions en/docs/connectors/catalog/communication/google-chat/actions.md

Large diffs are not rendered by default.

79 changes: 79 additions & 0 deletions en/docs/connectors/catalog/communication/google-chat/example.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
---
title: Examples
description: Step-by-step example for using the Google Chat connector to build an echo bot using a webhook trigger.
keywords: [google chat, google workspace, connector example, webhook, trigger, ballerina]
---

import ThemedImage from '@theme/ThemedImage';
import useBaseUrl from '@docusaurus/useBaseUrl';

# Example

## Google Chat Trigger Example

### What you'll build

A minimal Google Chat app that replies to every message with the same text. Google Chat delivers interaction events over HTTP; the `chat:Listener` verifies the Google-signed bearer token on each request before dispatching to `onMessage`, which replies via the injected `chat:MessageCaller`.

### Architecture

```mermaid
flowchart LR
A((Chat User)) --> B[Google Chat]
B --> C[[chat:Listener]]
C --> D[Handler: onMessage]
D --> E[caller->respond]
```

### Prerequisites

- A GCP project with the Google Chat API enabled and a Chat app configured. See the [Setup Guide](setup-guide.md).
- A public HTTPS URL for local development, for example using [ngrok](https://ngrok.com)

### Setting up the Google Chat integration

> **New to WSO2 Integrator?** Follow the [Create a New Integration](../../../../develop/create-integrations/create-a-new-integration.md) guide to set up your integration first, then return here to add the trigger.

### Adding the Google Chat trigger

Add a Google Chat event integration and implement the listener and service as described in the [Google Chat event integration guide](../../../../develop/integration-artifacts/event/google-chat.md). WSO2 Integrator renders the listener and service on the design canvas, with all available handlers listed under **Event Handlers**.

<ThemedImage
alt="WSO2 Integrator design canvas showing the chatListener connected to ChatService with onMessage and onAddedToSpace handlers"
sources={{
light: useBaseUrl('/img/connectors/catalog/communication/google-chat/integration-overview.png'),
dark: useBaseUrl('/img/connectors/catalog/communication/google-chat/integration-overview.png'),
}}
/>

Select **chat:ChatService** in the design canvas to open the Service Designer, which lists every pre-registered event handler bound to the `chatListener`.

<ThemedImage
alt="Google Chat Service Designer listing onMessage, onAddedToSpace, onRemovedFromSpace, and onCardClicked handlers"
sources={{
light: useBaseUrl('/img/connectors/catalog/communication/google-chat/service-designer.png'),
dark: useBaseUrl('/img/connectors/catalog/communication/google-chat/service-designer.png'),
}}
/>

### Handling Google Chat events

Select the **onMessage** row to open its flow canvas, then declare a variable for the message text and respond via the injected caller:

```ballerina
remote function onMessage(chat:MessageEvent event, chat:MessageCaller caller) returns error? {
string text = event.message.text ?: "";
log:printInfo("Google Chat message received", text = text);
check caller->respond({text: "Echo: " + text});
}
```

### Running the integration

Run the integration from WSO2 Integrator, then message your Chat app from Google Chat. Google Chat delivers the event to your listener, which invokes `onMessage`, logs the message, and replies with the echoed text. Verify both the log entry and the reply in the chat.

## What's next

- [Action Reference](actions.md): manage spaces, messages, and members using the `Client`.
- [Trigger Reference](triggers.md): full listener configuration and service callback reference.
- [Setup Guide](setup-guide.md): create a GCP project and configure the Chat app.
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
---
title: "Google Chat Connector Overview"
description: "Overview of the Ballerina Google Chat connector: send and manage messages, and handle Google Chat interaction events."
keywords: [google chat, google workspace, webhook, ballerina connector]
connector: true
connector_name: "googleapis.chat"
---

# Overview

[Google Chat](https://workspace.google.com/products/chat/) is a communication platform from Google, designed for teams and businesses as part of Google Workspace. The Ballerina `ballerinax/googleapis.chat` connector provides both a REST client for the Google Chat API and a webhook listener that receives Google Chat interaction events directly over HTTP.

The listener runs as a plain HTTPS endpoint that Google Chat posts events to directly. There's no separate webhook relay. It supports three authentication mechanisms: service account (recommended for bots), OAuth 2.0 (for user-scoped actions), and short-lived bearer tokens (for quick tests).

## Key features

- Create spaces, send messages, manage memberships, and upload attachments via the REST client
- Receive Chat interaction events (messages, slash commands, card clicks, dialog submissions, app-home opens) over a webhook listener
- Reply synchronously within the event window using event-specific callers
- Google-signed bearer token verification, validated against your HTTP endpoint URL or GCP project number

## Actions

Actions are operations you invoke on the Google Chat API from your integration: listing spaces, sending messages, and downloading media. The connector exposes actions through a single client:

| Client | Actions |
|--------|---------|
| `Client` | Space and message management, media download |

See the **[Action Reference](actions.md)** for the full list of operations, parameters, and sample code. Most send/respond/update/delete operations used inside event handlers go through the per-event callers documented in the [Trigger Reference](triggers.md) instead.

## Triggers

Triggers allow your integration to react to Google Chat interaction events in real time. The connector's listener receives events directly from Google Chat and invokes your service callbacks automatically.

Supported trigger events (`chat:ChatService` callbacks):

| Callback | Description |
|----------|-------------|
| `onMessage` | A user sends a message, @mentions the app, or invokes a slash command. |
| `onAddedToSpace` | The app is added to a space. |
| `onRemovedFromSpace` | The app is removed from a space. |
| `onCardClicked` | A user clicks a button or interactive element on a card. |
| `onWidgetUpdated` | A widget requests an autocomplete or similar update. |
| `onAppCommand` | A user invokes a Chat app command. |
| `onAppHome` | A user opens the app's home page. |
| `onSubmitForm` | A user submits a dialog or form. |

See the **[Trigger Reference](triggers.md)** for listener configuration, service callbacks, and the event payload structure.

## Documentation

* **[Setup Guide](setup-guide.md)**: Create a GCP project, enable the Google Chat API, and configure your Chat app.
* **[Action Reference](actions.md)**: Full reference for the client: operations, parameters, return types, and sample code.
* **[Trigger Reference](triggers.md)**: Reference for event-driven integration using the webhook listener and service model.
* **[Example](example.md)**: Learn how to build and configure an integration using the **Google Chat** connector, including event-driven trigger setup.

## How to contribute

As an open source project, WSO2 welcomes contributions from the community.

To contribute to the code for this connector, please create a pull request in the following repository.

* [Google Chat Connector GitHub repository](https://github.com/ballerina-platform/module-ballerinax-googleapis.chat)

Check the issue tracker for open issues that interest you. We look forward to receiving your contributions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
---
title: Setup Guide
description: "How to create a GCP project, enable the Google Chat API, and configure a Chat app for the Google Chat connector."
keywords: [google chat, google cloud platform, chat api, service account, oauth]
connector: true
connector_name: "googleapis.chat"
---

# Setup Guide

This guide walks you through creating a Google Cloud Platform (GCP) project and configuring a Chat app for the Google Chat connector.

## Prerequisites

- A [Google Cloud Platform](https://console.cloud.google.com/) account with a project, or [sign up for one](https://cloud.google.com/)

## Create a Google Cloud Platform project

Open the [Google Cloud Platform Console](https://console.cloud.google.com/), click the project drop-down menu, and select an existing project or create a new one for your Chat app.

## Enable the Google Chat API

Navigate to **APIs & Services → Library** and enable the **Google Chat API**.

## Expose your local listener

Google Chat must reach the listener over a public HTTPS URL. For local development, the easiest option is [ngrok](https://ngrok.com/):

```bash
ngrok http 8000
```

Copy the `https://<sub>.ngrok-free.app` URL it prints. You'll use this both in the next step and as the listener's `endpointUrl`.

For production, deploy the listener behind any HTTPS-terminating load balancer or reverse proxy.

## Configure the Chat app

1. In the Google Cloud Console, open the **Google Chat API** page and select the **Configuration** tab.
2. Provide the **App name**, **Avatar URL**, and **Description**.
3. Make sure **"Build this Chat app as a Workspace add-on"** is **unchecked**. This connector handles interaction events directly over HTTP, not as a Workspace add-on.
4. Under **Interactive features**, enable the features your app needs (receive 1:1 messages, join spaces, slash commands, and so on).
5. Under **Connection settings**, choose **HTTP endpoint URL** and paste the ngrok (or production) HTTPS URL.
6. Set **Authentication audience** to either:
- the same **HTTP endpoint URL** (use `HttpEndpointUrlConfig`/`endpointUrl` in the `@chat:ServiceConfig` annotation), or
- your **Project number** (use `ProjectNumberConfig`/`projectNumber` instead).

The value you choose here must match your service annotation. The listener uses it to validate the `aud` claim of the Google-signed bearer token on every incoming request.
7. Under **Visibility**, add the email addresses of users or Google Workspace domains that can install your app.

## Choose an authentication method

The connector supports three authentication modes for the internal Chat API client used by event callers.

### Option A: Service account (recommended for bots)

A service account lets your app act as itself. It's ideal for bots that post messages or run continuously.

1. Navigate to **APIs & Services → Credentials**, open **+ Create credentials**, and select **Service account**.
2. Give it a name, click **Done**, then open the created service account and go to the **Keys** tab.
3. Click **Add key → Create new key → JSON** and save the downloaded JSON file securely. You'll reference its path from `Config.toml`.

### Option B: OAuth 2.0 (for user-scoped actions)

OAuth 2.0 lets your app act on behalf of a signed-in user. It's required for operations like attachment uploads that need user scopes.

1. Open **APIs & Services → OAuth consent screen** and configure your consent screen (app name and support email).
2. Open **APIs & Services → Credentials → Create credentials → OAuth client ID**.
3. Fill in the form:

| Field | Value |
|---|---|
| Application type | Web Application |
| Name | ChatConnector |
| Authorized Redirect URIs | `https://developers.google.com/oauthplayground` |

4. Save the **Client ID** and **Client secret**.
5. Use the [OAuth 2.0 Playground](https://developers.google.com/oauthplayground) to obtain a refresh token: open the gear icon, select "Use your own OAuth credentials", enter the client ID and secret, authorize the Chat scopes you need, then exchange the authorization code for tokens.

### Option C: Bearer token (for quick tests)

For short-lived experiments, use a Google access token directly:

```bash
gcloud auth print-access-token
```

:::note
Google access tokens expire in roughly one hour. Bearer-token auth is best for short-lived processes. For long-running services, use service account or OAuth 2.0. Both auto-refresh tokens.
:::

## Next steps

- [Action Reference](actions.md): call the Chat REST API using the `Client`.
- [Trigger Reference](triggers.md): handle interaction events using the `Listener` and `ChatService`.
142 changes: 142 additions & 0 deletions en/docs/connectors/catalog/communication/google-chat/triggers.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
---
title: Triggers
description: "Reference for the Google Chat webhook listener and service callbacks: configure message, card click, and other interaction event handlers in Ballerina integrations."
keywords: [google chat, webhook listener, chat api, event handler, ballerina]
connector: true
connector_name: "googleapis.chat"
---

# Triggers

The `ballerinax/googleapis.chat` package supports event-driven integration through direct HTTP delivery of Google Chat interaction events. There's no separate webhook relay. When a user messages, adds, or interacts with your Chat app, the listener receives the event and dispatches it to the matching service callback automatically.

Components that work together:

| Component | Role |
|-----------|------|
| `chat:Listener` | Exposes the HTTP endpoint, verifies the Google-signed bearer token, and dispatches incoming events to an attached `ChatService`. |
| `chat:ChatService` | Defines the event-type callbacks, such as `onMessage`, `onCardClicked`, and `onAppHome`. Requires a `@chat:ServiceConfig` annotation. |
| `chat:MessageEvent` | The event payload passed to `onMessage`, with `message` guaranteed non-optional. |
| `chat:MessageCaller`, `chat:CardClickedCaller`, `chat:AppHomeCaller`, `chat:SubmitFormCaller` | Event-specific callers injected into handlers, pre-configured with the event's space context, used to respond or call the Chat API asynchronously. |

For action-based operations, see the [Action Reference](actions.md).

## Error handling

Each service callback returns `error?`. If a callback returns an error, the listener logs the failure.

## Listener

The `chat:Listener` receives interaction events directly from Google Chat over HTTP and routes them to the attached service. It also builds an internal Chat API client, used by the injected callers, from the `auth` configuration.

### Configuration

| Config Type | Description |
|-------------|-------------|
| `int\|http:Listener` | The port or HTTP listener to listen on. Defaults to port `8000`. |
| `ListenerConfig` | Auth credentials for the internal Chat API client, plus optional inbound HTTP listener settings. |

`chat:ListenerConfig` fields:

| Field | Type | Default | Description |
|---|---|---|---|
| `auth` | <code>ServiceAccountAuthConfig&#124;OAuth2Config&#124;http:BearerTokenConfig</code> | Required | Authentication for the internal Chat API client. |
| `httpListenerConfig` | `http:ListenerConfiguration` | `{}` | Optional inbound HTTP listener settings. |

### Initializing the listener

```ballerina
import ballerinax/googleapis.chat;

configurable chat:ServiceAccountFileConfig serviceAccountAuth = ?;

listener chat:Listener chatListener = new (8000, {
auth: serviceAccountAuth
});
```

## Service

A Google Chat trigger service is a Ballerina service attached to a `chat:Listener`, implementing `chat:ChatService`, with a required `@chat:ServiceConfig` annotation that declares the bearer-token audience.

```ballerina
@chat:ServiceConfig {
endpointUrl: "https://my-app.example.com"
}
service chat:ChatService on chatListener {
// ...
}
```

Use `projectNumber` instead of `endpointUrl` if your Chat app's **Authentication audience** is set to **Project Number**. The value must match your Chat app's configuration exactly. The listener validates the `aud` claim of every incoming bearer token against it, and attaching a service without this annotation fails.

### Callback signatures

| Callback | Signature | Description |
|----------|-----------|-------------|
| `onMessage` | `remote function onMessage(chat:MessageEvent event, chat:MessageCaller caller) returns error?` | Invoked when a user sends a message, @mentions the app, or invokes a slash command. |
| `onAddedToSpace` | `remote function onAddedToSpace(chat:ChatEvent event, chat:MessageCaller caller) returns error?` | Invoked when the app is added to a space. |
| `onRemovedFromSpace` | `remote function onRemovedFromSpace(chat:ChatEvent event) returns error?` | Invoked when the app is removed from a space. No caller, since the app can no longer respond. |
| `onCardClicked` | `remote function onCardClicked(chat:ChatEvent event, chat:CardClickedCaller caller) returns error?` | Invoked when a user clicks a button or interactive element on a card. |
| `onWidgetUpdated` | `remote function onWidgetUpdated(chat:ChatEvent event, chat:WidgetUpdatedCaller caller) returns error?` | Invoked when a widget requests an autocomplete or similar update. |
| `onAppCommand` | `remote function onAppCommand(chat:ChatEvent event, chat:MessageCaller caller) returns error?` | Invoked when a user invokes a Chat app command. |
| `onAppHome` | `remote function onAppHome(chat:ChatEvent event, chat:AppHomeCaller caller) returns error?` | Invoked when a user opens the app's home page. |
| `onSubmitForm` | `remote function onSubmitForm(chat:ChatEvent event, chat:SubmitFormCaller caller) returns error?` | Invoked when a user submits a dialog or form. |

:::note
The native dispatcher inspects each declared remote function's signature at runtime to determine which event-specific caller to inject alongside the event.
:::

### Full usage example

```ballerina
import ballerina/log;
import ballerinax/googleapis.chat;

configurable chat:ServiceAccountFileConfig serviceAccountAuth = ?;
configurable string endpointUrl = ?;

listener chat:Listener chatListener = new (8000, {auth: serviceAccountAuth});

@chat:ServiceConfig {
endpointUrl: endpointUrl
}
service chat:ChatService on chatListener {

remote function onMessage(chat:MessageEvent event, chat:MessageCaller caller) returns error? {
string text = event.message.text ?: "";
log:printInfo("Google Chat message received", text = text);
check caller->respond({text: "Echo: " + text});
}
}
```

## Event payload types

### `ChatEvent`

The base Google Chat app interaction event.

| Field | Type | Description |
|-------|------|-------------|
| `type` | `EventType` | The type of interaction event. |
| `eventTime` | `string?` | When the event occurred (RFC 3339 timestamp). |
| `message` | `Message?` | The message that triggered the event, for `MESSAGE`, `ADDED_TO_SPACE`, and `CARD_CLICKED` events. |
| `user` | `User?` | The user that triggered the interaction. |
| `space` | `Space?` | The space where the interaction occurred. |
| `action` | `FormAction?` | The form action data, for `CARD_CLICKED` and `SUBMIT_FORM` events. |
| `common` | `CommonEventObject?` | Information about the user's client (locale, platform, form inputs). |

### `MessageEvent`

A specialization of `ChatEvent` with `message` guaranteed non-optional. Used as the parameter type for `onMessage` to avoid nil-check operators.

| Field | Type | Description |
|-------|------|-------------|
| `message` | `Message` | The message that triggered the event (always present for `MESSAGE` events). |

## What's next

- [Action Reference](actions.md): manage spaces, messages, and members using the `Client`.
- [Example](example.md): complete example integrations for the Google Chat connector and trigger.
- [Setup Guide](setup-guide.md): create a GCP project and configure the Chat app.
Loading