Apps 脚本是为 Google Chat 创建 Chat 应用的最快方法之一。
- 只需几分钟,您就可以直接在浏览器中启动并运行应用。
- 您不必担心运行和管理服务器、持续维护或运营费用,甚至不必担心下载和设置开发环境。
- 调用 Google API(尤其是Google Workspace API)非常简单,因为 Apps 脚本无需下载或设置,身份验证会自动处理,而 Google API 调用就像原生函数调用一样。
本指南介绍了如何使用 Apps 脚本创建和注册应用。
使用入门
本部分介绍如何使用 Apps 脚本快速创建聊天应用。
第 1 步:复制 Apps 脚本模板
如需开始创建 Apps 脚本应用,最简单的方法是使用 Chat 模板。这将创建一个 Apps 脚本项目,其中包含您需要的方法。之后,根据需要填充方法来实现应用逻辑,或与您已构建的应用集成。以下代码展示了为简单应用填充的模板示例。
/** * Responds to a MESSAGE event in Google Chat. * * @param {Object} event the event object from Google Chat */ function onMessage(event) { var name = ""; if (event.space.type == "DM") { name = "You"; } else { name = event.user.displayName; } var message = name + " said \"" + event.message.text + "\""; return { "text": message }; } /** * Responds to an ADDED_TO_SPACE event in Google Chat. * * @param {Object} event the event object from Google Chat */ function onAddToSpace(event) { var message = ""; if (event.space.singleUserBotDm) { message = "Thank you for adding me to a DM, " + event.user.displayName + "!"; } else { message = "Thank you for adding me to " + (event.space.displayName ? event.space.displayName : "this chat"); } if (event.message) { // Bot added through @mention. message = message + " and you said: \"" + event.message.text + "\""; } return { "text": message }; } /** * Responds to a REMOVED_FROM_SPACE event in Google Chat. * * @param {Object} event the event object from Google Chat */ function onRemoveFromSpace(event) { console.info("Bot removed from ", (event.space.name ? event.space.name : "this chat")); }
第 2 步:修改 onMessage 函数
默认情况下,模板中的 onMessage
函数会返回一个包含文本和简单卡片的 Message
对象。您可以修改此函数以返回文本或特定的卡片 widget。
function onMessage(e) {
return { 'text': 'You said: \`' + e.message.text + '\`' };
}
第 3 步:获取部署 ID
在注册您的应用之前,您需要获取此特定应用的部署 ID。
- 点击部署 > 新建部署。
- 在选择类型下,点击插件。
- 填写选项,然后点击部署。
- 在“Deployment ID”下,点击 Copy。
请参阅版本管理指南,了解使用部署 ID 的建议做法。
第 4 步:注册应用
您可以从 Google Cloud 控制台注册您的应用。在应用注册屏幕上,您需要输入应用名称、头像网址和说明。对于测试,您可以启用“应用可以直接发送消息”和“应用可在包含多位用户的聊天室中工作”。在连接设置下,选择 Apps 脚本,然后粘贴您在上一步中复制的部署 ID。
第 5 步:测试应用
如要测试应用,你可以发起私信对话,也可以用“@”提及聊天室。当您与它对话时,它将会响应第 2 步中的消息响应。大功告成!
Apps 脚本应用概念
事件
Apps 脚本支持您的应用可以实现的若干事件处理脚本函数。每个函数处理不同的事件类型,每个函数接收一个参数 e,即 Event 对象。
onAddToSpace(e)
- 当您的应用添加到聊天室时,系统会执行此函数。您的应用可以直接添加到聊天室,也可以通过“@”提及。在第二种情况下,事件 e 也将具有
message
属性。此函数应返回一个Message
对象,这通常是欢迎消息,用于向最终用户告知您的应用或对用“@”提及的响应。 onMessage(e)
- 当您的应用已存在于聊天室中且用户用“@”提及您的应用时,系统会调用此函数。它应返回一个包含应用响应的
Message
对象。 onRemoveFromSpace(e)
- 当用户从其私信列表或聊天室中移除您的应用时,系统会调用此函数。此函数的返回值已被忽略,因为您的应用已被移除,并且无法再发布消息。
以下示例实现了 onAddToSpace
和 onRemoveFromSpace
:
// onAddToSpace() is invoked when the app is added to a space or when
// a user initiates / re-initiates a direct message with the app.
function onAddToSpace(e) {
if (!e.space.singleUserBotDm) {
return { 'text': 'Thanks for adding me to "' +
(e.space.displayName ? e.space.displayName : "this chat") + '"!' };
} else {
return { 'text': 'Thanks for adding me to a DM!' };
}
}
// onRemoveFromSpace() is invoked when app is removed from a space
// or when a user removes a direct message with the app.
function onRemoveFromSpace(e) {}
请注意,e.space.displayName
可能不存在于人间私信中。
互动式卡片
与其他应用一样,Apps 脚本应用也可以显示互动卡片。如需了解如何使卡片具有互动性,请参阅互动式卡片文档。Apps 脚本应用的主要区别在于,它们可以通过使用 action.actionMethodName 和 action.parameters 键值对作为方法参数,在触发 onClick 事件时指定调用的具体方法。
授权
访问受保护资源的 Apps 脚本应用需要在首次向每位用户运行时授予此访问权限。您不需要执行任何操作,但请注意,用户首次使用您的应用时可能会看到授权对话框。
Apps 脚本在脚本级别处理授权。需要授权的应用只能在最终用户授权给应用后才执行任何操作。如果您希望应用在未获授权且被直接添加到聊天室时显示欢迎消息,可以在清单中指定回退消息。如果您的应用需要初始化逻辑,您可能需要在 onMessage
操作中复制此逻辑。例如:
function onMessage(event) {
var userProperties = PropertiesService.getUserProperties();
if (!userProperties.getProperty('initialized')) {
// handle the onAddToSpace initialization logic here.
...
userProperties.setProperties({initialized: 'true'});
}
// Handle normal onMessage logic.
...
}
异步消息
某些应用可能需要根据外部触发器(例如 Apps 脚本中的时间驱动型触发器)向 Google Chat 发送消息。
对于此用例,我们计划以原生方式将 Google Chat API 集成到 Apps 脚本中。在此期间,实现此目的的唯一方法是通过外部 HTTP API(请参阅文档)。这需要通过 OAuth2 for Apps 脚本库使用 Cloud 服务帐号(请参阅文档)。
以下完整示例应用每分钟都会向所在的每个聊天室发布一条消息:
// Example app for Google Chat that demonstrates app-initiated messages
// by spamming the user every minute.
//
// This app makes use of the Apps Script OAuth2 library at:
// https://github.com/googlesamples/apps-script-oauth2
//
// Follow the instructions there to add the library to your script.
// When added to a space, we store the space's ID in ScriptProperties.
function onAddToSpace(e) {
PropertiesService.getScriptProperties()
.setProperty(e.space.name, '');
return {
'text': 'Hi! I\'ll post a message here every minute. ' +
'Please remove me after testing or I\'ll keep spamming you!'
};
}
// When removed from a space, we remove the space's ID from ScriptProperties.
function onRemoveFromSpace(e) {
PropertiesService.getScriptProperties()
.deleteProperty(e.space.name);
}
// Add a trigger that invokes this function every minute via the
// "Edit > Current Project's Triggers" menu. When it runs, it will
// post in each space the app was added to.
function onTrigger() {
var spaceIds = PropertiesService.getScriptProperties()
.getKeys();
var message = { 'text': 'Hi! It\'s now ' + (new Date()) };
for (var i = 0; i < spaceIds.length; ++i) {
postMessage(spaceIds[i], message);
}
}
var SCOPE = 'https://www.googleapis.com/auth/chat.bot';
// The values below are copied from the JSON file downloaded upon
// service account creation.
// For SERVICE_ACCOUNT_PRIVATE_KEY, remember to include the BEGIN and END lines of the private key
var SERVICE_ACCOUNT_PRIVATE_KEY = '...';
var SERVICE_ACCOUNT_EMAIL = 'service-account@project-id.iam.gserviceaccount.com';
// Posts a message into the given space ID via the API, using
// service account authentication.
function postMessage(spaceId, message) {
var service = OAuth2.createService('chat')
.setTokenUrl('https://accounts.google.com/o/oauth2/token')
.setPrivateKey(SERVICE_ACCOUNT_PRIVATE_KEY)
.setClientId(SERVICE_ACCOUNT_EMAIL)
.setPropertyStore(PropertiesService.getUserProperties())
.setScope(SCOPE);
if (!service.hasAccess()) {
Logger.log('Authentication error: %s', service.getLastError());
return;
}
var url = 'https://chat.googleapis.com/v1/' + spaceId + '/messages';
UrlFetchApp.fetch(url, {
method: 'post',
headers: { 'Authorization': 'Bearer ' + service.getAccessToken() },
contentType: 'application/json',
payload: JSON.stringify(message),
});
}
清单文件
以下是必须附有脚本的 Apps 脚本清单文件的示例。
如果您未从 Chat 模板启动项目,则需要修改清单文件,以将 "chat": {}
对象添加到其中。
请务必从清单文件中排除 "runtimeVersion": "V8"
。Chat 应用尚未完全支持 Apps 脚本 V8 运行时,因此如果您指定 "runtimeVersion": "V8"
,Chat 应用有时就会出现错误。例如,对于使用 V8 运行时构建的 Chat 应用,JSON 响应结构可能会以不可预知的方式意外改变。
{
"timeZone": "America/Los_Angeles",
"dependencies": {},
"chat": {
"addToSpaceFallbackMessage": "Thank you for adding me!"
},
"exceptionLogging": "STACKDRIVER"
}
用户可以在授权您的应用之前将应用添加到聊天室。在这种情况下,您的应用无法响应“添加到聊天室”事件。您可以使用 addToSpaceFallbackMessage
字段提供在发生这种情况时显示的欢迎辞。
清单文件名为 appsscript.json
,属于您的 Apps 脚本项目。如需在 Apps 脚本编辑器中查看清单文件,请依次选择 View > Show manifest file。