고급 채팅 서비스
컬렉션을 사용해 정리하기
내 환경설정을 기준으로 콘텐츠를 저장하고 분류하세요.
고급 Chat 서비스를 통해 Apps Script에서 Google Chat API를 사용할 수 있습니다. 이 API를 사용하면 스크립트를 통해 Chat 스페이스를 검색, 생성, 수정하고, 스페이스에 참여자를 추가 또는 삭제하고, 텍스트, 카드, 첨부파일, 반응이 포함된 메시지를 읽거나 게시할 수 있습니다.
기본 요건
참조
이 서비스에 대한 자세한 내용은 Chat API 참조 문서를 참고하세요.
Apps Script의 모든 고급 서비스와 마찬가지로 Chat 서비스는 공개 API와 동일한 객체, 메서드, 매개변수를 사용합니다.
샘플 코드
이 샘플에서는 고급 서비스를 사용하여 일반적인 Google Chat API 작업을 실행하는 방법을 보여줍니다.
사용자 인증 정보로 메시지 게시
다음 예에서는 사용자를 대신하여 Chat 스페이스에 메시지를 게시하는 방법을 보여줍니다.
Apps Script 프로젝트의 appsscript.json
파일에 chat.messages.create
승인 범위를 추가합니다.
"oauthScopes": [
"https://www.googleapis.com/auth/chat.messages.create"
]
다음과 같은 함수를 Apps Script 프로젝트의 코드에 추가합니다.
앱 사용자 인증 정보로 메시지 게시
다음 예에서는 앱을 대신하여 Chat 스페이스에 메시지를 게시하는 방법을 보여줍니다. 서비스 계정으로 고급 Chat 서비스를 사용하면 appsscript.json
에서 승인 범위를 지정하지 않아도 됩니다. 서비스 계정을 사용한 인증에 관한 자세한 내용은 Google Chat 앱으로 인증을 참고하세요.
스페이스 만들기
다음 예에서는 채팅 스페이스에 관한 정보를 가져오는 방법을 보여줍니다.
Apps Script 프로젝트의 appsscript.json
파일에 chat.spaces.readonly
승인 범위를 추가합니다.
"oauthScopes": [
"https://www.googleapis.com/auth/chat.spaces.readonly"
]
다음과 같은 함수를 Apps Script 프로젝트의 코드에 추가합니다.
스페이스 만들기
다음 예는 Chat 스페이스를 만드는 방법을 보여줍니다.
Apps Script 프로젝트의 appsscript.json
파일에 chat.spaces.create
승인 범위를 추가합니다.
"oauthScopes": [
"https://www.googleapis.com/auth/chat.spaces.create"
]
다음과 같은 함수를 Apps Script 프로젝트의 코드에 추가합니다.
멤버십 나열
다음 예에서는 채팅 스페이스의 모든 구성원을 나열하는 방법을 보여줍니다.
Apps Script 프로젝트의 appsscript.json
파일에 chat.memberships.readonly
승인 범위를 추가합니다.
"oauthScopes": [
"https://www.googleapis.com/auth/chat.memberships.readonly"
]
다음과 같은 함수를 Apps Script 프로젝트의 코드에 추가합니다.
문제 해결
오류 메시지 Some requested scopes cannot be shown
와 함께 Error 400: invalid_scope
가 표시되면 Apps Script 프로젝트의 appsscript.json
파일에 승인 범위가 지정되지 않았음을 의미합니다. 대부분의 경우 Apps Script는 스크립트에 필요한 범위를 자동으로 결정하지만 Chat 고급 서비스를 사용하는 경우 스크립트가 사용하는 승인 범위를 Apps Script 프로젝트의 매니페스트 파일에 수동으로 추가해야 합니다. 명시적 범위 설정을 참고하세요.
이 오류를 해결하려면 oauthScopes
배열의 일부로 Apps Script 프로젝트의 appsscript.json
파일에 적절한 승인 범위를 추가하세요. 예를 들어 spaces.messages.create
메서드를 호출하려면 다음을 추가합니다.
"oauthScopes": [
"https://www.googleapis.com/auth/chat.messages.create"
]
한도 및 고려사항
고급 Chat 서비스는 다음을 지원하지 않습니다.
메일 첨부파일을 다운로드하거나 개발자 미리보기 메서드를 호출하려면 대신 UrlFetchApp
를 사용하세요.
달리 명시되지 않는 한 이 페이지의 콘텐츠에는 Creative Commons Attribution 4.0 라이선스에 따라 라이선스가 부여되며, 코드 샘플에는 Apache 2.0 라이선스에 따라 라이선스가 부여됩니다. 자세한 내용은 Google Developers 사이트 정책을 참조하세요. 자바는 Oracle 및/또는 Oracle 계열사의 등록 상표입니다.
최종 업데이트: 2025-08-31(UTC)
[null,null,["최종 업데이트: 2025-08-31(UTC)"],[[["\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."]]