Organiza tus páginas con colecciones
Guarda y categoriza el contenido según tus preferencias.
En esta guía, se explica cómo usar el método delete() en el recurso Space de la API de Google Chat para borrar un espacio con nombre cuando ya no sea necesario. Cuando borras un espacio, también se borra todo lo que contiene, incluidos los mensajes y los archivos adjuntos.
Si eres administrador de Google Workspace, puedes llamar al método delete() para borrar cualquier espacio con nombre de tu organización de Google Workspace.
El recurso Space representa un lugar donde las personas y las apps de Chat pueden enviar mensajes, compartir archivos y colaborar. Existen varios tipos de espacios:
Los mensajes directos (MD) son conversaciones entre dos usuarios o entre un usuario y una app de Chat.
Los chats grupales son conversaciones entre tres o más usuarios y apps de Chat.
Los espacios con nombre son lugares persistentes donde las personas envían mensajes, comparten archivos y colaboran.
Crea credenciales de ID de cliente de OAuth para una aplicación de escritorio. Para ejecutar la muestra en esta guía, guarda las credenciales como un archivo JSON llamado credentials.json en tu directorio local.
Para obtener orientación, completa los pasos para configurar tu entorno en esta
guía de inicio rápido.
import{createClientWithUserCredentials}from'./authentication-utils.js';constUSER_AUTH_OAUTH_SCOPES=['https://www.googleapis.com/auth/chat.delete'];// This sample shows how to delete a space with user credentialasyncfunctionmain(){// Create a clientconstchatClient=awaitcreateClientWithUserCredentials(USER_AUTH_OAUTH_SCOPES);// Initialize request argument(s)constrequest={// Replace SPACE_NAME herename:'spaces/SPACE_NAME'};// Make the requestconstresponse=awaitchatClient.deleteSpace(request);// Handle the responseconsole.log(response);}main().catch(console.error);
Para ejecutar este ejemplo, reemplaza SPACE_NAME por el ID del campo name del espacio. Puedes obtener el ID llamando al método ListSpaces() o desde la URL del espacio.
En tu directorio de trabajo, crea un archivo llamado chat_space_delete_app.py.
Incluye el siguiente código en chat_space_delete_app.py:
fromgoogle.oauth2importservice_accountfromapiclient.discoveryimportbuild# Define your app's authorization scopes.# When modifying these scopes, delete the file token.json, if it exists.SCOPES=["https://www.googleapis.com/auth/chat.app.delete"]defmain():''' Authenticates with Chat API using app authentication, then deletes the specified space. '''# Specify service account details.creds=(service_account.Credentials.from_service_account_file('credentials.json').with_scopes(SCOPES))# Build a service endpoint for Chat API.chat=build('chat','v1',credentials=creds)# Use the service endpoint to call Chat API.result=chat.spaces().delete(# The space to delete.## Replace SPACE with a space name.# Obtain the space name from the spaces resource of Chat API,# or from a space's URL.name='spaces/SPACE').execute()# Print Chat API's response in your command line interface.# When deleting a space, the response body is empty.print(result)if__name__=='__main__':main()
En el código, reemplaza lo siguiente:
SPACE con el nombre del espacio, que puedes obtener del método spaces.list en la API de Chat o de la URL de un espacio
En tu directorio de trabajo, compila y ejecuta la muestra:
python3chat_space_delete_app.py
Si se ejecuta correctamente, el cuerpo de la respuesta estará vacío, lo que indica que se borró el espacio.
Borra un espacio con nombre como administrador de Google Workspace
Si eres administrador de Google Workspace, puedes llamar al método DeleteSpace() para borrar cualquier espacio con nombre de tu organización de Google Workspace.
Para llamar a este método como administrador de Google Workspace, haz lo siguiente:
[[["Fácil de comprender","easyToUnderstand","thumb-up"],["Resolvió mi problema","solvedMyProblem","thumb-up"],["Otro","otherUp","thumb-up"]],[["Falta la información que necesito","missingTheInformationINeed","thumb-down"],["Muy complicado o demasiados pasos","tooComplicatedTooManySteps","thumb-down"],["Desactualizado","outOfDate","thumb-down"],["Problema de traducción","translationIssue","thumb-down"],["Problema con las muestras o los códigos","samplesCodeIssue","thumb-down"],["Otro","otherDown","thumb-down"]],["Última actualización: 2025-08-29 (UTC)"],[[["\u003cp\u003eThis guide explains how to delete a Google Chat space and its contents (messages, attachments) using the \u003ccode\u003edelete()\u003c/code\u003e method.\u003c/p\u003e\n"],["\u003cp\u003eGoogle Workspace administrators can delete any named space within their organization.\u003c/p\u003e\n"],["\u003cp\u003ePrerequisites include a Google Workspace account, a Google Cloud project, and necessary API configurations.\u003c/p\u003e\n"],["\u003cp\u003eTwo deletion methods are outlined: one using user authentication for personal spaces and another using app authentication (developer preview) for app-created spaces.\u003c/p\u003e\n"],["\u003cp\u003eGoogle Workspace administrators have the additional capability to delete any named space using admin privileges.\u003c/p\u003e\n"]]],["The guide details deleting named spaces in Google Chat via the `delete()` method. Users can delete spaces they have access to by specifying the `chat.delete` scope, calling `DeleteSpace()`, and providing the space's name. Chat apps can delete spaces they created using `chat.app.delete` scope and an API key. Google Workspace admins can delete any named space by calling `DeleteSpace()`, using appropriate authorization scopes with `useAdminAccess` set to `true` in the request. Deleting a space removes all its content.\n"],null,["# Delete a space\n\nThis guide explains how use the\n[`delete()`](/workspace/chat/api/reference/rpc/google.chat.v1#google.chat.v1.ChatService.DeleteSpace)\nmethod on the `Space` resource of the Google Chat API to delete a named space when\nit's no longer needed. Deleting a space also deletes everything that it\ncontains, including messages and attachments.\n\nIf you're a Google Workspace administrator, you can call the `delete()`\nmethod to delete any named space in your Google Workspace organization.\n\nThe\n[`Space` resource](/workspace/chat/api/reference/rest/v1/spaces)\nrepresents a place where people and Chat apps can send messages,\nshare files, and collaborate. There are several types of spaces:\n\n- Direct messages (DMs) are conversations between two users or a user and a Chat app.\n- Group chats are conversations between three or more users and Chat apps.\n- Named spaces are persistent places where people send messages, share files, and collaborate.\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\u003c!-- --\u003e\n\n- A Google Chat space. To create one using the Google Chat API, see [Create a space](/workspace/chat/create-spaces). To create one in Chat, visit the [Help Center documentation](https://support.google.com/chat/answer/12176488).\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\nDelete a named space as a user\n------------------------------\n\nTo delete an existing space in Google Chat with\n[user authentication](/workspace/chat/authenticate-authorize-chat-user), pass\nthe following in your request:\n\n- Specify the `chat.delete` authorization scope.\n- Call the [`DeleteSpace()`](/workspace/chat/api/reference/rpc/google.chat.v1#google.chat.v1.ChatService.DeleteSpace) method.\n- Pass the `name` of the space to delete.\n\nHere's how to delete a space: \n\n### Node.js\n\nchat/client-libraries/cloud/delete-space-user-cred.js \n[View on GitHub](https://github.com/googleworkspace/node-samples/blob/main/chat/client-libraries/cloud/delete-space-user-cred.js) \n\n```javascript\nimport {createClientWithUserCredentials} from './authentication-utils.js';\n\nconst USER_AUTH_OAUTH_SCOPES = ['https://www.googleapis.com/auth/chat.delete'];\n\n// This sample shows how to delete a space 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 here\n name: 'spaces/SPACE_NAME'\n };\n\n // Make the request\n const response = await chatClient.deleteSpace(request);\n\n // Handle the response\n console.log(response);\n}\n\nmain().catch(console.error);\n```\n\nTo run this sample, replace \u003cvar translate=\"no\"\u003eSPACE_NAME\u003c/var\u003e with the ID from\nthe space's\n[`name`](/workspace/chat/api/reference/rpc/google.chat.v1#google.chat.v1.Space.FIELDS.string.google.chat.v1.Space.name)\nfield. You can obtain the ID by calling the\n[`ListSpaces()`](/workspace/chat/api/reference/rpc/google.chat.v1#google.chat.v1.ChatService.ListSpaces)\nmethod or from the space's URL.\n\nDelete a named space as a Chat app\n----------------------------------\n\nApp authentication requires one-time\n[administrator approval](/workspace/chat/authenticate-authorize-chat-app#admin-approval).\n\nWith app authentication, you can only delete spaces created by\nChat apps.\n\nTo delete an existing space in Google Chat with\n[app authentication](/workspace/chat/authenticate-authorize-chat-app), pass\nthe following in your request:\n\n- Specify the `chat.app.delete` authorization scope.\n- Call the [`delete` method](/workspace/chat/api/reference/rest/v1/spaces/delete) on the [`Space` resource](/workspace/chat/api/reference/rest/v1/spaces).\n- Pass the `name` of the space to delete.\n\n### Write a script that calls Chat API\n\nHere's how to delete a space: \n\n### Python\n\n1. In your working directory, create a file named `chat_space_delete_app.py`.\n2. Include the following code in `chat_space_delete_app.py`:\n\n from google.oauth2 import service_account\n from apiclient.discovery import build\n\n # Define your app's authorization scopes.\n # When modifying these scopes, delete the file token.json, if it exists.\n SCOPES = [\"https://www.googleapis.com/auth/chat.app.delete\"]\n\n def main():\n '''\n Authenticates with Chat API using app authentication,\n then deletes the specified space.\n '''\n\n # Specify service account details.\n creds = (\n service_account.Credentials.from_service_account_file('credentials.json')\n .with_scopes(SCOPES)\n )\n\n # Build a service endpoint for Chat API.\n chat = build('chat', 'v1', credentials=creds)\n\n # Use the service endpoint to call Chat API.\n result = chat.spaces().delete(\n\n # The space to delete.\n #\n # Replace SPACE with a space name.\n # Obtain the space name from the spaces resource of Chat API,\n # or from a space's URL.\n name='spaces/\u003cvar translate=\"no\"\u003eSPACE\u003c/var\u003e'\n\n ).execute()\n\n # Print Chat API's response in your command line interface.\n # When deleting a space, the response body is empty.\n print(result)\n\n if __name__ == '__main__':\n main()\n\n3. In the code, replace the following:\n\n - \u003cvar translate=\"no\"\u003eSPACE\u003c/var\u003e with the space name, which you can obtain from the [`spaces.list` method](/workspace/chat/api/reference/rest/v1/spaces/list) in the Chat API, or from a space's URL.\n4. In your working directory, build and run the sample:\n\n python3 chat_space_delete_app.py\n\nIf successful, the response body is empty, which indicates that the space is\ndeleted.\n\nDelete a named space as a Google Workspace administrator\n--------------------------------------------------------\n\nIf you're a Google Workspace administrator, you can call the\n`DeleteSpace()` method to delete any named space in your\nGoogle Workspace organization.\n\nTo call this method as a Google Workspace administrator, do the following:\n\n- Call the method using user authentication, and specify an [authorization scope](/workspace/chat/authenticate-authorize#asynchronous-chat-calls) that supports calling the method using [administrator privileges](/workspace/chat/authenticate-authorize-chat-user#admin-privileges).\n- In your request, specify the query parameter `useAdminAccess` to `true`.\n\nFor more information and examples, see\n[Manage Google Chat spaces as a Google Workspace administrator](/workspace/chat/admin-overview).\n\nRelated topics\n--------------\n\n- [Create a space](/workspace/chat/create-spaces)\n- [Get details about a space](/workspace/chat/get-spaces).\n- [List spaces](/workspace/chat/list-spaces).\n- [Update a space](/workspace/chat/update-spaces).\n- [Delete a space](/workspace/chat/delete-spaces).\n- [Set up a space](/workspace/chat/set-up-spaces).\n- [Find a direct message space](/workspace/chat/find-direct-message-in-spaces)."]]