本页介绍了如何使用 HTTP 服务构建可在 Google Chat 中使用的 Google Workspace 插件。
本快速入门介绍了如何使用 Google Cloud 服务构建 HTTP 服务。如需构建 Chat 应用,您需要编写并部署一个 Cloud Functions 函数,供 Chat 应用用来响应用户的消息。
在 HTTP 架构中,您可以配置 Chat 以使用 HTTP 与 Google Cloud 或本地服务器集成,如下图所示:
在上图中,与 HTTP Chat 应用互动的用户的信息流如下所示:
- 用户在 Chat 中通过私信或聊天室向 Chat 应用发送消息。
- 系统会向 Web 服务器发送 HTTP 请求,该服务器是包含 Chat 应用逻辑的云端或本地系统。
- 如有需要,Chat 应用逻辑可以与 Google Workspace 服务(例如 Google 日历和 Google 表格)、其他 Google 服务(例如 Google 地图、YouTube 和 Vertex AI)或其他 Web 服务(例如项目管理系统或工单工具)集成。
- 网络服务器将 HTTP 响应发回给 Chat 中的 Chat 应用服务。
- 系统会将响应传递给用户。
- 聊天应用可以选择调用 Chat API 以异步发布消息或执行其他操作。
由于这些 Chat 应用可以使用不同的编程语言进行设计,因此您可以灵活使用系统中现有的库和组件。
目标
- 设置环境。
- 创建和部署 Cloud Functions 函数。
- 为 Chat 应用配置 Google Workspace 插件。
- 测试应用。
前提条件
- 拥有对 Google Chat 访问权限的商务版或企业版 Google Workspace 账号。
- 启用了结算功能的 Google Cloud 项目。如需检查现有项目是否已启用结算功能,请参阅验证项目的结算状态。如需创建项目并设置结算信息,请参阅创建 Google Cloud 项目。
设置环境
在使用 Google API 之前,您需要先在 Google Cloud 项目中启用这些 API。您可以在单个 Google Cloud 项目中启用一个或多个 API。在 Google Cloud 控制台中,启用 Cloud Build API、Cloud Functions API、Cloud Pub/Sub API、Cloud Logging API、Artifact Registry API 和 Cloud Run API。
创建和部署 Cloud Functions 函数
创建并部署一个 Cloud Functions 函数,用于生成包含发件人显示名称和头像图片的 Chat 卡片。当 Chat 应用收到消息时,它会运行该函数并使用卡片进行响应。
如需为 Chat 应用创建和部署函数,请完成以下步骤:
Node.js
在 Google Cloud 控制台中,转到 Cloud Functions 页面:
确保已选择 Chat 应用的项目。
点击
创建函数。在“创建函数”页面上,设置您的函数:
- 在环境中,选择 Cloud Run 函数。
- 在函数名称中,输入
AddOnChatApp
。 - 在区域中,选择一个区域。
- 在“身份验证”下,选择需要进行身份验证。
- 点击下一步。
在运行时中,选择最新版本的 Node.js。
在源代码中,选择內嵌编辑器。
在入口点中,删除默认文本,然后输入
avatarApp
。将
index.js
的内容替换为以下代码:/** * Google Cloud Function that responds to messages sent from a * Google Chat space. * * @param {Object} req Request sent from Google Chat space * @param {Object} res Response to send back */ exports.avatarApp = function avatarApp(req, res) { if (req.method === 'GET' || !req.body.chat) { return res.send('Hello! This function is meant to be used ' + 'in a Google Chat Space.'); } // Stores the Google Chat event as a variable. const chatMessage = req.body.chat.messagePayload.message; // Replies with the sender's avatar in a card. const displayName = chatMessage.sender.displayName; const avatarUrl = chatMessage.sender.avatarUrl; res.send({ hostAppDataAction: { chatDataAction: { createMessageAction: { message: { text: 'Here\'s your avatar', cardsV2: [{ cardId: 'avatarCard', card: { name: 'Avatar Card', header: { title: `Hello ${displayName}!`, }, sections: [{ widgets: [{ textParagraph: { text: 'Your avatar picture: ' } }, { image: { imageUrl: avatarUrl } }] }] } }] }}}}}); };
点击部署。
Python
在 Google Cloud 控制台中,转到 Cloud Functions 页面:
确保已选择 Chat 应用的项目。
点击
创建函数。在“创建函数”页面上,设置您的函数:
- 在环境中,选择 Cloud Run 函数。
- 在函数名称中,输入
AddOnChatApp
。 - 在区域中,选择一个区域。
- 在“身份验证”下,选择需要进行身份验证。
- 点击下一步。
在运行时中,选择最新版本的 Python。
在源代码中,选择內嵌编辑器。
在入口点中,删除默认文本,然后输入
avatar_app
。将
main.py
的内容替换为以下代码:from typing import Any, Mapping import flask import functions_framework @functions_framework.http def avatar_app(req: flask.Request) -> Mapping[str, Any]: """Google Cloud Function that handles requests from Google Chat Args: flask.Request: the request Returns: Mapping[str, Any]: the response """ if req.method == "GET": return "Hello! This function must be called from Google Chat." request_json = req.get_json(silent=True) # Stores the Google Chat event as a variable. chat_message = request_json["chat"]["messagePayload"]["message"] # Replies with the sender's avatar in a card. display_name = chat_message["sender"]["displayName"] avatar_url = chat_message["sender"]["avatarUrl"] return { "hostAppDataAction": { "chatDataAction": { "createMessageAction": { "message": { "text": "Here's your avatar", "cardsV2": [{ "cardId": "avatarCard", "card": { "name": "Avatar Card", "header": { "title": f"Hello {display_name}!" }, "sections": [{ "widgets": [{ "textParagraph": { "text": "Your avatar picture:" } }, { "image": { "imageUrl": avatar_url } }] }] } }] }}}}}
点击部署。
Java
在 Google Cloud 控制台中,转到 Cloud Functions 页面:
确保已选择 Chat 应用的项目。
点击
创建函数。在“创建函数”页面上,设置您的函数:
- 在环境中,选择 Cloud Run 函数。
- 在函数名称中,输入
AddOnChatApp
。 - 在区域中,选择一个区域。
- 在“身份验证”下,选择需要进行身份验证。
- 点击下一步。
在运行时中,选择最新版本的 Java。
在源代码中,选择內嵌编辑器。
在入口点中,删除默认文本,然后输入
AvatarApp
。将默认的 Java 文件重命名为
src/main/java/AvatarApp.java
。将
AvatarApp.java
的内容替换为以下代码:import java.util.List; import com.google.api.services.chat.v1.model.CardWithId; import com.google.api.services.chat.v1.model.GoogleAppsCardV1Card; import com.google.api.services.chat.v1.model.GoogleAppsCardV1CardHeader; import com.google.api.services.chat.v1.model.GoogleAppsCardV1Image; import com.google.api.services.chat.v1.model.GoogleAppsCardV1Section; import com.google.api.services.chat.v1.model.GoogleAppsCardV1TextParagraph; import com.google.api.services.chat.v1.model.GoogleAppsCardV1Widget; import com.google.api.services.chat.v1.model.Message; import com.google.cloud.functions.HttpFunction; import com.google.cloud.functions.HttpRequest; import com.google.cloud.functions.HttpResponse; import com.google.gson.Gson; import com.google.gson.JsonObject; public class AvatarApp implements HttpFunction { private static final Gson gson = new Gson(); @Override public void service(HttpRequest request, HttpResponse response) throws Exception { JsonObject body = gson.fromJson(request.getReader(), JsonObject.class); if (request.getMethod().equals("GET") || !body.has("chat")) { response.getWriter().write("Hello! This function is meant to be used " + "in a Google Chat Space.."); return; } // Stores the Google Chat event as a variable. JsonObject chatMessage = body.getAsJsonObject("chat") .getAsJsonObject("messagePayload").getAsJsonObject("message"); // Replies with the sender's avatar in a card. String displayName = chatMessage.getAsJsonObject("sender").get("displayName").getAsString(); String avatarUrl = chatMessage.getAsJsonObject("sender").get("avatarUrl").getAsString(); Message message = createMessage(displayName, avatarUrl); JsonObject createMessageAction = new JsonObject(); createMessageAction.add("message", gson.fromJson(gson.toJson(message), JsonObject.class)); JsonObject chatDataAction = new JsonObject(); chatDataAction.add("createMessageAction", createMessageAction); JsonObject hostAppDataAction = new JsonObject(); hostAppDataAction.add("chatDataAction", chatDataAction); JsonObject dataActions = new JsonObject(); dataActions.add("hostAppDataAction", hostAppDataAction); response.getWriter().write(gson.toJson(dataActions)); } Message createMessage(String displayName, String avatarUrl) { GoogleAppsCardV1CardHeader cardHeader = new GoogleAppsCardV1CardHeader(); cardHeader.setTitle(String.format("Hello %s!", displayName)); GoogleAppsCardV1TextParagraph textParagraph = new GoogleAppsCardV1TextParagraph(); textParagraph.setText("Your avatar picture: "); GoogleAppsCardV1Widget avatarWidget = new GoogleAppsCardV1Widget(); avatarWidget.setTextParagraph(textParagraph); GoogleAppsCardV1Image image = new GoogleAppsCardV1Image(); image.setImageUrl(avatarUrl); GoogleAppsCardV1Widget avatarImageWidget = new GoogleAppsCardV1Widget(); avatarImageWidget.setImage(image); GoogleAppsCardV1Section section = new GoogleAppsCardV1Section(); section.setWidgets(List.of(avatarWidget, avatarImageWidget)); GoogleAppsCardV1Card card = new GoogleAppsCardV1Card(); card.setName("Avatar Card"); card.setHeader(cardHeader); card.setSections(List.of(section)); CardWithId cardWithId = new CardWithId(); cardWithId.setCardId("avatarCard"); cardWithId.setCard(card); Message message = new Message(); message.setText("Here's your avatar"); message.setCardsV2(List.of(cardWithId)); return message; } }
将
pom.xml
的内容替换为以下代码:<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.google.chat</groupId> <artifactId>avatar-app</artifactId> <version>1.0-SNAPSHOT</version> <properties> <maven.compiler.target>17</maven.compiler.target> <maven.compiler.source>17</maven.compiler.source> </properties> <dependencies> <dependency> <groupId>com.google.cloud.functions</groupId> <artifactId>functions-framework-api</artifactId> <version>1.0.4</version> </dependency> <!-- https://mvnrepository.com/artifact/com.google.code.gson/gson --> <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.9.1</version> </dependency> <!-- https://mvnrepository.com/artifact/com.google.apis/google-api-services-chat --> <dependency> <groupId>com.google.apis</groupId> <artifactId>google-api-services-chat</artifactId> <version>v1-rev20230115-2.0.0</version> </dependency> </dependencies> <!-- Required for Java functions in the inline editor --> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.8.1</version> <configuration> <excludes> <exclude>.google/</exclude> </excludes> </configuration> </plugin> </plugins> </build> </project>
点击部署。
Cloud Functions 详情页面随即打开,您的函数会显示两个进度指示器:一个指示构建进度,另一个指示服务进度。当两个进度指示器消失并被对勾标记取代时,表示您的函数已部署且已准备就绪。
配置插件
部署 Cloud Functions 函数后,请按以下步骤创建插件并部署 Google Chat 应用:
在 Google Cloud 控制台中,依次点击“菜单”图标 > Cloud Functions。
请务必选择启用了 Cloud Functions 的项目。
在函数列表中,点击 AddOnChatApp。
点击触发器标签页。
在 HTTPS 下方,复制网址。
搜索“Google Chat API”,点击 Google Chat API,然后点击管理。
点击配置,然后设置 Google Chat 应用:
- 在应用名称中,输入
Add-on Chat app
。 - 在头像网址中,输入
https://developers.google.com/workspace/add-ons/images/quickstart-app-avatar.png
。 - 在说明中,输入
Add-on Chat app
。 - 在功能下,选择接收一对一消息和加入聊天室和群组对话。
- 在连接设置下,选择 HTTP 端点网址,然后将 Cloud Functions 函数触发器的网址粘贴到该框中。
- 在身份验证受众群体中,选择 HTTP 端点网址。
- 在公开范围下,选择面向您网域中的特定人员和群组提供此 Google Chat 应用,然后输入您的电子邮件地址。
- 在日志下,选择将错误记录到 Logging。
- 在应用名称中,输入
点击保存。
接下来,授权 Chat 应用调用 Cloud Functions 函数。
授权 Google Chat 调用您的函数
如需授权 Google Workspace 插件调用您的函数,请添加具有 Cloud Run Invoker 角色的 Google Workspace 插件服务账号。
在 Google Cloud 控制台中,转到 Cloud Run 页面。
在 Cloud Run 服务列表中,选中接收函数旁边的复选框。(请勿点击函数本身。)
点击权限。此时权限面板会打开。
点击添加主账号。
在新主账号中,输入与您的项目关联的 Google Workspace 插件服务账号的电子邮件地址。在 Chat API 配置页面上,依次选择连接设置 > HTTP 端点网址 > 服务账号电子邮件地址,找到服务账号电子邮件地址:
在选择角色中,依次选择 Cloud Run > Cloud Run Invoker。
点击保存。
Chat 应用已准备好接收和回复 Chat 中的消息。
测试您的 Chat 应用
如需测试 Chat 应用,请使用 Chat 应用打开私信聊天室并发送消息:
使用您在将自己添加为受信任的测试人员时提供的 Google Workspace 账号打开 Google Chat。
- 点击 发起新聊天。
- 在添加 1 人或更多人字段中,输入 Chat 应用的名称。
从搜索结果中选择 Chat 应用。系统随即会打开一条私信。
- 在与应用来往的新私信中,输入
Hello
并按enter
。
Chat 应用的消息包含一个卡片,用于显示发件人的姓名和头像图片,如下图所示:
如需添加可信测试人员并详细了解如何测试交互式功能,请参阅测试 Google Chat 应用的交互式功能。
问题排查
当 Google Chat 应用或卡片返回错误时,Chat 界面会显示一条消息,提示“出了点问题”。 或“无法处理您的请求”。有时,Chat 界面不会显示任何错误消息,但 Chat 应用或卡片会产生意外结果;例如,卡片消息可能不会显示。
虽然 Chat 界面中可能不会显示错误消息,但当 Chat 应用的错误日志记录功能处于开启状态时,描述性错误消息和日志数据可帮助您修正错误。如需有关查看、调试和修复错误的帮助,请参阅排查和修复 Google Chat 错误。
清理
为避免系统因本教程中使用的资源向您的 Google Cloud 账号收取费用,我们建议您删除该 Cloud 项目。
- 在 Google Cloud 控制台中,前往管理资源页面。依次点击菜单 > IAM 和管理 > 管理资源。
- 在项目列表中,选择要删除的项目,然后点击删除 。
- 在对话框中输入项目 ID,然后点击关闭以删除项目。