@chat-adapter/gchat

中文文档
4.44.0发布于 2026/11/02MITTypeScriptES Module构建来源已验证近 30 天下载 31.5万

Google Chat adapter for Chat SDK — service account auth, Card v2, dialogs, and Workspace Events

原始使用文档
文档目录36 节
  1. Installation
  2. Scaffold with the CLI
  3. Usage
  4. Google Chat setup
  5. 1. Create a GCP project
  6. 2. Enable required APIs
  7. 3. Create a service account
  8. 4. Create service account key
  9. 5. Configure Google Chat app
  10. 6. Add bot to a space
  11. Pub/Sub for all messages (optional)
  12. 1. Create Pub/Sub topic
  13. 2. Grant Chat service account access
  14. 3. Create push subscription
  15. 4. Enable domain-wide delegation
  16. Configuration
  17. Environment variables
  18. Webhook verification
  19. Direct webhooks (Google Chat API)
  20. Pub/Sub push messages
  21. Features
  22. Messaging
  23. Rich content
  24. Conversations
  25. Message history
  26. Limitations
  27. Message history ( fetchMessages )
  28. Troubleshooting
  29. 401 Unauthorized on webhooks
  30. No webhook received
  31. Pub/Sub not working
  32. "Permission denied" for Workspace Events
  33. "Insufficient Permission" for DMs
  34. Button clicks not received
  35. AI Coding Agents
  36. License

Google Chat adapter for Chat SDK

@chat-adapter/gchat

npm package: @chat-adapter/gchat

Agent Stack MIT License

Google Chat adapter for Chat SDK. Configure with service account authentication and optional Pub/Sub.

Documentation: chat-sdk.dev/adapters/official/gchat · Guides: vercel.com/kb/chat-sdk

Installation

pnpm add @chat-adapter/gchat

Scaffold with the CLI

To scaffold a new Google Chat bot with this adapter preselected:

npx create-chat-sdk@latest my-bot --adapter gchat memory

Visit the adapters directory to see other available official and vendor-official adapters.

Usage

The adapter auto-detects credentials from GOOGLE_CHAT_CREDENTIALS or GOOGLE_CHAT_USE_ADC environment variables:

import { Chat } from "chat";
import { createGoogleChatAdapter } from "@chat-adapter/gchat";

const bot = new Chat({
  userName: "mybot",
  adapters: {
    gchat: createGoogleChatAdapter(),
  },
});

bot.onNewMention(async (thread, message) => {
  await thread.post("Hello from Google Chat!");
});

Google Chat setup

1. Create a GCP project

  1. Go to console.cloud.google.com
  2. Click the project dropdown then New Project
  3. Enter project name and click Create

2. Enable required APIs

Go to APIs & Services then Library and enable:

  • Google Chat API
  • Google Workspace Events API (for receiving all messages)
  • Cloud Pub/Sub API (for receiving all messages)

3. Create a service account

  1. Go to IAM & Admin then Service Accounts
  2. Click Create Service Account
  3. Enter name and description
  4. Click Create and Continue
  5. Skip the optional steps, click Done

4. Create service account key

  1. Click on your service account
  2. Go to Keys tab
  3. Click Add Key then Create new key
  4. Select JSON and click Create
  5. Copy the entire JSON content as GOOGLE_CHAT_CREDENTIALS

Note: If your organization has the iam.disableServiceAccountKeyCreation constraint enabled, you need to relax it or add an exception for your project in IAM & Admin then Organization Policies.

5. Configure Google Chat app

  1. Go to the Chat API configuration
  2. Click Configuration and fill in:
    • App name: Your bot's display name
    • Avatar URL: URL to your bot's avatar
    • Description: What your bot does
    • Interactive features: Enable Receive 1:1 messages and Join spaces and group conversations
    • Connection settings: Select App URL
    • App URL: https://your-domain.com/api/webhooks/gchat
    • Visibility: Choose who can discover your app
  3. Click Save

6. Add bot to a space

  1. Open Google Chat
  2. Create or open a Space
  3. Click the space name then Manage apps & integrations
  4. Click Add apps, search for your app, and click Add

