В этом руководстве показано, как создать приложение Google Chat, которое поможет пользователям Google Chat управлять своими личными и деловыми контактами. Для сбора информации приложение Chat предлагает пользователям заполнить контактную форму в карточках сообщений и диалогах.
Посмотрите, как работает приложение «Чат»:

Figure 1. The Chat app responds to the slash command /aboutwith a text message and button that opens a contact form.
Figure 2. The Chat app opens a dialog where users can input information about a contact. 
Figure 3. The Chat app returns a confirmation dialog so that users can review and confirm the information before submitting. 
Figure 4. After the user submits the form, the Chat app sends a private text message to confirm the submission. 
Figure 5. The Chat app also prompts users to add a contact from a card in a message.
Предварительные требования
- Корпоративный аккаунт Google Workspace с доступом к Google Chat .
- Create a Google Cloud project .
Цели
- Design and build user interfaces (UIs) as
cardobjects, and display the UIs in messages and dialogs. - Receive and process information that users submit using form input widgets .
- Respond to commands with messages that contain text, cards, and accessory widgets.
Архитектура
The Chat app is built in Google Apps Script and uses interaction events to process and respond to Chat users.
Ниже показано, как пользователь обычно взаимодействует с приложением «Чат»:
Пользователь открывает личное сообщение в приложении «Чат» или добавляет приложение «Чат» в уже существующее пространство.
The Chat app prompts the user to add a contact by building and displaying a contact form as a
cardobject. To present the contact form, the Chat app responds to users in the following ways:- Отвечает на упоминания (@mentions) и личные сообщения с помощью карточки, содержащей форму обратной связи.
- Responds to the slash command
/addContactby opening a dialog with the contact form. - Responds to the slash command
/aboutwith a text message that has a Add a contact button that users can click to open a dialog with the contact form.
При появлении контактной формы пользователь вводит контактную информацию в следующие поля и виджеты:
- First and last name : a
textInputwidget that accepts strings. - Birthdate : a
dateTimePickerwidget that accepts only dates. - Contact type : a
selectionInputwidget of radio buttons that lets users select and submit a single string value (eitherPersonalorWork). - Review and submit button: a
buttonListarray withbuttonwidget that the user clicks to submit the values that they input.
- First and last name : a
The Google Chat app handles a
CARD_CLICKEDinteraction event to process the values that the user inputs, and displays the values in a confirmation card.The user reviews the confirmation card and clicks the Submit button to finalize the contact information.
Приложение Google Chat отправляет личное текстовое сообщение, подтверждающее отправку.
Подготовьте окружающую среду
В этом разделе показано, как настроить проект Google Cloud для приложения «Чат».
Откройте свой облачный проект в консоли Google Cloud.
Если проект Cloud, который вы собираетесь использовать в этом примере, еще не открыт, откройте его:
- In the Google Cloud console, go to the Select a project page.
- 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 .
Настройте аутентификацию и авторизацию.
Google Chat apps require you to configure an OAuth consent screen so that users can authorize your app in Google Workspace applications, including Google Chat.
В этом руководстве вы развернете приложение чата, предназначенное только для тестирования и внутреннего использования, поэтому допустимо использовать информацию-заполнитель для экрана согласия. Перед публикацией приложения чата замените любую информацию-заполнитель реальной информацией.
In the Google Cloud console, go to Menu >Google Auth platform > Branding .
Если вы уже настроили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 :
- Under App Information , in App name , type
Contact Manager. - In User support email , select your email address or an appropriate Google group.
- Нажмите «Далее» .
- Under Audience , select Internal . If you can't select Internal , select External .
- Нажмите «Далее» .
- Under Contact Information , enter an Email address where you can be notified about any changes to your project.
- Нажмите «Далее» .
- 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 .
- Click Continue .
- Click Create .
- If you selected External for user type, add test users:
- Click Audience .
- Under Test users , click Add users .
- Enter your email address and any other authorized test users, then click Save .
- Under App Information , in App name , type
Создайте и разверните приложение «Чат».
В следующем разделе вы скопируете и обновите весь проект Apps Script, содержащий весь необходимый код приложения для вашего чат-приложения, поэтому нет необходимости копировать и вставлять каждый файл по отдельности.
При желании вы можете посмотреть весь проект на GitHub.
Вот краткий обзор каждого файла:
-
main.gs Обрабатывает всю логику приложения, включая события взаимодействия, связанные с отправкой пользователями сообщений в приложение чата, нажатием кнопок в сообщениях приложения чата, а также открытием и закрытием диалоговых окон.
View
main.gscode-
contactForm.gs Содержит виджеты, получающие данные из форм от пользователей. Эти виджеты ввода данных из форм отображаются в карточках, которые появляются в сообщениях и диалогах.
View
contactForm.gscode-
appsscript.json The Apps Script manifest that defines and configures the Apps Script project for the Chat app.
View
appsscript.jsoncode
Создайте проект Apps Script.
Для создания проекта Apps Script:
- Click the following button to open the Manage contacts in Google Chat Apps Script project.
Откройте проект - Click Overview .
- На странице обзора нажмите
Make a copy .
Назовите свою копию проекта Apps Script:
Click Copy of Manage contacts in Google Chat .
In Project title , type
Contact Manager - Google Chat appClick 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.
Теперь, когда весь код готов, разверните проект Apps Script. Идентификатор развертывания используется при настройке приложения «Чат» в Google Cloud.
В Apps Script откройте проект приложения «Чат».
Click Deploy > New deployment .
If Add-on isn't already selected, next to Select type , click deployment types
and select Add-on .
In Description , enter a description for this version, like
Test of Contact Manager.Click Deploy . Apps Script reports successful deployment and provides a deployment ID.
Click Copy to copy the deployment ID and then click Done .
Настройте приложение «Чат» в консоли Google Cloud.
В этом разделе показано, как настроить API Google Chat в консоли Google Cloud, используя информацию о вашем приложении Chat, включая идентификатор развертывания, которое вы только что создали из своего проекта Apps Script.
In the Google Cloud console, click Menu > More products > Google Workspace > Product Library > Google Chat API > Manage > Configuration .
Clear Build this Chat app as a Google Workspace add-on . A dialog opens asking you to confirm. In the dialog, click Disable .
In App name , type
Contact Manager.In Avatar URL , type
https://developers.google.com/chat/images/contact-icon.png.In Description , type
Manage your personal and business contacts.Click the Enable Interactive features toggle to the on position.
Under Functionality , select Join spaces and group conversations .
Under Connection settings , select Apps Script .
In Deployment ID , paste the Apps Script Deployment ID that you copied in the previous section when you created the Apps Script deployment.
Under Commands , set up the slash commands
/aboutand/addContact:- Click Add a slash command to set up the first slash command.
- In Name , type
About. - In Command ID , type
1. - In Description , type
Learn how to use this Chat app to manage your contacts. - Under Command type , select
Slash command. - In Slash command name , type
/about. - Select Opens a dialog .
- Click Done .
- Click Add a command to set up another slash command.
- In Name , type
Add a contact. - In Command ID , type
2. - In Description , type
Submit information about a contact. - Under Command type , select
Slash command. - In Slash command name , type
/addContact. - Select Opens a dialog .
- Click Done .
Under Visibility , select the Make this Chat app available to specific people and groups in YOUR DOMAIN checkbox and enter your email address.
Under Logs , select Log errors to Logging .
Click Save . A configuration saved message appears.
Приложение «Чат» готово к установке и тестированию в приложении «Чат».
Протестируйте приложение для чата
Чтобы протестировать приложение «Чат», откройте личное сообщение в приложении «Чат» и отправьте сообщение:
Откройте Google Chat, используя учетную запись Google Workspace, которую вы указали при добавлении себя в качестве доверенного тестировщика.
- Click New chat .
- In the Add 1 or more people field, type the name of your Chat app.
Выберите ваше приложение для чата из результатов поиска. Откроется личное сообщение.
In the new direct message with the Chat app, type
/addContactand press enter .В открывшемся диалоговом окне введите контактную информацию:
- In the First and last name text field, enter a name.
- In the Birthdate date picker, select a date.
- Under Contact type , select the Work or Personal radio button.
Click Review and submit .
In the confirmation dialog, review the information that you submitted and click Submit . The Chat app replies with a text message that says
✅ CONTACT NAME has been added to your contacts..При желании вы также можете протестировать и отправить форму обратной связи следующими способами:
- Use the
/aboutslash command. Chat app replies with a text message and an accessory widget button that saysAdd a contact. You can click the button to open a dialog with the contact form. - Send the Chat app a direct message without a slash command, such as
Hello. The Chat app replies with a text and card that contains the contact form.
- Use the
Уборка
Чтобы избежать списания средств с вашего аккаунта Google Cloud за ресурсы, использованные в этом руководстве, мы рекомендуем удалить проект Cloud.
- In the Google Cloud console, go to the Manage resources page. Click Menu > IAM & Admin > Manage Resources .
- In the project list, select the project you want to delete and then click Delete .
- In the dialog, type the project ID and then click Shut down to delete the project.
Связанные темы
- Реагировать на команды
- Сбор и обработка информации от пользователей Google Chat
- Открыть интерактивные диалоги
- Ознакомьтесь с другими примерами приложений Google Chat.