Organiza tus páginas con colecciones Guarda y categoriza el contenido según tus preferencias.
Crea un Google Apps Script que realice solicitudes a la API de Google Chat.
En las guías de inicio rápido, se explica cómo configurar y ejecutar una app que llama a una API de Google Workspace. En esta guía de inicio rápido, se usa un enfoque de autenticación simplificado que es adecuado para un entorno de pruebas. Para un entorno de producción, te recomendamos que obtengas información sobre la autenticación y la autorización antes de elegir las credenciales de acceso adecuadas para tu app.
En Apps Script, los inicios rápidos de Google Workspace usan los servicios avanzados de Google para llamar a las APIs de Google Workspace y controlar algunos detalles del flujo de autenticación y autorización.
Si usas un proyecto nuevo de Google Cloud para completar esta guía de inicio rápido, debes configurarlo y agregarte como usuario de prueba. Si ya completaste estos pasos para tu proyecto de Cloud, ve a la siguiente sección.
Abre tu proyecto de Cloud en la consola de Google Cloud.
Si aún no está abierto, abre el proyecto de Cloud que deseas usar para esta muestra:
En la consola de Google Cloud, ve a la página Seleccionar un proyecto.
Selecciona el proyecto de Google Cloud que deseas usar. O bien, haz clic en Crear proyecto y sigue las instrucciones en pantalla. Si creas un proyecto de Google Cloud, es posible que debas activar la facturación para el proyecto.
Activa la API de Chat
Antes de usar las APIs de Google, debes activarlas en un proyecto de Google Cloud. Puedes activar una o más APIs en un solo proyecto de Google Cloud.
En la consola de Google Cloud, habilita la API de Google Chat.
Si ya configuraste , puedes configurar los siguientes parámetros de configuración de la pantalla de consentimiento de OAuth en Branding, Audience y Data Access. Si ves un mensaje que dice aún no se configuró, haz clic en Comenzar:
En Información de la app, en Nombre de la app, ingresa un nombre para la app.
En Correo electrónico de asistencia del usuario, elige una dirección de correo electrónico de asistencia a la que los usuarios puedan comunicarse contigo si tienen preguntas sobre su consentimiento.
Haz clic en Siguiente.
En Público, selecciona Interno.
Haz clic en Siguiente.
En Información de contacto, ingresa una dirección de correo electrónico en la que puedas recibir notificaciones sobre cualquier cambio en tu proyecto.
Por el momento, puedes omitir la adición de permisos. En el futuro, cuando crees una app para usarla fuera de tu organización de Google Workspace, deberás cambiar el Tipo de usuario a Externo. Luego, agrega los permisos de autorización que requiere tu app. Para obtener más información, consulta la guía completa Configura el consentimiento de OAuth.
Configura la app de Google Chat
Para llamar a la API de Google Chat, debes configurar una app de Google Chat. Para cualquier solicitud de escritura, Google Chat atribuye la app de Google Chat en la IU con la siguiente información.
En la consola de Google Cloud, ve a la página Configuración de la API de Chat:
En Información de la aplicación, ingresa la siguiente información:
En el campo Nombre de la app, ingresa Chat API quickstart app.
En el campo URL del avatar, ingresa https://developers.google.com/chat/images/quickstart-app-avatar.png.
En el campo Descripción, ingresa Quickstart for calling the Chat API.
En Funciones interactivas, haz clic en el botón de activación Habilitar funciones interactivas y colócalo en la posición desactivada para inhabilitar las funciones interactivas de la app de Chat.
/** * This quickstart sample shows how to list spaces with user credential * * It relies on the OAuth2 scope 'https://www.googleapis.com/auth/chat.spaces.readonly' * referenced in the manifest file (appsscript.json). */functionlistSpaces(){// Initialize request argument(s)// Filter spaces by space type (SPACE or GROUP_CHAT or DIRECT_MESSAGE)constfilter='space_type = "SPACE"';// Iterate through the response pages using page tokensletresponsePage;letpageToken=null;do{// Request response pagesresponsePage=Chat.Spaces.list({filter:filter,pageToken:pageToken});// Handle response pagesif(responsePage.spaces){responsePage.spaces.forEach((space)=>console.log(space));}// Update the page token to the next onepageToken=responsePage.nextPageToken;}while(pageToken);}
Haz clic en Guardar .
Haz clic en Proyecto sin título, escribe Quickstart y haz clic en Cambiar nombre.
Configura la secuencia de comandos
Copia el número del proyecto de Cloud
En la consola de Google Cloud, ve a Menú menu>IAM y administración>Configuración.
[[["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-04 (UTC)"],[[["\u003cp\u003eThis quickstart demonstrates how to set up and run a Google Apps Script that interacts with the Google Chat API to list spaces.\u003c/p\u003e\n"],["\u003cp\u003eBefore running the script, you need to configure your Google Cloud project, enable the Chat API, and set up OAuth consent.\u003c/p\u003e\n"],["\u003cp\u003eThe script utilizes the Google Chat API client libraries for authentication and authorization and provides a simplified approach suitable for testing environments.\u003c/p\u003e\n"],["\u003cp\u003eYou need a Google Workspace account and a Google Cloud project to complete the steps outlined in the guide.\u003c/p\u003e\n"],["\u003cp\u003eTo run the script, you will need to copy your Cloud project number, link it to the Apps Script project, enable the Google Chat API, and authorize access.\u003c/p\u003e\n"]]],["This document outlines how to create and run a Google Apps Script to interact with the Google Chat API. Key actions include: configuring a Google Cloud project (enabling the Chat API, setting up OAuth consent, and configuring a Chat app), creating a new script, linking the script to the Cloud project, configuring the script by enabling the Chat API in its manifest file, and running the script. This allows the listing of spaces and other API interaction.\n"],null,["Create a\n[Google Apps Script](/apps-script/overview)\nthat makes requests to the Google Chat API.\n\nQuickstarts explain how to set up and run an app that calls a\nGoogle Workspace API. This quickstart uses a\nsimplified authentication approach that is appropriate for a testing\nenvironment. For a production environment, we recommend learning about\n[authentication and authorization](/workspace/guides/auth-overview)\nbefore\n[choosing the access credentials](/workspace/guides/create-credentials#choose_the_access_credential_that_is_right_for_you)\nthat are appropriate for your app.\n\nIn Apps Script, Google Workspace\nquickstarts use\n[Advanced Google services](/apps-script/guides/services/advanced) to call\nGoogle Workspace APIs and handle some details of the authentication\nand authorization flow.\n\nObjectives\n\n- Configure the environment.\n- Create and configure the script.\n- Run the script.\n\nPrerequisites\n\n- [A Google Cloud project](/workspace/guides/create-project).\n\n\n- A Business or Enterprise [Google Workspace](//support.google.com/a/answer/6043576) account with access to [Google Chat](//workspace.google.com/products/chat/).\n\n\u003cbr /\u003e\n\nConfigure your Cloud project\n\nIf you're using a new Google Cloud project to complete this quickstart, you need to\nconfigure it and add yourself as a test user. If you've already\ncompleted these steps for your Cloud project, skip to the next section.\n\nOpen your Cloud project in the Google Cloud console\n\nIf it's not open already, open the Cloud project that you intend to use\nfor this sample:\n\n1. In the Google Cloud console, go to the **Select a project** page.\n\n [Select a Cloud project](https://console.cloud.google.com/projectselector2)\n2. Select the Google Cloud project you want to use. Or, click **Create project** and follow the on-screen instructions. If you create a Google Cloud project, you might need to [turn on billing for the project](https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project).\n\nTurn on the Chat API Before using Google APIs, you need to turn them on in a Google Cloud project. You can turn on one or more APIs in a single Google Cloud project.\n\n- In the Google Cloud console, enable the Google Chat API.\n\n [Enable the API](https://console.cloud.google.com/flows/enableapi?apiid=chat.googleapis.com)\n\nConfigure the OAuth consent screen\n\n1. In the Google Cloud console, go to Menu menu \\\u003e **Google Auth platform** \\\u003e **Branding** .\n\n [Go to Branding](https://console.cloud.google.com/auth/branding)\n2. If you have already configured the Google Auth platform, you can configure the following OAuth Consent Screen settings in [Branding](https://console.cloud.google.com/auth/branding), [Audience](https://console.cloud.google.com/auth/audience), and [Data Access](https://console.cloud.google.com/auth/scopes). If you see a message that says **Google Auth platform not configured yet** , click **Get Started**:\n 1. Under **App Information** , in **App name**, enter a name for the app.\n 2. In **User support email**, choose a support email address where users can contact you if they have questions about their consent.\n 3. Click **Next**.\n 4. Under **Audience** , select **Internal**.\n 5. Click **Next**.\n 6. Under **Contact Information** , enter an **Email address** where you can be notified about any changes to your project.\n 7. Click **Next**.\n 8. Under **Finish** , review the [Google API Services User Data Policy](https://developers.google.com/terms/api-services-user-data-policy) and if you agree, select **I agree to the Google API Services: User Data Policy**.\n 9. Click **Continue**.\n 10. Click **Create**.\n3. For now, you can skip adding scopes. In the future, when you create an app for use outside of your Google Workspace organization, you must change the **User type** to **External** . Then add the authorization scopes that your app requires. To learn more, see the full [Configure OAuth consent](/workspace/guides/configure-oauth-consent) guide.\n\nConfigure the Google Chat app\n\nTo call the Google Chat API, you must configure a\nGoogle Chat app. For any write requests, Google Chat\nattributes the Google Chat app in the UI using\nthe following information.\n\n1. In the Google Cloud console, go to the Chat API **Configuration** page:\n\n [Go to Chat API Configuration page](https://console.cloud.google.com/apis/api/chat.googleapis.com/hangouts-chat)\n2. Under **Application info**, enter the following information:\n\n 1. In the **App name** field, enter `Chat API quickstart app`.\n 2. In the **Avatar URL** field, enter `https://developers.google.com/chat/images/quickstart-app-avatar.png`.\n 3. In the **Description** field, enter `Quickstart for calling the Chat API`.\n3. Under **Interactive features** , click the **Enable interactive features**\n toggle to the off position to disable interactive features for the\n Chat app.\n\n4. Click **Save**.\n\nCreate the script\n\n1. Create a new script by going to [script.google.com/create](https://script.google.com/create).\n2. Replace the contents of the script editor with the following code:\n\n\nchat/quickstart/Code.gs \n[View on GitHub](https://github.com/googleworkspace/apps-script-samples/blob/main/chat/quickstart/Code.gs) \n\n```gosu\n/**\n * This quickstart sample shows how to list spaces with user credential\n *\n * It relies on the OAuth2 scope 'https://www.googleapis.com/auth/chat.spaces.readonly'\n * referenced in the manifest file (appsscript.json).\n */\nfunction listSpaces() {\n // Initialize request argument(s)\n // Filter spaces by space type (SPACE or GROUP_CHAT or DIRECT_MESSAGE)\n const filter = 'space_type = \"SPACE\"';\n\n // Iterate through the response pages using page tokens\n let responsePage;\n let pageToken = null;\n do {\n // Request response pages\n responsePage = Chat.Spaces.list({\n filter: filter,\n pageToken: pageToken\n });\n // Handle response pages\n if (responsePage.spaces) {\n responsePage.spaces.forEach((space) =\u003e console.log(space));\n }\n // Update the page token to the next one\n pageToken = responsePage.nextPageToken;\n } while (pageToken);\n}\n```\n\n\u003cbr /\u003e\n\n\u003cbr /\u003e\n\n3. Click Save .\n4. Click **Untitled project** , type **Quickstart** , and click **Rename**.\n\n\u003cbr /\u003e\n\nConfigure the script\n\nCopy the Cloud project number\n\n1. In the Google Cloud console, go to Menu menu \\\u003e **IAM \\& Admin** \\\u003e **Settings** .\n\n [Go to IAM \\& Admin Settings](https://console.cloud.google.com/iam-admin/settings)\n2. In the **Project number** field, copy the value.\n\nLink your Google Cloud project\n\n1. Open the Apps Script project.\n2. Click **Project Settings** settings.\n3. Under **Google Cloud Platform (GCP) Project** , click **Change project**.\n4. In **GCP project number**, paste the Google Cloud project number.\n5. Click **Set project**.\n\nEnable the Google Chat API\n\nOpen the Apps Script project.\n\n1. Click **Project Settings** settings.\n2. Under **General settings** , enable **Show \"appsscript.json\" manifest file\n in editor**.\n3. Click **Editor** code, select the file `appscript.json`, and replace the contents with the following code:\n\n\nchat/quickstart/appsscript.json \n[View on GitHub](https://github.com/googleworkspace/apps-script-samples/blob/main/chat/quickstart/appsscript.json) \n\n```json\n{\n \"timeZone\": \"America/New_York\",\n \"exceptionLogging\": \"STACKDRIVER\",\n \"runtimeVersion\": \"V8\",\n \"oauthScopes\": [\n \"https://www.googleapis.com/auth/chat.spaces.readonly\"\n ],\n \"chat\": {},\n \"dependencies\": {\n \"enabledAdvancedServices\": [{\n \"userSymbol\": \"Chat\",\n \"version\": \"v1\",\n \"serviceId\": \"chat\"\n }]\n }\n}\n```\n\n\u003cbr /\u003e\n\nRun the sample\n\nIn the Apps Script editor, click **Run**.\n\nThe first time you run the sample, it prompts you to authorize access:\n\n1. Click **Review permissions**.\n2. Choose an account.\n3. Click **Allow**.\n\nThe script's execution log appears at the bottom of the window. \ndone It worked! **Great!** Check out the further reading section below to learn more.\nwarning There was a problem **Bummer** , [let us know what went wrong](#). Check out our [troubleshooting](#troubleshooting) section below for some common errors and solutions. If you have found a bug in the code, [report the issue on GitHub](https://github.com/googleworkspace/apps-script-samples/issues) or submit a pull request.\n\nNext steps\n\n- [Google Apps Script Advanced Services documentation](/apps-script/guides/services/advanced)"]]