Pub/Sub for all messages (optional)

By default, Google Chat only sends webhooks for @mentions. To receive all messages in a space, set up Workspace Events with Pub/Sub.

createGoogleChatAdapter({
  pubsubTopic: process.env.GOOGLE_CHAT_PUBSUB_TOPIC,
  impersonateUser: process.env.GOOGLE_CHAT_IMPERSONATE_USER,
});

GOOGLE_CHAT_PUBSUB_TOPIC and GOOGLE_CHAT_IMPERSONATE_USER are also auto-detected from env vars, so you can omit them from config if the env vars are set.

1. Create Pub/Sub topic

  1. Go to Pub/Sub then Topics
  2. Click Create Topic
  3. Enter topic ID (e.g., chat-events)
  4. Uncheck Add a default subscription
  5. Click Create
  6. Copy the full topic name as GOOGLE_CHAT_PUBSUB_TOPIC (format: projects/your-project-id/topics/chat-events)

2. Grant Chat service account access

  1. Go to your Pub/Sub topic
  2. Click Permissions tab
  3. Click Add Principal
  4. Enter [email protected]
  5. Select role Pub/Sub Publisher
  6. Click Save

3. Create push subscription

  1. Go to Pub/Sub then Subscriptions
  2. Click Create Subscription
  3. Select your topic
  4. Set Delivery type to Push
  5. Set Endpoint URL to https://your-domain.com/api/webhooks/gchat
  6. Check Enable authentication and pick a service account. This is what signs the OIDC token on each push, and its email is the value you set as GOOGLE_CHAT_PUBSUB_SERVICE_ACCOUNT_EMAIL
  7. Click Create

4. Enable domain-wide delegation

Domain-wide delegation is required for creating Workspace Events subscriptions and initiating DMs.

Step 1 — Enable delegation on the service account:

  1. Go to IAM & Admin then Service Accounts
  2. Click on your service account
  3. Check Enable Google Workspace Domain-wide Delegation and save
  4. Copy the Client ID (a numeric ID, not the email)

Step 2 — Authorize in Google Admin Console:

  1. Go to Google Admin Console
  2. Go to Security then Access and data control then API controls
  3. Click Manage Domain Wide Delegation then Add new
  4. Enter the numeric Client ID from Step 1
  5. Add OAuth scopes (comma-separated, on one line):
    https://www.googleapis.com/auth/chat.spaces.readonly,https://www.googleapis.com/auth/chat.messages.readonly,https://www.googleapis.com/auth/chat.spaces,https://www.googleapis.com/auth/chat.spaces.create
    
  6. Click Authorize

Step 3 — Set environment variable:

Set GOOGLE_CHAT_IMPERSONATE_USER to an admin user email in your domain (e.g., [email protected]).

Configuration

Most options are auto-detected from environment variables when not provided. endpointUrl must be passed in config.

