Получите подробную информацию о мероприятии в Google Chat
Оптимизируйте свои подборки
Сохраняйте и классифицируйте контент в соответствии со своими настройками.
В этом руководстве объясняется, как использовать метод get() ресурса SpaceEvent API Google Chat для получения сведений о событии из пространства Google Chat.
Вы можете запросить события за 28 дней до момента запроса. Событие содержит самую последнюю версию ресурса, который изменился. Например, если вы запрашиваете событие о новом сообщении, но сообщение было позже обновлено, сервер вернет обновлённый ресурс Message в полезной нагрузке события.
Для вызова этого метода необходимо использовать аутентификацию пользователя . Чтобы получить событие, аутентифицированный пользователь должен быть участником пространства, в котором произошло событие.
Создайте учётные данные OAuth-клиента для настольного приложения. Чтобы запустить пример из этого руководства, сохраните учётные данные в виде JSON-файла с именем credentials.json в локальном каталоге.
Для получения руководства выполните шаги по настройке вашей среды, описанные в этом кратком руководстве .
Получите подробную информацию о космическом событии
Чтобы получить подробную информацию о космическом мероприятии в Google Chat, передайте в запросе следующее:
Укажите область авторизации, поддерживающую тип события в вашем запросе. Рекомендуется выбрать наиболее строгую область, которая позволит вашему приложению функционировать.
Вызовите метод GetSpaceEvent() , передав name события пространства, которое нужно получить.
import{createClientWithUserCredentials}from'./authentication-utils.js';// Replace SCOPE_NAME here with an authorization scope based on the event typeconstUSER_AUTH_OAUTH_SCOPES=['SCOPE_NAME'];// This sample shows how to get space event with user credentialasyncfunctionmain(){// Create a clientconstchatClient=awaitcreateClientWithUserCredentials(USER_AUTH_OAUTH_SCOPES);// Initialize request argument(s)constrequest={// Replace SPACE_NAME and SPACE_EVENT_NAME herename:'spaces/SPACE_NAME/spaceEvents/SPACE_EVENT_NAME'};// Make the requestconstresponse=awaitchatClient.getSpaceEvent(request);// Handle the responseconsole.log(response);}main().catch(console.error);
Чтобы запустить этот пример, замените следующее:
SCOPE_NAME : область авторизации, основанная на типе события. Например, если вы получаете событие чат-группы о новом членстве, используйте область chat.memberships.readonly в формате https://www.googleapis.com/auth/chat.memberships.readonly . Тип события можно получить с помощью метода ListSpaceEvents() . Чтобы узнать, как использовать этот метод, см. раздел Список событий чат-группы .
SPACE_NAME : идентификатор из name пространства. Идентификатор можно получить, вызвав метод ListSpaces() или указав URL пространства.
[null,null,["Последнее обновление: 2025-08-29 UTC."],[[["\u003cp\u003eThis guide explains how to retrieve details about specific events within a Google Chat space using the \u003ccode\u003eget()\u003c/code\u003e method of the Google Chat API.\u003c/p\u003e\n"],["\u003cp\u003eThe \u003ccode\u003eSpaceEvent\u003c/code\u003e resource tracks changes in a space, and this guide details how to access information about these events.\u003c/p\u003e\n"],["\u003cp\u003eTo use this functionality, you need a Google Workspace account, appropriate authorization, and a configured Google Cloud project.\u003c/p\u003e\n"],["\u003cp\u003eYou must provide the correct authorization scope, space name, and space event name to successfully retrieve the event details.\u003c/p\u003e\n"],["\u003cp\u003eThe API returns a \u003ccode\u003eSpaceEvent\u003c/code\u003e object containing comprehensive information about the requested event.\u003c/p\u003e\n"]]],["The guide details how to retrieve space event information using the `get()` method on the Google Chat API's `SpaceEvent` resource. This method requires user authentication, and the user must be a space member. To use `get()`, provide an authorization scope and the event's name within a request. The API returns the latest `SpaceEvent` data, up to 28 days old, reflecting any changes to the space or its resources. It requires Node.js, a Google Workspace account, and proper API configuration.\n"],null,["# Get details about a Google Chat space event\n\nThis guide explains how to use the\n[`get()`](/workspace/chat/api/reference/rpc/google.chat.v1#google.chat.v1.ChatService.GetSpaceEvent)\nmethod on the `SpaceEvent` resource of the Google Chat API to get details about\nan event from a Google Chat space.\n\nThe\n[`SpaceEvent` resource](/workspace/chat/api/reference/rpc/google.chat.v1#google.chat.v1.SpaceEvent)\nrepresents a change to a space or its child resources, such as messages,\nreactions, and memberships. To learn about the supported event types, see the\n[`eventType` field of the `SpaceEvent` resource](/workspace/chat/api/reference/rpc/google.chat.v1#google.chat.v1.SpaceEvent.FIELDS.string.google.chat.v1.SpaceEvent.event_type)\nreference documentation.\n\nYou can request events up to 28 days before the time of the request. The event\ncontains the most recent version of the resource that changed. For example, if\nyou request an event about a new message but the message was later updated, the\nserver returns the updated `Message` resource in the event payload.\n\nTo call this method, you must use\n[user authentication](/workspace/chat/authenticate-authorize-chat-user). To get\nan event, the authenticated user must be a member of the space where the event\noccurred.\n\nPrerequisites\n-------------\n\n\n### Node.js\n\n- A Business or Enterprise [Google Workspace](https://support.google.com/a/answer/6043576) account with access to [Google Chat](https://workspace.google.com/products/chat/).\n\n\u003c!-- --\u003e\n\n- Set up your environment:\n - [Create a Google Cloud project](/workspace/guides/create-project).\n - [Configure the OAuth consent screen](/workspace/guides/configure-oauth-consent).\n - [Enable and configure the Google Chat API](/workspace/chat/configure-chat-api) with a name, icon, and description for your Chat app.\n - Install the Node.js [Cloud Client Library](/workspace/chat/libraries?tab=nodejs#cloud-client-libraries).\n - [Create OAuth client ID credentials](/workspace/chat/authenticate-authorize-chat-user#step-2:) for a desktop application. To run the sample in this guide, save the credentials as a JSON file named `credentials.json` to your local directory.\n\n For guidance, complete the steps for setting up your environment in this [quickstart](/workspace/chat/api/guides/quickstart/nodejs\n #set-up-environment).\n- [Choose an authorization scope](/workspace/chat/authenticate-authorize#asynchronous-chat-calls) that supports user authentication.\n\n\n| The code samples in this page use the gRPC API interface with the Google Cloud client libraries. Alternatively, you can use the REST API interface. For more information about the gRPC and REST interfaces, see [Google Chat API overview](/workspace/chat/api/reference).\n\n\u003cbr /\u003e\n\nGet details about a space event\n-------------------------------\n\nTo get details about a space event in Google Chat, pass the following in your\nrequest:\n\n- Specify an authorization scope that supports the event type in your request. As a best practice, choose the most restrictive scope that still allows your app to function.\n- Call the [`GetSpaceEvent()`](/workspace/chat/api/reference/rpc/google.chat.v1#google.chat.v1.ChatService.GetSpaceEvent) method, passing the `name` of the space event to get.\n\nThe following example gets a space event: \n\n### Node.js\n\nchat/client-libraries/cloud/get-space-event-user-cred.js \n[View on GitHub](https://github.com/googleworkspace/node-samples/blob/main/chat/client-libraries/cloud/get-space-event-user-cred.js) \n\n```javascript\nimport {createClientWithUserCredentials} from './authentication-utils.js';\n\n// Replace SCOPE_NAME here with an authorization scope based on the event type\nconst USER_AUTH_OAUTH_SCOPES = ['SCOPE_NAME'];\n\n// This sample shows how to get space event with user credential\nasync function main() {\n // Create a client\n const chatClient = await createClientWithUserCredentials(USER_AUTH_OAUTH_SCOPES);\n\n // Initialize request argument(s)\n const request = {\n // Replace SPACE_NAME and SPACE_EVENT_NAME here\n name: 'spaces/SPACE_NAME/spaceEvents/SPACE_EVENT_NAME'\n };\n\n // Make the request\n const response = await chatClient.getSpaceEvent(request);\n\n // Handle the response\n console.log(response);\n}\n\nmain().catch(console.error);\n```\n\nTo run this sample, replace the following:\n\n- \u003cvar translate=\"no\"\u003eSCOPE_NAME\u003c/var\u003e: an authorization scope based on the event type. For example, if you are getting a space event about a new membership, use the `chat.memberships.readonly` scope, formatted as `https://www.googleapis.com/auth/chat.memberships.readonly`. You can obtain the event type from the [`ListSpaceEvents()`](/workspace/chat/api/reference/rpc/google.chat.v1#google.chat.v1.ChatService.ListSpaceEvents) method. To learn how to use this method, see [List events from a space](/workspace/chat/list-space-events).\n- \u003cvar translate=\"no\"\u003eSPACE_NAME\u003c/var\u003e: the ID from the space's [`name`](/workspace/chat/api/reference/rpc/google.chat.v1#google.chat.v1.Space.FIELDS.string.google.chat.v1.Space.name). You can obtain the ID by calling the [`ListSpaces()`](/workspace/chat/api/reference/rpc/google.chat.v1#google.chat.v1.ChatService.ListSpaces) method or from the space's URL.\n- \u003cvar translate=\"no\"\u003eSPACE_EVENT_NAME\u003c/var\u003e: the ID from the space event's [`name`](/workspace/chat/api/reference/rpc/google.chat.v1#google.chat.v1.SpaceEvent.FIELDS.string.google.chat.v1.SpaceEvent.name). You can obtain the ID from the [`ListSpaceEvents()`](/workspace/chat/api/reference/rpc/google.chat.v1#google.chat.v1.ChatService.ListSpaceEvents) method. To learn how to use this method, see [List events from a space](/workspace/chat/list-space-events).\n\nThe Chat API returns an instance of\n[`SpaceEvent`](/workspace/chat/api/reference/rpc/google.chat.v1#google.chat.v1.SpaceEvent)\nwith details about the event.\n\nRelated topics\n--------------\n\n- [Work with events from Google Chat](/workspace/chat/events-overview)\n- [List events from a Google Chat space](/workspace/chat/list-space-events)"]]