高级聊天服务
使用集合让一切井井有条
根据您的偏好保存内容并对其进行分类。
通过高级聊天服务,您可以在 Apps 脚本中使用 Google Chat API。此 API 允许脚本查找、创建和修改 Chat 聊天室、向聊天室添加或移除成员,以及阅读或发布包含文字、卡片、附件和回应的消息。
前提条件
参考
如需详细了解此服务,请参阅 Chat API 参考文档。与 Apps 脚本中的所有高级服务一样,Chat 服务使用的对象、方法和参数均与公共 API 相同。
示例代码
这些示例展示了如何使用高级服务执行常见的 Google Chat API 操作。
使用用户凭据发布消息
以下示例演示了如何代表用户向 Chat 群组发布消息。
将 chat.messages.create
授权范围添加到 Apps 脚本项目的 appsscript.json
文件中:
"oauthScopes": [
"https://www.googleapis.com/auth/chat.messages.create"
]
将如下函数添加到 Apps 脚本项目的代码中:
发布带有应用凭据的消息
以下示例演示了如何代表应用向 Chat 群组发布消息。使用具有服务账号的高级 Chat 服务时,您无需在 appsscript.json
中指定授权范围。如需详细了解如何使用服务账号进行身份验证,请参阅以 Google Chat 应用的身份进行身份验证。
创建聊天室
以下示例演示了如何获取有关聊天空间的信息。
将 chat.spaces.readonly
授权范围添加到 Apps 脚本项目的 appsscript.json
文件中:
"oauthScopes": [
"https://www.googleapis.com/auth/chat.spaces.readonly"
]
将如下函数添加到 Apps 脚本项目的代码中:
创建聊天室
以下示例演示了如何创建 Chat 聊天室。
将 chat.spaces.create
授权范围添加到 Apps 脚本项目的 appsscript.json
文件中:
"oauthScopes": [
"https://www.googleapis.com/auth/chat.spaces.create"
]
将如下函数添加到 Apps 脚本项目的代码中:
列出会员资格
以下示例演示了如何列出聊天室的所有成员。
将 chat.memberships.readonly
授权范围添加到 Apps 脚本项目的 appsscript.json
文件中:
"oauthScopes": [
"https://www.googleapis.com/auth/chat.memberships.readonly"
]
将如下函数添加到 Apps 脚本项目的代码中:
问题排查
如果您遇到 Error 400: invalid_scope
错误,并显示 Some requested scopes cannot be shown
错误消息,则表示您未在 Apps 脚本项目的 appsscript.json
文件中指定任何授权范围。在大多数情况下,Apps 脚本会自动确定脚本所需的范围,但当您使用 Chat 高级服务时,必须手动将脚本使用的授权范围添加到 Apps 脚本项目的清单文件中。请参阅设置明确的范围。
如需解决此错误,请将相应的授权范围添加到 Apps 脚本项目的 appsscript.json
文件中,作为 oauthScopes
数组的一部分。例如,如需调用 spaces.messages.create
方法,请添加以下内容:
"oauthScopes": [
"https://www.googleapis.com/auth/chat.messages.create"
]
限制和注意事项
高级聊天服务不支持以下功能:
如需下载消息附件或调用开发者预览版方法,请改用 UrlFetchApp
。
如未另行说明,那么本页面中的内容已根据知识共享署名 4.0 许可获得了许可,并且代码示例已根据 Apache 2.0 许可获得了许可。有关详情,请参阅 Google 开发者网站政策。Java 是 Oracle 和/或其关联公司的注册商标。
最后更新时间 (UTC):2025-08-31。
[null,null,["最后更新时间 (UTC):2025-08-31。"],[[["\u003cp\u003eThe Advanced Chat service enables Apps Script to interact with the Google Chat API, allowing scripts to manage spaces, members, and messages.\u003c/p\u003e\n"],["\u003cp\u003eUtilizing this service requires setting up a Google Chat app in the Google Cloud console and configuring proper authentication (user or app).\u003c/p\u003e\n"],["\u003cp\u003eSample code snippets demonstrate common actions like posting messages and managing spaces using user or app credentials.\u003c/p\u003e\n"],["\u003cp\u003eThe service mirrors the Chat API's objects and methods but has limitations, such as not supporting media downloads or Developer Preview methods.\u003c/p\u003e\n"],["\u003cp\u003eTroubleshooting steps and workarounds are provided for potential issues like scope errors.\u003c/p\u003e\n"]]],[],null,["# Advanced Chat Service\n\nThe Advanced Chat service lets you use the\n[Google Chat API](/chat/api/guides) in\nApps Script. This API allows scripts to find, create, and modify\nChat spaces, add or remove members to spaces, and read or post\nmessages with text, cards, attachments, and reactions.\n\nPrerequisites\n-------------\n\n- An Apps Script Google Chat app configured on the Chat API configuration page in the Google Cloud console. The app's Apps Script project must use a standard Google Cloud project instead of the default one created automatically for Apps Script projects. To create a compatible Google Chat app, see [Build a Google Chat app with Google Apps Script](/workspace/add-ons/chat/quickstart-apps-script).\n- Authentication configured for the Chat app. Performing an action on behalf of a user requires [user authentication](/chat/api/guides/auth/users). Performing an action as the Chat app requires [app authentication with a service account](/chat/api/guides/auth/service-accounts). To check which form of authentication a Chat API method supports, see [Types of required authentication for Google Chat API calls](/chat/api/guides/auth#asynchronous-chat-calls).\n\n| **Note:** This is an advanced service that you must [turn on before use](/apps-script/guides/services/advanced).\n\nReference\n---------\n\nFor more information about this service, see the\n[Chat API reference documentation](/chat/api/reference/rest).\nLike all advanced services in Apps Script, the\nChat service uses the same objects, methods, and parameters as\nthe public API.\n\nSample code\n-----------\n\nThese samples show you how to perform common\n[Google Chat API](/chat/api/guides)\nactions using the advanced service.\n\n### Post a message with user credentials\n\nThe following example demonstrates how to post a message to a\nChat space on behalf of the user.\n\n1. Add the `chat.messages.create` authorization scope to the\n Apps Script project's `appsscript.json` file:\n\n \"oauthScopes\": [\n \"https://www.googleapis.com/auth/chat.messages.create\"\n ]\n\n2. Add a function like this one to the Apps Script project's\n code:\n\n advanced/chat.gs \n [View on GitHub](https://github.com/googleworkspace/apps-script-samples/blob/main/advanced/chat.gs) \n\n ```javascript\n /**\n * Posts a new message to the specified space on behalf of the user.\n * @param {string} spaceName The resource name of the space.\n */\n function postMessageWithUserCredentials(spaceName) {\n try {\n const message = {'text': 'Hello world!'};\n Chat.Spaces.Messages.create(message, spaceName);\n } catch (err) {\n // TODO (developer) - Handle exception\n console.log('Failed to create message with error %s', err.message);\n }\n }\n ```\n\n### Post a message with app credentials\n\nThe following example demonstrates how to post a message to a\nChat space on behalf of the app. Using the advanced\nChat service with a service account doesn't require you to\nspecify authorization scopes in `appsscript.json`. For details about\nauthentication with service accounts, see\n[Authenticate as a Google Chat app](/chat/api/guides/auth/service-accounts). \nadvanced/chat.gs \n[View on GitHub](https://github.com/googleworkspace/apps-script-samples/blob/main/advanced/chat.gs) \n\n```javascript\n/**\n * Posts a new message to the specified space on behalf of the app.\n * @param {string} spaceName The resource name of the space.\n */\nfunction postMessageWithAppCredentials(spaceName) {\n try {\n // See https://developers.google.com/chat/api/guides/auth/service-accounts\n // for details on how to obtain a service account OAuth token.\n const appToken = getToken_();\n const message = {'text': 'Hello world!'};\n Chat.Spaces.Messages.create(\n message,\n spaceName,\n {},\n // Authenticate with the service account token.\n {'Authorization': 'Bearer ' + appToken});\n } catch (err) {\n // TODO (developer) - Handle exception\n console.log('Failed to create message with error %s', err.message);\n }\n}\n```\n\n### Get a space\n\nThe following example demonstrates how to get information about a\nChat space.\n\n1. Add the `chat.spaces.readonly` authorization scope to the\n Apps Script project's `appsscript.json` file:\n\n \"oauthScopes\": [\n \"https://www.googleapis.com/auth/chat.spaces.readonly\"\n ]\n\n2. Add a function like this one to the Apps Script project's\n code:\n\n advanced/chat.gs \n [View on GitHub](https://github.com/googleworkspace/apps-script-samples/blob/main/advanced/chat.gs) \n\n ```javascript\n /**\n * Gets information about a Chat space.\n * @param {string} spaceName The resource name of the space.\n */\n function getSpace(spaceName) {\n try {\n const space = Chat.Spaces.get(spaceName);\n console.log('Space display name: %s', space.displayName);\n console.log('Space type: %s', space.spaceType);\n } catch (err) {\n // TODO (developer) - Handle exception\n console.log('Failed to get space with error %s', err.message);\n }\n }\n ```\n\n### Create a space\n\nThe following example demonstrates how to create a Chat space.\n\n1. Add the `chat.spaces.create` authorization scope to the\n Apps Script project's `appsscript.json` file:\n\n \"oauthScopes\": [\n \"https://www.googleapis.com/auth/chat.spaces.create\"\n ]\n\n2. Add a function like this one to the Apps Script project's\n code:\n\n advanced/chat.gs \n [View on GitHub](https://github.com/googleworkspace/apps-script-samples/blob/main/advanced/chat.gs) \n\n ```javascript\n /**\n * Creates a new Chat space.\n */\n function createSpace() {\n try {\n const space = {'displayName': 'New Space', 'spaceType': 'SPACE'};\n Chat.Spaces.create(space);\n } catch (err) {\n // TODO (developer) - Handle exception\n console.log('Failed to create space with error %s', err.message);\n }\n }\n ```\n\n### List memberships\n\nThe following example demonstrates how to list all the members of a\nChat space.\n\n1. Add the `chat.memberships.readonly` authorization scope to the\n Apps Script project's `appsscript.json` file:\n\n \"oauthScopes\": [\n \"https://www.googleapis.com/auth/chat.memberships.readonly\"\n ]\n\n2. Add a function like this one to the Apps Script project's\n code:\n\n advanced/chat.gs \n [View on GitHub](https://github.com/googleworkspace/apps-script-samples/blob/main/advanced/chat.gs) \n\n ```javascript\n /**\n * Lists all the members of a Chat space.\n * @param {string} spaceName The resource name of the space.\n */\n function listMemberships(spaceName) {\n let response;\n let pageToken = null;\n try {\n do {\n response = Chat.Spaces.Members.list(spaceName, {\n pageSize: 10,\n pageToken: pageToken\n });\n if (!response.memberships || response.memberships.length === 0) {\n pageToken = response.nextPageToken;\n continue;\n }\n response.memberships.forEach((membership) =\u003e console.log(\n 'Member resource name: %s (type: %s)',\n membership.name,\n membership.member.type));\n pageToken = response.nextPageToken;\n } while (pageToken);\n } catch (err) {\n // TODO (developer) - Handle exception\n console.log('Failed with error %s', err.message);\n }\n }\n ```\n\nTroubleshoot\n------------\n\nIf you encounter `Error 400: invalid_scope` with the error message\n`Some requested scopes cannot be shown`,\nit means you haven't specified any authorization scopes in the\nApps Script project's `appsscript.json` file. In most cases,\nApps Script automatically determines what scopes a script needs,\nbut when you use the Chat advanced service, you must manually add\nthe authorization scopes that your script uses to your\nApps Script project's manifest file. See\n[Setting explicit scopes](/apps-script/concepts/scopes#setting_explicit_scopes).\n\nTo resolve the error, add the appropriate authorization scopes\nto the Apps Script project's `appsscript.json` file as part of\nthe `oauthScopes` array. For example, to call the\n[`spaces.messages.create`](/chat/api/reference/rest/v1/spaces.messages/create)\nmethod, add the following: \n\n \"oauthScopes\": [\n \"https://www.googleapis.com/auth/chat.messages.create\"\n ]\n\nLimits and considerations\n-------------------------\n\nThe Advanced Chat service doesn't support:\n\n- The Chat API method [`media.download`](/chat/api/reference/rest/v1/media/download).\n- Chat API methods available in [Developer Preview](/workspace/preview)\n\nTo download a message attachment or call a developer preview method, use\n[`UrlFetchApp`](/apps-script/reference/url-fetch/url-fetch-app) instead."]]