OptionRequiredDescription
credentialsNo*Service account credentials JSON. Auto-detected from GOOGLE_CHAT_CREDENTIALS
botUserIdNoCanonical users/... resource name of this Chat app. Required for exact self-message and mention detection. Auto-detected from GOOGLE_CHAT_BOT_USER_ID
useApplicationDefaultCredentialsNoUse Application Default Credentials. Auto-detected from GOOGLE_CHAT_USE_ADC
pubsubTopicNoPub/Sub topic for Workspace Events. Auto-detected from GOOGLE_CHAT_PUBSUB_TOPIC
pubsubAudienceNo†Expected JWT audience for Pub/Sub webhook verification. Auto-detected from GOOGLE_CHAT_PUBSUB_AUDIENCE
pubsubServiceAccountEmailNo§Service account your Pub/Sub push subscription authenticates as. Required to accept Pub/Sub pushes. Auto-detected from GOOGLE_CHAT_PUBSUB_SERVICE_ACCOUNT_EMAIL
googleChatProjectNumberNo†GCP project number for direct webhook JWT verification when the Chat app's authentication audience is "Project number". Auto-detected from GOOGLE_CHAT_PROJECT_NUMBER
endpointUrlNo†Public webhook URL for button click routing and direct webhook JWT verification when the Chat app's authentication audience is "HTTP endpoint URL". Must be passed in config
workspaceAddOnServiceAccountEmailNo‡Your own service-{projectNumber}@gcp-sa-gsuiteaddons.iam.gserviceaccount.com identity. Required to accept Workspace Add-on Chat app webhooks. Auto-detected from GOOGLE_CHAT_WORKSPACE_ADDON_SERVICE_ACCOUNT_EMAIL
disableSignatureVerificationNo†Disable JWT verification entirely (development only). Auto-detected from GOOGLE_CHAT_DISABLE_SIGNATURE_VERIFICATION=true
impersonateUserNoUser email for domain-wide delegation. Auto-detected from GOOGLE_CHAT_IMPERSONATE_USER
authNoCustom auth object (advanced)
apiUrlNoOverride the Google Chat API base URL. Auto-detected from GOOGLE_CHAT_API_URL
loggerNoLogger instance (defaults to ConsoleLogger("info"))

*Either credentials, GOOGLE_CHAT_CREDENTIALS env var, useApplicationDefaultCredentials, or GOOGLE_CHAT_USE_ADC=true is required.

Use the canonical sender.name from a verified message authored by your Chat app for botUserId. The adapter does not learn its identity from inbound mentions. Without this value it conservatively treats every BOT sender as self to prevent reply loops.

Apps upgrading from an earlier release that rely on mention handlers must configure botUserId to preserve mention handling. Without it, bot mention annotations are left unchanged and the default onNewMention detection may no longer match them.

†One of googleChatProjectNumber, endpointUrl, pubsubAudience, or disableSignatureVerification: true is required — the constructor throws otherwise. Configure the verifier(s) for each transport you actually receive; requests of a shape whose verifier is unconfigured are rejected with HTTP 401.

§Required alongside pubsubAudience. The audience is your public push endpoint, so anyone can have Google mint a validly signed token naming it from their own project. Only the email claim identifies the caller, which is why Google requires checking it in addition to aud. Without it, Pub/Sub pushes are rejected with HTTP 401 rather than trusted on their audience alone.

‡Only Workspace Add-on Chat apps need this. Their webhooks are signed by an add-on service identity rather than [email protected], and every add-on project shares the same service-{projectNumber}@gcp-sa-gsuiteaddons email shape — so the identity is only meaningful compared exactly. Without it, add-on tokens are rejected with HTTP 401 rather than trusted by shape. Standalone Chat apps are unaffected.

Environment variables

GOOGLE_CHAT_CREDENTIALS={"type":"service_account",...}
GOOGLE_CHAT_BOT_USER_ID=users/123456789

# Optional: for receiving all messages
GOOGLE_CHAT_PUBSUB_TOPIC=projects/your-project/topics/chat-events
[email protected]

# Webhook verification — at least one verifier or the explicit opt-out is required
GOOGLE_CHAT_PROJECT_NUMBER=123456789          # Direct webhooks with project-number audience
GOOGLE_CHAT_PUBSUB_AUDIENCE=https://your-domain.com/api/webhooks/gchat  # For Pub/Sub JWT verification
GOOGLE_CHAT_PUBSUB_SERVICE_ACCOUNT_EMAIL=pubsub@your-project.iam.gserviceaccount.com  # Push subscription identity
# Workspace Add-on Chat apps only — your own add-on service identity
GOOGLE_CHAT_WORKSPACE_ADDON_SERVICE_ACCOUNT_EMAIL=service-123456789@gcp-sa-gsuiteaddons.iam.gserviceaccount.com
# GOOGLE_CHAT_DISABLE_SIGNATURE_VERIFICATION=true  # Escape hatch for local dev only

# Optional: override the Google Chat API base URL
GOOGLE_CHAT_API_URL=...

Webhook verification

