Restez organisé à l'aide des collections
Enregistrez et classez les contenus selon vos préférences.
Créez un script Google Apps qui envoie des requêtes à l'API Google Chat.
Les guides de démarrage rapide expliquent comment configurer et exécuter une application qui appelle une API Google Workspace. Ce guide de démarrage rapide utilise une approche d'authentification simplifiée qui convient à un environnement de test. Pour un environnement de production, nous vous recommandons de vous renseigner sur l'authentification et l'autorisation avant de choisir les identifiants d'accès adaptés à votre application.
Dans Apps Script, les démarrages rapides Google Workspace utilisent les services Google avancés pour appeler les API Google Workspace et gérer certains détails du flux d'authentification et d'autorisation.
Si vous utilisez un nouveau projet Google Cloud pour effectuer ce guide de démarrage rapide, vous devez le configurer et vous ajouter en tant qu'utilisateur test. Si vous avez déjà effectué ces étapes pour votre projet Cloud, passez à la section suivante.
Ouvrez votre projet Cloud dans la console Google Cloud.
Si ce n'est pas déjà fait, ouvrez le projet Cloud que vous souhaitez utiliser pour cet exemple :
Dans la console Google Cloud, accédez à la page Sélectionner un projet.
Sélectionnez le projet Google Cloud que vous souhaitez utiliser. Vous pouvez également cliquer sur Créer un projet et suivre les instructions à l'écran. Si vous créez un projet Google Cloud, vous devrez peut-être activer la facturation pour ce projet.
Activer l'API Chat
Avant d'utiliser les API Google, vous devez les activer dans un projet Google Cloud.
Vous pouvez activer une ou plusieurs API dans un même projet Google Cloud.
Dans la console Google Cloud, activez l'API Google Chat.
Si vous avez déjà configuré Google Auth platform, vous pouvez configurer les paramètres de l'écran d'autorisation OAuth suivants dans Branding, Audience et Accès aux données. Si le message Google Auth platform pas encore configuré s'affiche, cliquez sur Commencer :
Sous Informations sur l'application, dans Nom de l'application, saisissez le nom de l'application.
Dans Adresse e-mail d'assistance utilisateur, sélectionnez une adresse e-mail d'assistance que les utilisateurs pourront contacter s'ils ont des questions sur leur consentement.
Cliquez sur Suivant.
Sous Audience, sélectionnez Interne.
Cliquez sur Suivant.
Sous Coordonnées, saisissez une adresse e-mail à laquelle vous pourrez être informé de toute modification apportée à votre projet.
Pour l'instant, vous pouvez ignorer l'ajout de portées.
À l'avenir, lorsque vous créerez une application à utiliser en dehors de votre organisation Google Workspace, vous devrez définir le type d'utilisateur sur Externe. Ajoutez ensuite les niveaux d'autorisation dont votre application a besoin. Pour en savoir plus, consultez le guide complet Configurer le consentement OAuth.
Configurer l'application Google Chat
Pour appeler l'API Google Chat, vous devez configurer une application Google Chat. Pour toute requête d'écriture, Google Chat attribue l'application Google Chat dans l'UI à l'aide des informations suivantes.
Dans la console Google Cloud, accédez à la page Configuration de l'API Chat :
Sous Informations sur l'application, saisissez les informations suivantes :
Dans le champ Nom de l'application, saisissez Chat API quickstart app.
Dans le champ URL de l'avatar, saisissez https://developers.google.com/chat/images/quickstart-app-avatar.png.
Dans le champ Description, saisissez Quickstart for calling the Chat API.
Sous Fonctionnalités interactives, cliquez sur le bouton Activer les fonctionnalités interactives pour désactiver les fonctionnalités interactives de l'application 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);}
Cliquez sur Enregistrer .
Cliquez sur Projet sans titre, saisissez Quickstart, puis cliquez sur Renommer.
Configurer le script
Copier le numéro du projet Cloud
Dans la console Google Cloud, accédez à Menu menu>IAM et administration>Paramètres.
Sauf indication contraire, le contenu de cette page est régi par une licence Creative Commons Attribution 4.0, et les échantillons de code sont régis par une licence Apache 2.0. Pour en savoir plus, consultez les Règles du site Google Developers. Java est une marque déposée d'Oracle et/ou de ses sociétés affiliées.
Dernière mise à jour le 2025/08/29 (UTC).
[null,null,["Dernière mise à jour le 2025/08/29 (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```javascript\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)\n- [Try the Google Workspace APIs in the APIs explorer](/workspace/explore)"]]