Создайте приложение Google Chat с помощью скрипта Google Apps.

На этой странице объясняется, как создать надстройку для Google Workspace, работающую в Google Chat, с помощью Google Apps Script.

Приложение «Чат» позволяет отправлять сообщения напрямую и отвечать на них, повторяя ваши сообщения.

На следующей диаграмме показана архитектура и схема обмена сообщениями:

Архитектура чат-приложения, реализованного с помощью Apps Script.

На приведенной выше диаграмме показано следующее взаимодействие пользователя с приложением Apps Script Chat:

  1. Пользователь отправляет сообщение в приложение для чата, либо в личном сообщении, либо в чате.
  2. Логика чат-приложения, реализованная в Apps Script, размещенном в Google Cloud, получает и обрабатывает сообщение.
  3. При желании логика приложения «Чат» может интегрироваться с сервисами Google Workspace, такими как Календарь или Таблицы, или с другими сервисами Google, такими как Google Maps или YouTube.
  4. Логика приложения «Чат» отправляет ответ обратно в службу приложения «Чат» внутри приложения «Чат».
  5. Ответ отправляется пользователю.

Цели

  • Настройте свою среду.
  • Настройте скрипт.
  • Настройте приложение «Чат».
  • Протестируйте приложение «Чат».

Предварительные требования

Настройте свою среду

Откройте свой облачный проект в консоли Google Cloud.

Если проект Cloud, который вы собираетесь использовать в этом примере, еще не открыт, откройте его:

  1. In the Google Cloud console, go to the Select a project page.

    Выберите облачный проект

  2. 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 .

Включите API чата

Перед использованием API Google необходимо включить их в проекте Google Cloud. В одном проекте Google Cloud можно включить один или несколько API.

В консоли Google Cloud включите API Google Chat.

Включить API

Настройте экран согласия OAuth.

Для всех приложений, использующих OAuth 2.0, требуется настройка экрана согласия. Настройка экрана согласия OAuth в вашем приложении определяет, что отображается пользователям и модераторам приложения, а также регистрирует ваше приложение, чтобы вы могли опубликовать его позже.

  1. In the Google Cloud console, go to Menu >Google Auth platform > Branding .

    Перейти к разделу «Брендинг»

  2. Если вы уже настроили Google Auth platform, you can configure the following OAuth Consent Screen settings in Branding , Audience , and Data Access . If you see a message that says Google Auth platform not configured yet , click Get Started :
    1. Under App Information , in App name , enter a name for the app.
    2. In User support email , choose a support email address where users can contact you if they have questions about their consent.
    3. Нажмите «Далее» .
    4. Under Audience , select Internal .
    5. Нажмите «Далее» .
    6. Under Contact Information , enter an Email address where you can be notified about any changes to your project.
    7. Нажмите «Далее» .
    8. Under Finish , review the Google API Services User Data Policy and if you agree, select I agree to the Google API Services: User Data Policy .
    9. Click Continue .
    10. Click Create .
  3. 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 guide.

Настройте скрипт

To set up the script, you use the Chat app template from the Apps Script Getting Started page.

Создайте проект Apps Script.

  1. From Apps Script's Getting Started page, go to Google Workspace add-on starters and click the Chat app template:

    Откройте шаблон приложения «Чат».

  2. В открывшемся новом проекте Apps Script назовите проект следующим образом:

    1. Click Untitled project .

    2. In Project title , type Add-on Chat app .

    3. Click Rename .

In the future, if you want to use certain Google APIs or publish your app, you must associate your Cloud project with your Apps Script project. For this guide, you don't need to do so. To learn more, see the Google Cloud projects guide .

Создайте тестовое развертывание.

Для этого проекта Apps Script вам потребуется идентификатор развертывания, чтобы вы могли использовать его на следующем шаге.

Чтобы получить идентификатор головного развертывания, выполните следующие действия:

  1. In the Chat app Apps Script project, click Deploy > Test deployments .
  2. Copy the Head deployment ID for use in a later step and click Done .

Настройте приложение «Чат».

Для настройки приложения Google Chat выполните следующие действия:

  1. In the console , search for Google Chat API , and click Google Chat API .
  2. Click Manage .
  3. Click Configuration and set up the Chat app:

    1. In the App name field, enter Add-on Chat app .
    2. In the Avatar URL field, enter https://developers.google.com/workspace/add-ons/images/quickstart-app-avatar.png .
    3. In the Description field, enter Add-on Chat app .
    4. Under Functionality , select Join spaces and group conversations .
    5. Under Connection settings, select Apps Script project .
    6. In the Deployment ID field, paste the Head deployment ID that you previously copied.
    7. Under Visibility, select Specific people and groups in your domain , and enter your email.
  4. Click Save .

Приложение «Чат» готово отвечать на сообщения.

Протестируйте приложение для чата

Чтобы протестировать приложение «Чат», откройте личное сообщение в приложении «Чат» и отправьте сообщение:

  1. Откройте Google Chat, используя учетную запись Google Workspace, которую вы указали при добавлении себя в качестве доверенного тестировщика.

    Перейдите в Google Чат

  2. Click New chat .
  3. In the Add 1 or more people field, type the name of your Chat app.
  4. Выберите ваше приложение для чата из результатов поиска. Откроется личное сообщение.

  5. In the new direct message with the app, type Hello and press enter .

    Приложение «Чат» благодарит вас за добавление и повторяет ваше сообщение.

To add trusted testers and learn more about testing interactive features, see Test interactive features for Google Chat apps .

Устранение неполадок

When a Google Chat app or card returns an error, the Chat interface surfaces a message saying "Something went wrong." or "Unable to process your request." Sometimes the Chat UI doesn't display any error message, but the Chat app or card produces an unexpected result; for example, a card message might not appear.

Although an error message might not display in the Chat UI, descriptive error messages and log data are available to help you fix errors when error logging for Chat apps is turned on. For help viewing, debugging, and fixing errors, see Troubleshoot and fix Google Chat errors .

Уборка

Чтобы избежать списания средств с вашего аккаунта Google Cloud за ресурсы, использованные в этом руководстве, мы рекомендуем удалить проект Cloud.

  1. In the Google Cloud console, go to the Manage resources page. Click Menu > IAM & Admin > Manage Resources .

    Перейдите в Диспетчер ресурсов

  2. In the project list, select the project you want to delete and then click Delete .
  3. In the dialog, type the project ID and then click Shut down to delete the project.