The adapter supports JWT verification for both webhook types. When configured, the adapter validates the Authorization: Bearer <JWT> header on incoming requests using Google's public keys. Requests with missing or invalid tokens are rejected with HTTP 401.

Verification is required. The constructor throws ValidationError unless one of the following is set:

  • googleChatProjectNumber (or GOOGLE_CHAT_PROJECT_NUMBER) — direct webhooks when the Chat app's authentication audience is "Project number"
  • endpointUrl — direct webhooks when the Chat app's authentication audience is "HTTP endpoint URL"; also required for routing card button clicks in HTTP endpoint apps. Workspace Add-on Chat apps additionally need workspaceAddOnServiceAccountEmail, since their tokens are signed by an add-on identity instead of [email protected]
  • pubsubAudience (or GOOGLE_CHAT_PUBSUB_AUDIENCE) — Pub/Sub push deliveries. Also set pubsubServiceAccountEmail (or GOOGLE_CHAT_PUBSUB_SERVICE_ACCOUNT_EMAIL) to the identity in your subscription's push auth settings, or pushes are rejected
  • disableSignatureVerification: true (or GOOGLE_CHAT_DISABLE_SIGNATURE_VERIFICATION=true) — explicit opt-out, intended for local development only

The two transports share one HTTP endpoint, so each verifier only covers its own request shape. If you only configure a direct-webhook verifier, incoming Pub/Sub-shaped requests are rejected with HTTP 401, and vice versa — configure both if you receive both.

Direct webhooks (Google Chat API)

Google Chat sends a signed token with every webhook request. The expected JWT audience (aud claim) depends on the Chat app's Authentication audience setting:

createGoogleChatAdapter({
  googleChatProjectNumber: "123456789",
});

Use googleChatProjectNumber when the setting is Project number. Find your project number in the GCP Console dashboard (it's different from the project ID).

createGoogleChatAdapter({
  endpointUrl: "https://your-domain.com/api/webhooks/gchat",
});

Use endpointUrl when the setting is HTTP endpoint URL. Workspace Add-on Chat apps always use URL audience tokens. When both googleChatProjectNumber and endpointUrl are set, either token type is accepted.

The two modes carry different token types, and the adapter verifies each per Google's reference implementation: endpoint-URL tokens are standard Google OIDC ID tokens (checked against Google's public certs, plus the Chat service-account email claim with email_verified), while project-number tokens are JWTs self-signed by [email protected] (checked against that service account's X.509 certificates with issuer [email protected]). The configured endpointUrl must exactly match the URL registered in the Chat API console — a trailing-slash or scheme mismatch fails verification.

Pub/Sub push messages

Google Cloud Pub/Sub sends a signed OIDC JWT with push deliveries. The JWT audience is whatever you configured on the push subscription.

createGoogleChatAdapter({
  pubsubAudience: "https://your-domain.com/api/webhooks/gchat",
});

To enable authenticated push on your Pub/Sub subscription:

  1. Go to Pub/Sub then Subscriptions
  2. Edit your push subscription
  3. Enable Authentication
  4. Select a service account with the Service Account Token Creator role
  5. Set the Audience to your webhook URL
  6. Use the same URL as GOOGLE_CHAT_PUBSUB_AUDIENCE

Features

Messaging

FeatureSupported
Post messageYes
Edit messageYes
Delete messageYes
File uploadsNo
StreamingPost+Edit fallback

Rich content

FeatureSupported
Card formatGoogle Chat Cards
ButtonsYes
Link buttonsYes
Select menusYes
TablesASCII
FieldsYes
Images in cardsYes
ModalsNo

Conversations

FeatureSupported
Slash commandsNo
MentionsYes
Add reactionsYes (via Workspace Events)
Remove reactionsYes (via Workspace Events)
Typing indicatorNo
DMsYes (requires delegation)
Ephemeral messagesYes (native)

Message history

FeatureSupported
Fetch messagesYes
Fetch single messageNo
Fetch thread infoYes
Fetch channel messagesYes
List threadsYes
Fetch channel infoYes
Post channel messageYes

Limitations

  • Typing indicators: Not supported by Google Chat API. startTyping() is a no-op.
  • Adding reactions: The Google Chat API doesn't support service account (app) authentication for adding reactions. To use addReaction() or removeReaction(), you need domain-wide delegation with impersonateUser configured — but the reaction appears as coming from the impersonated user, not the bot.

Message history (fetchMessages)

Fetching message history requires domain-wide delegation with the impersonateUser config option set. The impersonated user must have access to the spaces you want to read from. See the Pub/Sub setup above for configuring delegation and OAuth scopes.

Troubleshooting

401 Unauthorized on webhooks

  • For direct webhooks: verify GOOGLE_CHAT_PROJECT_NUMBER matches your GCP project number (not project ID)
  • For Pub/Sub: verify GOOGLE_CHAT_PUBSUB_AUDIENCE matches the audience configured on your push subscription
  • Check that authentication is enabled on your Pub/Sub push subscription
  • Ensure the service account used for push authentication has the Service Account Token Creator role

No webhook received

  • Verify the App URL is correct in Google Chat configuration
  • Check that the Chat API is enabled
  • Ensure the service account has the necessary permissions

Pub/Sub not working

  • Verify [email protected] has Pub/Sub Publisher role
  • Check that the push subscription URL is correct
  • Verify domain-wide delegation is configured with correct scopes
  • Check GOOGLE_CHAT_IMPERSONATE_USER is a valid admin email

"Permission denied" for Workspace Events

  • Ensure domain-wide delegation is configured
  • Verify the OAuth scopes are exactly as specified
  • Check that the impersonated user has access to the spaces

"Insufficient Permission" for DMs

  • DMs require domain-wide delegation with chat.spaces and chat.spaces.create scopes
  • Scope changes can take up to 24 hours to propagate

Button clicks not received

  • Verify Interactive features is enabled in the Google Chat app configuration
  • Check that the App URL is correctly set and accessible
  • Button clicks go to the same webhook URL as messages

AI Coding Agents

If you use an AI coding agent such as OpenAI Codex, Claude Code, or Cursor, install the Chat SDK skill so it knows the SDK APIs, adapter patterns, and project conventions before writing code.

npx skills add vercel/chat

The skill references bundled documentation in node_modules/chat/docs, plus adapter guides and starter templates in the published package.

You can also install the Vercel Plugin for a broader agent toolkit — it includes the Chat SDK skill alongside specialist agents, agent slash commands, and more:

npx plugins add vercel/vercel-plugin

The plugin is optional; the skill alone is enough to build with Chat SDK.

For agent-readable documentation, see chat-sdk.dev/llms.txt (page index) or chat-sdk.dev/llms-full.txt (full text).

License

MIT

版本与发布记录

@chat-adapter/gchat 共发布 61 个版本,首次发布于 2026/01/03;过去 12 个月发布了 61 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
4.44.0latest2026/11/026 天前
4.43.02026/10/1921 天前
4.42.02026/10/1425 天前
4.41.12026/09/291 个月前
4.41.02026/09/181 个月前
4.40.02026/09/052 个月前

关于 @chat-adapter/gchat 的常见问题

@chat-adapter/gchat 是什么?

Google Chat adapter for Chat SDK — service account auth, Card v2, dialogs, and Workspace Events

如何安装 @chat-adapter/gchat?

在项目目录运行 npm install @chat-adapter/gchat,或使用 pnpm add / yarn add / bun add。

@chat-adapter/gchat 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@chat-adapter/gchat 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@chat-adapter/gchat 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=20。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@chat-adapter/gchat 可以商用吗?

@chat-adapter/gchat 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@chat-adapter/gchat 的下载量有多少?

根据 npm 官方下载统计,@chat-adapter/gchat 在 2026/10/10 – 2026/11/08 这 30 天内被下载 315,158 次,日均约 10,505 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@chat-adapter/gchat 还在维护吗?

最新版本 4.44.0 发布于 2026/11/02(6 天前);至今共发布 61 个版本,其中过去 12 个月发布了 61 个;首次发布于 2026/01/03。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。