Package google.chat.v1

Индекс

ЧатСервис

Позволяет разработчикам создавать приложения Chat и их интеграцию на платформе Google Chat.

CompleteImportSpace

rpc CompleteImportSpace( CompleteImportSpaceRequest ) returns ( CompleteImportSpaceResponse )

Завершает процесс импорта указанного пространства и делает его видимым для пользователей. Требуется аутентификация приложения и делегирование на уровне домена. Дополнительную информацию см. в разделе Разрешение приложениям Google Chat импортировать данные .

Области авторизации

Требуется следующая область действия OAuth:

  • https://www.googleapis.com/auth/chat.import

Дополнительную информацию см. в руководстве по авторизации .

Создать членство

rpc CreateMembership( CreateMembershipRequest ) returns ( Membership )

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

Чтобы указать добавляемого участника, задайте membership.member.name для человека или участника приложения или задайте membership.group_member.name для члена группы.

  • Чтобы добавить вызывающее приложение в пространство или прямое сообщение между двумя пользователями-людьми, используйтеusers users/app . Невозможно добавить в пространство другие приложения.

  • Чтобы добавить пользователя-человека, используйте users/{user} , где {user} может быть адресом электронной почты пользователя. Для пользователей в одной организации Workspace {user} также может быть id человека из API People или id пользователя в API каталога. Например, если идентификатор профиля пользователя People API для user@example.com123456789 , вы можете добавить пользователя в пространство, задав для membership.member.name users/user@example.com илиusers users/123456789 .

  • Чтобы добавить или пригласить группу Google в именованное пространство, используйте groups/{group} , где {group} — это id группы из Cloud Identity Groups API. Например, вы можете использовать API поиска групп Cloud Identity , чтобы получить идентификатор 123456789 для адреса электронной почты группы group@example.com , а затем добавить или пригласить группу в именованное пространство, задав для membership.group_member.name значение groups/123456789 . Групповая электронная почта не поддерживается, а группы Google можно добавлять только в качестве участников в именованных пространствах.

Области авторизации

Требуется одна из следующих областей OAuth:

  • https://www.googleapis.com/auth/chat.admin.memberships
  • https://www.googleapis.com/auth/chat.import
  • https://www.googleapis.com/auth/chat.memberships
  • https://www.googleapis.com/auth/chat.memberships.app

Дополнительную информацию см. в руководстве по авторизации .

Создать сообщение

rpc CreateMessage( CreateMessageRequest ) returns ( Message )

Создает сообщение в чате Google. Максимальный размер сообщения, включая текст и карточки, составляет 32 000 байт. Пример см. в разделе «Отправить сообщение» .

Вызов этого метода требует аутентификации и поддерживает следующие типы аутентификации:

  • Для текстовых сообщений поддерживается аутентификация пользователя или аутентификация приложения.
  • Для карточных сообщений поддерживается только аутентификация приложения. (Только приложения чата могут создавать карточные сообщения.)
Области авторизации

Требуется одна из следующих областей OAuth:

  • https://www.googleapis.com/auth/chat.bot
  • https://www.googleapis.com/auth/chat.import
  • https://www.googleapis.com/auth/chat.messages
  • https://www.googleapis.com/auth/chat.messages.create

Дополнительную информацию см. в руководстве по авторизации .

Создатьреакцию

rpc CreateReaction( CreateReactionRequest ) returns ( Reaction )

Создает реакцию и добавляет ее в сообщение. Поддерживаются только смайлы Юникода. Пример см. в разделе Добавление реакции на сообщение . Требует аутентификации пользователя .

Области авторизации

Требуется одна из следующих областей OAuth:

  • https://www.googleapis.com/auth/chat.import
  • https://www.googleapis.com/auth/chat.messages
  • https://www.googleapis.com/auth/chat.messages.reactions
  • https://www.googleapis.com/auth/chat.messages.reactions.create

Дополнительную информацию см. в руководстве по авторизации .

Создать пространство

rpc CreateSpace( CreateSpaceRequest ) returns ( Space )

Создает именованное пространство. Пространства, сгруппированные по темам, не поддерживаются. Пример см. в разделе Создание пространства .

Если при создании пространства вы получаете сообщение об ошибке ALREADY_EXISTS , попробуйте другое displayName . Возможно, это отображаемое имя уже используется в существующем пространстве в организации Google Workspace.

Требует аутентификации пользователя .

Области авторизации

Требуется одна из следующих областей OAuth:

  • https://www.googleapis.com/auth/chat.import
  • https://www.googleapis.com/auth/chat.spaces
  • https://www.googleapis.com/auth/chat.spaces.create

Дополнительную информацию см. в руководстве по авторизации .

Удалить членство

rpc DeleteMembership( DeleteMembershipRequest ) returns ( Membership )

Удаляет членство. Пример см. в статье Удаление пользователя или приложения Google Chat из пространства .

Требует аутентификации пользователя .

Области авторизации

Требуется одна из следующих областей OAuth:

  • https://www.googleapis.com/auth/chat.admin.memberships
  • https://www.googleapis.com/auth/chat.import
  • https://www.googleapis.com/auth/chat.memberships
  • https://www.googleapis.com/auth/chat.memberships.app

Дополнительную информацию см. в руководстве по авторизации .

Удалить сообщение

rpc DeleteMessage( DeleteMessageRequest ) returns ( Empty )

Удаляет сообщение. Пример см. в разделе Удаление сообщения .

Требует аутентификации . Поддерживает аутентификацию приложений и аутентификацию пользователей . При использовании аутентификации приложения запросы могут удалять только сообщения, созданные вызывающим приложением чата.

Области авторизации

Требуется одна из следующих областей OAuth:

  • https://www.googleapis.com/auth/chat.bot
  • https://www.googleapis.com/auth/chat.import
  • https://www.googleapis.com/auth/chat.messages

Дополнительную информацию см. в руководстве по авторизации .

Удалитьреакцию

rpc DeleteReaction( DeleteReactionRequest ) returns ( Empty )

Удаляет реакцию на сообщение. Поддерживаются только смайлы Юникода. Пример см. в разделе Удаление реакции . Требует аутентификации пользователя .

Области авторизации

Требуется одна из следующих областей OAuth:

  • https://www.googleapis.com/auth/chat.import
  • https://www.googleapis.com/auth/chat.messages
  • https://www.googleapis.com/auth/chat.messages.reactions

Дополнительную информацию см. в руководстве по авторизации .

Удалить пространство

rpc DeleteSpace( DeleteSpaceRequest ) returns ( Empty )

Удаляет именованное пространство. Всегда выполняет каскадное удаление, что означает, что дочерние ресурсы пространства, такие как сообщения, опубликованные в пространстве, и членство в пространстве, также удаляются. Пример см. в разделе Удаление пробела . Требуется аутентификация пользователя от пользователя, у которого есть разрешение на удаление пространства.

Области авторизации

Требуется одна из следующих областей OAuth:

  • https://www.googleapis.com/auth/chat.admin.delete
  • https://www.googleapis.com/auth/chat.import
  • https://www.googleapis.com/auth/chat.delete

Дополнительную информацию см. в руководстве по авторизации .

НайтиDirectMessage

rpc FindDirectMessage( FindDirectMessageRequest ) returns ( Space )

Возвращает существующее прямое сообщение указанному пользователю. Если пространство для прямых сообщений не найдено, возвращается ошибка 404 NOT_FOUND . Пример см. в разделе «Найти прямое сообщение» .

При аутентификации пользователя возвращает пространство прямого сообщения между указанным пользователем и пользователем, прошедшим проверку подлинности.

При проверке подлинности приложения возвращает пространство прямого сообщения между указанным пользователем и вызывающим приложением чата.

Требуется аутентификация пользователя или аутентификация приложения .

Области авторизации

Требуется одна из следующих областей OAuth:

  • https://www.googleapis.com/auth/chat.spaces
  • https://www.googleapis.com/auth/chat.spaces.readonly
  • https://www.googleapis.com/auth/chat.bot

Дополнительную информацию см. в руководстве по авторизации .

Получить вложение

rpc GetAttachment( GetAttachmentRequest ) returns ( Attachment )

Получает метаданные вложения сообщения. Данные вложения извлекаются с помощью медиа API . Пример см. в разделе Получение метаданных о вложении сообщения . Требуется аутентификация приложения .

Области авторизации

Требуется следующая область действия OAuth:

  • https://www.googleapis.com/auth/chat.bot

Дополнительную информацию см. в руководстве по авторизации .

Получить членство

rpc GetMembership( GetMembershipRequest ) returns ( Membership )

Возвращает сведения о членстве. Пример см. в разделе Получение сведений о членстве пользователя или приложения Google Chat .

Требует аутентификации . Поддерживает аутентификацию приложений и аутентификацию пользователей .

Области авторизации

Требуется одна из следующих областей OAuth:

  • https://www.googleapis.com/auth/chat.admin.memberships
  • https://www.googleapis.com/auth/chat.admin.memberships.readonly
  • https://www.googleapis.com/auth/chat.bot
  • https://www.googleapis.com/auth/chat.memberships
  • https://www.googleapis.com/auth/chat.memberships.readonly

Дополнительную информацию см. в руководстве по авторизации .

Получить сообщение

rpc GetMessage( GetMessageRequest ) returns ( Message )

Возвращает сведения о сообщении. Пример см. в разделе Получение сведений о сообщении .

Требует аутентификации . Поддерживает аутентификацию приложений и аутентификацию пользователей .

Примечание. Может вернуть сообщение от заблокированного участника или пространства.

Области авторизации

Требуется одна из следующих областей OAuth:

  • https://www.googleapis.com/auth/chat.bot
  • https://www.googleapis.com/auth/chat.messages
  • https://www.googleapis.com/auth/chat.messages.readonly

Дополнительную информацию см. в руководстве по авторизации .

GetSpace

rpc GetSpace( GetSpaceRequest ) returns ( Space )

Возвращает подробную информацию о пространстве. Пример см. в разделе Получение сведений о пространстве .

Требует аутентификации . Поддерживает аутентификацию приложений и аутентификацию пользователей .

Области авторизации

Требуется одна из следующих областей OAuth:

  • https://www.googleapis.com/auth/chat.admin.spaces
  • https://www.googleapis.com/auth/chat.admin.spaces.readonly
  • https://www.googleapis.com/auth/chat.spaces
  • https://www.googleapis.com/auth/chat.spaces.readonly
  • https://www.googleapis.com/auth/chat.bot

Дополнительную информацию см. в руководстве по авторизации .

GetSpaceEvent

rpc GetSpaceEvent( GetSpaceEventRequest ) returns ( SpaceEvent )

Возвращает событие из пространства Google Chat. Полезные данные события содержат самую последнюю версию измененного ресурса. Например, если вы запрашиваете событие о новом сообщении, но позже оно было обновлено, сервер возвращает обновленный ресурс Message в полезных данных события.

Требует аутентификации пользователя . Чтобы получить событие, аутентифицированный пользователь должен быть членом пространства.

Пример см. в разделе Получение сведений о событии из чата Google .

Области авторизации

Требуется одна из следующих областей OAuth:

  • https://www.googleapis.com/auth/chat.spaces
  • https://www.googleapis.com/auth/chat.spaces.readonly
  • https://www.googleapis.com/auth/chat.messages
  • https://www.googleapis.com/auth/chat.messages.readonly
  • https://www.googleapis.com/auth/chat.memberships
  • https://www.googleapis.com/auth/chat.memberships.readonly
  • https://www.googleapis.com/auth/chat.messages.reactions
  • https://www.googleapis.com/auth/chat.messages.reactions.readonly

Дополнительную информацию см. в руководстве по авторизации .

GetSpaceReadState

rpc GetSpaceReadState( GetSpaceReadStateRequest ) returns ( SpaceReadState )

Возвращает сведения о состоянии чтения пользователя в пространстве, используемые для идентификации прочитанных и непрочитанных сообщений. Пример см. в разделе Получение сведений о состоянии чтения пространства пользователя .

Требует аутентификации пользователя .

Области авторизации

Требуется одна из следующих областей OAuth:

  • https://www.googleapis.com/auth/chat.users.readstate
  • https://www.googleapis.com/auth/chat.users.readstate.readonly

Дополнительную информацию см. в руководстве по авторизации .

GetThreadReadState

rpc GetThreadReadState( GetThreadReadStateRequest ) returns ( ThreadReadState )

Возвращает сведения о состоянии чтения пользователя в потоке, используемые для идентификации прочитанных и непрочитанных сообщений. Пример см. в разделе Получение сведений о состоянии чтения потока пользователя .

Требует аутентификации пользователя .

Области авторизации

Требуется одна из следующих областей OAuth:

  • https://www.googleapis.com/auth/chat.users.readstate
  • https://www.googleapis.com/auth/chat.users.readstate.readonly

Дополнительную информацию см. в руководстве по авторизации .

Список членства

rpc ListMemberships( ListMembershipsRequest ) returns ( ListMembershipsResponse )

Перечисляет членство в пространстве. Пример см. в разделе Список пользователей и приложений Google Chat в пространстве . В списке участников с проверкой подлинности приложения перечислены участники в пространствах, к которым у приложения Chat есть доступ, но исключаются членства в приложении Chat, включая собственное. В списке участников с аутентификацией пользователя перечислены членства в пространствах, к которым имеет доступ аутентифицированный пользователь.

Требует аутентификации . Поддерживает аутентификацию приложений и аутентификацию пользователей .

Области авторизации

Требуется одна из следующих областей OAuth:

  • https://www.googleapis.com/auth/chat.admin.memberships
  • https://www.googleapis.com/auth/chat.admin.memberships.readonly
  • https://www.googleapis.com/auth/chat.import
  • https://www.googleapis.com/auth/chat.bot
  • https://www.googleapis.com/auth/chat.memberships
  • https://www.googleapis.com/auth/chat.memberships.readonly

Дополнительную информацию см. в руководстве по авторизации .

Список сообщений

rpc ListMessages( ListMessagesRequest ) returns ( ListMessagesResponse )

Перечисляет сообщения в пространстве, участником которого является вызывающий абонент, включая сообщения от заблокированных участников и пространств. Пример см. в разделе Список сообщений . Требует аутентификации пользователя .

Области авторизации

Требуется одна из следующих областей OAuth:

  • https://www.googleapis.com/auth/chat.import
  • https://www.googleapis.com/auth/chat.messages
  • https://www.googleapis.com/auth/chat.messages.readonly

Дополнительную информацию см. в руководстве по авторизации .

Список реакций

rpc ListReactions( ListReactionsRequest ) returns ( ListReactionsResponse )

Перечисляет реакции на сообщение. Пример см. в разделе Список реакций на сообщение . Требует аутентификации пользователя .

Области авторизации

Требуется одна из следующих областей OAuth:

  • https://www.googleapis.com/auth/chat.messages
  • https://www.googleapis.com/auth/chat.messages.readonly
  • https://www.googleapis.com/auth/chat.messages.reactions
  • https://www.googleapis.com/auth/chat.messages.reactions.readonly

Дополнительную информацию см. в руководстве по авторизации .

ListSpaceEvents

rpc ListSpaceEvents( ListSpaceEventsRequest ) returns ( ListSpaceEventsResponse )

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

Требует аутентификации пользователя . Чтобы составить список событий, аутентифицированный пользователь должен быть участником пространства.

Пример см. в разделе Список событий из чата Google .

Области авторизации

Требуется одна из следующих областей OAuth:

  • https://www.googleapis.com/auth/chat.spaces
  • https://www.googleapis.com/auth/chat.spaces.readonly
  • https://www.googleapis.com/auth/chat.messages
  • https://www.googleapis.com/auth/chat.messages.readonly
  • https://www.googleapis.com/auth/chat.memberships
  • https://www.googleapis.com/auth/chat.memberships.readonly
  • https://www.googleapis.com/auth/chat.messages.reactions
  • https://www.googleapis.com/auth/chat.messages.reactions.readonly

Дополнительную информацию см. в руководстве по авторизации .

Список пространств

rpc ListSpaces( ListSpacesRequest ) returns ( ListSpacesResponse )

Перечисляет пространства, членом которых является вызывающий абонент. Групповые чаты и личные сообщения не отображаются в списке до тех пор, пока не будет отправлено первое сообщение. Пример см. в разделе Пространства списков .

Требует аутентификации . Поддерживает аутентификацию приложений и аутентификацию пользователей .

Перечисляет пространства, видимые вызывающему абоненту или аутентифицированному пользователю. Групповые чаты и личные сообщения не отображаются в списке до тех пор, пока не будет отправлено первое сообщение.

Чтобы получить список всех именованных пространств по организациям Google Workspace, используйте вместо этого метод spaces.search() с правами администратора Workspace.

Области авторизации

Требуется одна из следующих областей OAuth:

  • https://www.googleapis.com/auth/chat.spaces
  • https://www.googleapis.com/auth/chat.spaces.readonly
  • https://www.googleapis.com/auth/chat.bot

Дополнительную информацию см. в руководстве по авторизации .

Поиск пространств

rpc SearchSpaces( SearchSpacesRequest ) returns ( SearchSpacesResponse )

Возвращает список пространств на основе поиска пользователя. Требует аутентификации пользователя . Пользователь должен быть администратором организации Google Workspace. В запросе установите для use_admin_access значение true .

Области авторизации

Требуется одна из следующих областей OAuth:

  • https://www.googleapis.com/auth/chat.admin.spaces
  • https://www.googleapis.com/auth/chat.admin.spaces.readonly

Дополнительную информацию см. в руководстве по авторизации .

SetUpSpace

rpc SetUpSpace( SetUpSpaceRequest ) returns ( Space )

Создает пространство и добавляет в него указанных пользователей. Вызывающий пользователь автоматически добавляется в пространство и не должен указываться как член в запросе. Пример см. в разделе «Настройка пространства с первоначальными участниками» .

Чтобы указать добавляемых участников-людей, добавьте членство с соответствующим membership.member.name . Чтобы добавить пользователя-человека, используйте users/{user} , где {user} может быть адресом электронной почты пользователя. Для пользователей в одной организации Workspace {user} также может быть id человека из API People или id пользователя в API каталога. Например, если идентификатор профиля пользователя People API для user@example.com123456789 , вы можете добавить пользователя в пространство, задав для membership.member.name users/user@example.com илиusers users/123456789 .

Чтобы указать группы Google для добавления, добавьте членство с соответствующим membership.group_member.name . Чтобы добавить или пригласить группу Google, используйте groups/{group} , где {group} — это id группы из Cloud Identity Groups API. Например, вы можете использовать API поиска групп Cloud Identity для получения идентификатора 123456789 для адреса электронной почты группы group@example.com , а затем добавить группу в пространство, задав для membership.group_member.name значение groups/123456789 . Групповая электронная почта не поддерживается, а группы Google можно добавлять только в качестве участников в именованных пространствах.

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

Чтобы создать прямое сообщение (DM) между вызывающим пользователем и другим пользователем-человеком, укажите ровно одно членство, которое будет представлять пользователя-человека. Если один пользователь блокирует другого, запрос не выполняется и DM не создается.

Чтобы создать DM между вызывающим пользователем и вызывающим приложением, установите для Space.singleUserBotDm значение true и не указывайте членство. Вы можете использовать этот метод только для настройки DM с вызывающим приложением. Чтобы добавить вызывающее приложение в качестве участника пространства или существующего DM между двумя пользователями-людьми, см. Приглашение или добавление пользователя или приложения в пространство .

Если DM уже существует между двумя пользователями, даже если один пользователь блокирует другого во время запроса, тогда возвращается существующая DM.

Темы с цепочками ответов не поддерживаются. Если при настройке пространства вы получаете сообщение об ошибке ALREADY_EXISTS , попробуйте другое displayName . Возможно, это отображаемое имя уже используется в существующем пространстве в организации Google Workspace.

Требует аутентификации пользователя .

Области авторизации

Требуется одна из следующих областей OAuth:

  • https://www.googleapis.com/auth/chat.spaces
  • https://www.googleapis.com/auth/chat.spaces.create

Дополнительную информацию см. в руководстве по авторизации .

Обновление членства

rpc UpdateMembership( UpdateMembershipRequest ) returns ( Membership )

Обновляет членство. Пример см. в разделе Обновление членства пользователя в пространстве .

Требует аутентификации пользователя .

Области авторизации

Требуется одна из следующих областей OAuth:

  • https://www.googleapis.com/auth/chat.admin.memberships
  • https://www.googleapis.com/auth/chat.import
  • https://www.googleapis.com/auth/chat.memberships

Дополнительную информацию см. в руководстве по авторизации .

Обновление сообщения

rpc UpdateMessage( UpdateMessageRequest ) returns ( Message )

Обновляет сообщение. Существует разница между методами patch и update . Метод patch использует запрос patch , а метод update использует запрос put . Мы рекомендуем использовать метод patch . Пример см. в разделе Обновление сообщения .

Требует аутентификации . Поддерживает аутентификацию приложений и аутентификацию пользователей . При использовании аутентификации приложения запросы могут обновлять только сообщения, созданные вызывающим приложением чата.

Области авторизации

Требуется одна из следующих областей OAuth:

  • https://www.googleapis.com/auth/chat.bot
  • https://www.googleapis.com/auth/chat.import
  • https://www.googleapis.com/auth/chat.messages

Дополнительную информацию см. в руководстве по авторизации .

ОбновлениеПространство

rpc UpdateSpace( UpdateSpaceRequest ) returns ( Space )

Обновляет пространство. Пример см. в разделе Обновление пространства .

Если вы обновляете поле displayName и получаете сообщение об ошибке ALREADY_EXISTS , попробуйте другое отображаемое имя. Возможно, существующее пространство в организации Google Workspace уже использует это отображаемое имя.

Требует аутентификации пользователя .

Области авторизации

Требуется одна из следующих областей OAuth:

  • https://www.googleapis.com/auth/chat.admin.spaces
  • https://www.googleapis.com/auth/chat.import
  • https://www.googleapis.com/auth/chat.spaces

Дополнительную информацию см. в руководстве по авторизации .

UpdateSpaceReadState

rpc UpdateSpaceReadState( UpdateSpaceReadStateRequest ) returns ( SpaceReadState )

Обновляет состояние чтения пользователя в пространстве, используемое для идентификации прочитанных и непрочитанных сообщений. Пример см . в разделе Обновление состояния чтения пространства пользователя .

Требует аутентификации пользователя .

Области авторизации

Требуется следующая область действия OAuth:

  • https://www.googleapis.com/auth/chat.users.readstate

Дополнительную информацию см. в руководстве по авторизации .

АксессуарВиджет

Один или несколько интерактивных виджетов, которые появляются внизу сообщения. Подробности см. в разделе Добавление интерактивных виджетов внизу сообщения .

Поля
Полевые action Союза. Тип действия. action может быть только одним из следующих:
button_list

ButtonList

Список кнопок.

ДействиеОтвет

Параметры, которые приложение чата может использовать для настройки способа публикации ответа.

Поля
type

ResponseType

Только ввод. Тип ответа приложения Chat.

url

string

Только ввод. URL-адрес для пользователей для аутентификации или настройки. (Только для типов ответов REQUEST_CONFIG .)

dialog_action

DialogAction

Только ввод. Ответ на событие взаимодействия, связанное с диалогом . Должен сопровождаться ResponseType.Dialog .

updated_widget

UpdatedWidget

Только ввод. Ответ обновленного виджета.

Тип ответа

Тип ответа приложения Chat.

Перечисления
TYPE_UNSPECIFIED Тип по умолчанию, который обрабатывается как NEW_MESSAGE .
NEW_MESSAGE Опубликовать как новое сообщение в теме.
UPDATE_MESSAGE Обновите сообщение приложения Chat. Это разрешено только для события CARD_CLICKED , где тип отправителя сообщения — BOT .
UPDATE_USER_MESSAGE_CARDS Обновите карточки в сообщении пользователя. Это разрешено только в качестве ответа на событие MESSAGE с совпадающим URL-адресом или событие CARD_CLICKED где тип отправителя сообщения — HUMAN . Текст игнорируется.
REQUEST_CONFIG В частном порядке запросите у пользователя дополнительную аутентификацию или настройку.
DIALOG Представляет диалог .
UPDATE_WIDGET Запрос параметров автозаполнения текста виджета.

Элементы выбора

Список результатов автозаполнения виджета.

Поля
items[]

SelectionItem

Массив объектов SelectionItem.

Обновленный виджет

Ответ обновленного виджета. Используется для предоставления параметров автозаполнения для виджета.

Поля
widget

string

Идентификатор обновленного виджета. Идентификатор должен совпадать с идентификатором виджета, который инициировал запрос на обновление.

Поле объединения updated_widget . Виджет обновляется в ответ на действие пользователя. updated_widget может быть только одним из следующих:
suggestions

SelectionItems

Список результатов автозаполнения виджета

Статус действия

Представляет состояние запроса на вызов или отправку диалога .

Поля
status_code

Code

Код состояния.

user_facing_message

string

Сообщение для отправки пользователям о статусе их запроса. Если значение не установлено, отправляется общее сообщение на основе status_code .

Аннотация

Только вывод. Аннотации, связанные с текстовым телом сообщения. Чтобы добавить базовое форматирование к текстовому сообщению, см. раздел Форматирование текстовых сообщений .

Пример тела сообщения в виде обычного текста:

Hello @FooBot how are you!"

Соответствующие метаданные аннотаций:

"annotations":[{
  "type":"USER_MENTION",
  "startIndex":6,
  "length":7,
  "userMention": {
    "user": {
      "name":"users/{user}",
      "displayName":"FooBot",
      "avatarUrl":"https://goo.gl/aeDtrS",
      "type":"BOT"
    },
    "type":"MENTION"
   }
}]
Поля
type

AnnotationType

Тип этой аннотации.

length

int32

Длина подстроки в теле сообщения в виде обычного текста, которой соответствует эта аннотация.

start_index

int32

Начальный индекс (от 0 включительно) в теле текстового сообщения, которому соответствует эта аннотация.

metadata поля объединения. Дополнительные метаданные об аннотации. metadata могут быть только одним из следующих:
user_mention

UserMentionMetadata

Метаданные упоминания пользователя.

slash_command

SlashCommandMetadata

Метаданные для косой черты.

Тип аннотации

Тип аннотации.

Перечисления
ANNOTATION_TYPE_UNSPECIFIED Значение по умолчанию для перечисления. Не используйте.
USER_MENTION Упоминается пользователь.
SLASH_COMMAND Вызывается команда косой черты.

ПрикрепленоGif

Изображение GIF, указанное URL-адресом.

Поля
uri

string

Только вывод. URL-адрес, на котором размещено изображение GIF.

Вложение

Вложение в Google Chat.

Поля
name

string

Имя ресурса вложения в форме spaces/{space}/messages/{message}/attachments/{attachment} .

content_name

string

Только вывод. Исходное имя файла содержимого, а не полный путь.

content_type

string

Только вывод. Тип содержимого (тип MIME) файла.

thumbnail_uri

string

Только вывод. URL-адрес миниатюры, который следует использовать для предварительного просмотра вложения пользователю-человеку. Приложения чата не должны использовать этот URL-адрес для загрузки содержимого вложений.

download_uri

string

Только вывод. URL-адрес загрузки, который следует использовать, чтобы позволить пользователю-человеку загрузить вложение. Приложения чата не должны использовать этот URL-адрес для загрузки содержимого вложений.

source

Source

Только вывод. Источник вложения.

Поле объединения data_ref . Ссылка на данные во вложении. data_ref может быть только одним из следующих:
attachment_data_ref

AttachmentDataRef

Ссылка на данные вложения. Это поле используется с медиа-API для загрузки данных вложения.

drive_data_ref

DriveDataRef

Только вывод. Ссылка на вложение Google Диска. Это поле используется с API Google Диска.

Источник

Источник вложения.

Перечисления
SOURCE_UNSPECIFIED Сдержанный.
DRIVE_FILE Это файл Google Диска.
UPLOADED_CONTENT Файл будет загружен в чат.

ссылка на вложение данных

Ссылка на данные вложения.

Поля
resource_name

string

Имя ресурса данных вложения. Это поле используется с медиа-API для загрузки данных вложения.

attachment_upload_token

string

Непрозрачный токен, содержащий ссылку на загруженный вложение. Рассматривается клиентами как непрозрачная строка и используется для создания или обновления сообщений чата с вложениями.

Картасид

Карточка в сообщении Google Chat.

Только приложения чата могут создавать карточки. Если ваше приложение Chat авторизуется как пользователь , сообщение не может содержать карточки.

Создавайте и просматривайте карты с помощью Card Builder.

Откройте конструктор карточек

Поля
card_id

string

Требуется, если сообщение содержит несколько карточек. Уникальный идентификатор карты в сообщении.

card

Card

Карта. Максимальный размер — 32 КБ.

ChatSpaceLinkData

Данные для ссылок в чате.

Поля
space

string

Пространство связанного ресурса пространства чата.

Формат: spaces/{space}

thread

string

Ветка связанного ресурса чата.

Формат: spaces/{space}/threads/{thread}

message

string

Сообщение связанного ресурса пространства чата.

Формат: spaces/{space}/messages/{message}

Завершить импорт пространства запрос

Сообщение с запросом о завершении процесса импорта пространства.

Поля
name

string

Необходимый. Имя ресурса пространства режима импорта.

Формат: spaces/{space}

Комплеимпортспейсереспонс

Ответное сообщение о завершении процесса импорта пространства.

Поля
space

Space

Пространство режима импорта.

Контекстная надстройкаразметка

Этот тип не имеет полей.

Разметка, позволяющая разработчикам указывать содержимое контекстной надстройки.

Карта

Карточка — это элемент пользовательского интерфейса, который может содержать виджеты пользовательского интерфейса, такие как текст и изображения.

Поля
header

CardHeader

Заголовок карты. Заголовок обычно содержит заголовок и изображение.

sections[]

Section

Разделы разделены разделителем строк.

card_actions[]

CardAction

Действия этой карты.

name

string

Название карты.

КартаДействие

Действие карты — это действие, связанное с картой. Для карточки счета-фактуры типичным действием будет: удалить счет, отправить счет по электронной почте или открыть счет в браузере.

Не поддерживается приложениями Google Chat.

Поля
action_label

string

Метка раньше отображалась в пункте меню действий.

on_click

OnClick

Действие onclick для этого элемента действия.

Заголовок карты

Поля
title

string

Должно быть указано название. Заголовок имеет фиксированную высоту: если указаны и заголовок, и подзаголовок, каждый занимает одну строку. Если указан только заголовок, он занимает обе строки.

subtitle

string

Подзаголовок шапки карты.

image_style

ImageStyle

Тип изображения (например, квадратная или круглая рамка).

image_url

string

URL-адрес изображения в заголовке карточки.

Стиль изображения

Перечисления
IMAGE_STYLE_UNSPECIFIED
IMAGE Квадратная граница.
AVATAR Круглая граница.

Раздел

Раздел содержит коллекцию виджетов, которые отображаются (вертикально) в том порядке, в котором они указаны. На всех платформах карточки имеют узкую фиксированную ширину, поэтому в настоящее время нет необходимости в свойствах макета (например, float).

Поля
header

string

Заголовок раздела. Поддерживается форматированный текст. Дополнительную информацию о форматировании текста см. в разделах «Форматирование текста в приложениях Google Chat» и «Форматирование текста в надстройках Google Workspace» .

widgets[]

WidgetMarkup

Раздел должен содержать хотя бы один виджет.

Создать запрос на членство

Сообщение с запросом на создание членства.

Поля
parent

string

Необходимый. Имя ресурса пространства, для которого необходимо создать членство.

Формат: пробелы/{пробел}

membership

Membership

Необходимый. Отношение членства для создания. memberType должно содержать пользователя с заполненными полями user.name и user.type . Сервер назначит имя ресурса и перезапишет все указанное. Когда приложение чата создает отношение членства для пользователя-человека, оно должно использовать область chat.memberships , установить для user.type значение HUMAN и задать user.name в формате users/{user} , где {user} может быть адресом электронной почты. адрес для пользователя. Для пользователей в одной организации Workspace {user} также может быть id человека из API People или id пользователя в API каталога. Например, если идентификатор профиля пользователя People API для user@example.com123456789 , вы можете добавить пользователя в пространство, задав для membership.member.name users/user@example.com илиusers users/123456789 . Когда приложение чата создает для себя отношение членства, оно должно использовать область chat.memberships.app , установить для user.type значение BOT и задать для user.name users/app .

use_admin_access

bool

Если true , метод запускается с использованием прав администратора Google Workspace пользователя.

Вызывающий пользователь должен быть администратором Google Workspace с правом управления чатом и беседами в чат-группах .

Требуется область действия OAuth 2.0 chat.admin.memberships .

Создание членства в приложении или членство для пользователей за пределами организации Google Workspace, принадлежащей администратору, не поддерживается с использованием доступа администратора.

Создать запрос сообщения

Создает сообщение.

Поля
parent

string

Необходимый. Имя ресурса пространства, в котором создается сообщение.

Формат: spaces/{space}

message

Message

Необходимый. Тело сообщения.

thread_key
(deprecated)

string

Необязательный. Устарело: вместо этого используйте thread.thread_key . Идентификатор потока. Поддерживает до 4000 символов. Чтобы запустить поток или добавить его, создайте сообщение и укажите threadKey или thread.name . Пример использования см . в разделе «Начать цепочку сообщений или ответить на нее» .

request_id

string

Необязательный. Уникальный идентификатор запроса для этого сообщения. Указание существующего идентификатора запроса возвращает сообщение, созданное с этим идентификатором, вместо создания нового сообщения.

message_reply_option

MessageReplyOption

Необязательный. Указывает, запускает ли сообщение цепочку или отвечает на нее. Поддерживается только в именованных пространствах.

message_id

string

Необязательный. Пользовательский идентификатор сообщения. Позволяет приложениям чата получать, обновлять или удалять сообщения без необходимости сохранять назначенный системой идентификатор в имени ресурса сообщения (представленном в поле name сообщения).

Значение этого поля должно соответствовать следующим требованиям:

  • Начинается с client- . Например, client-custom-name является допустимым пользовательским идентификатором, а custom-name — нет.
  • Содержит до 63 символов и только строчные буквы, цифры и дефисы.
  • Уникальна в пространстве. Приложение чата не может использовать один и тот же собственный идентификатор для разных сообщений.

Подробности см. в разделе Назовите сообщение .

Опция ответа сообщения

Указывает, как ответить на сообщение. В будущем могут быть добавлены и другие штаты.

Перечисления
MESSAGE_REPLY_OPTION_UNSPECIFIED По умолчанию. Начинает новую тему. Использование этой опции игнорирует любой включенный thread ID или thread_key .
REPLY_MESSAGE_FALLBACK_TO_NEW_THREAD Создает сообщение как ответ на поток, указанный thread ID или thread_key . Если это не удается, вместо этого сообщение запускает новый поток.
REPLY_MESSAGE_OR_FAIL Создает сообщение как ответ на поток, указанный thread ID или thread_key . Если используется новый thread_key , создается новый поток. Если создать сообщение не удалось, вместо этого возвращается ошибка NOT_FOUND .

CreateReactionRequest

Создает реакцию на сообщение.

Поля
parent

string

Необходимый. Сообщение, в котором создается реакция.

Формат: spaces/{space}/messages/{message}

reaction

Reaction

Необходимый. Реакция на создание.

CreateSpaceRequest

Запрос на создание именованного пространства.

Поля
space

Space

Необходимый. Поля displayName и spaceType должны быть заполнены. Поддерживается только SpaceType.SPACE .

Если вы получили сообщение об ошибке ALREADY_EXISTS , попробуйте другое displayName . Возможно, это отображаемое имя уже используется в существующем пространстве в организации Google Workspace.

name пространства назначается на сервере, поэтому все, указанное в этом поле, будет игнорироваться.

request_id

string

Необязательный. Уникальный идентификатор этого запроса. Рекомендуется использовать случайный UUID. Указание существующего идентификатора запроса возвращает пространство, созданное с этим идентификатором, вместо создания нового пространства. Указание существующего идентификатора запроса из того же приложения чата с другим пользователем, прошедшим проверку подлинности, возвращает ошибку.

ПользовательскиеEmoji

Представляет пользовательский эмодзи.

Поля
uid

string

Только вывод. Уникальный ключ для пользовательского ресурса смайлов.

Удалить запрос на членство

Запрос на удаление членства в пространстве.

Поля
name

string

Необходимый. Имя ресурса членства, которое требуется удалить. Приложения чата могут удалять пользователей-людей или их собственные членства. Приложения чата не могут удалять членство других приложений.

При удалении человеческого членства требуется область действия chat.memberships и формат spaces/{space}/members/{member} . Вы можете использовать адрес электронной почты в качестве псевдонима для {member} . Например, spaces/{space}/members/example@gmail.com , где example@gmail.com — это адрес электронной почты пользователя Google Chat.

При удалении членства в приложении требуется область действия chat.memberships.app и формат spaces/{space}/members/app .

Формат: spaces/{space}/members/{member} или spaces/{space}/members/app .

use_admin_access

bool

Если true , метод запускается с использованием прав администратора Google Workspace пользователя.

Вызывающий пользователь должен быть администратором Google Workspace с правом управления чатом и беседами в чат-группах .

Требуется область действия OAuth 2.0 chat.admin.memberships .

Удаление членства в приложении в пространстве не поддерживается с использованием доступа администратора.

Удалить сообщениезапрос

Просьба удалить сообщение.

Поля
name

string

Необходимый. Имя ресурса сообщения.

Формат: spaces/{space}/messages/{message}

Если вы установили собственный идентификатор для своего сообщения, вы можете использовать значение из поля clientAssignedMessageId для {message} . Подробности см. в разделе Назовите сообщение .

force

bool

Если true , при удалении сообщения также удаляются вложенные в него ответы. Если false , если сообщение имеет цепочки ответов, удаление не удастся.

Применяется только при аутентификации пользователя . Не имеет эффекта при аутентификации в приложении чата .

Удалитьреакционрекуест

Удаляет реакцию на сообщение.

Поля
name

string

Необходимый. Название реакции, которую нужно удалить.

Формат: spaces/{space}/messages/{message}/reactions/{reaction}

Удалить спейсрекуест

Запрос на удаление пространства.

Поля
name

string

Необходимый. Имя ресурса пространства, которое требуется удалить.

Формат: spaces/{space}

use_admin_access

bool

Если true , метод запускается с использованием прав администратора Google Workspace пользователя.

Вызывающий пользователь должен быть администратором Google Workspace с правом управления чатом и беседами в чат-группах .

Требуется область действия OAuth 2.0 chat.admin.delete .

Удаление метаданных

Информация об удаленном сообщении. Сообщение удаляется, если установлено delete_time .

Поля
deletion_type

DeletionType

Указывает, кто удалил сообщение.

Тип удаления

Кто удалил сообщение и как оно было удалено.

Перечисления
DELETION_TYPE_UNSPECIFIED Это значение не используется.
CREATOR Пользователь удалил собственное сообщение.
SPACE_OWNER Владелец темы удалил сообщение.
ADMIN Администратор Google Workspace удалил сообщение.
APP_MESSAGE_EXPIRY Приложение чата удалило собственное сообщение по истечении срока его действия.
CREATOR_VIA_APP Приложение чата удалило сообщение от имени пользователя.
SPACE_OWNER_VIA_APP Приложение чата удалило сообщение от имени владельца чат-группы.

Диалог

Обертка вокруг тела карточки диалога.

Поля
body

Card

Только ввод. Тело диалога, отображаемое в модальном режиме. Приложения Google Chat не поддерживают следующие объекты карточек: DateTimePicker , OnChangeAction .

ДиалогДействие

Содержит диалоговое окно и код состояния запроса.

Поля
action_status

ActionStatus

Только ввод. Статус запроса на вызов или отправку диалога . Отображает статус и сообщение пользователям, если это необходимо. Например, в случае ошибки или успеха.

Полевые action Союза. Действие для выполнения. action может быть только одним из следующих:
dialog

Dialog

Только вход. Диалог для запроса.

DRIEDATAREF

Ссылка на данные привязанности к дисков.

Поля
drive_file_id

string

Идентификатор для файла диска. Используйте с приводом API.

DRIVELINKDATA

Данные для ссылок на Google Drive.

Поля
drive_data_ref

DriveDataRef

DriedAtaref , который ссылается на файл Google Drive.

mime_type

string

Тип MIME связанного ресурса Google Drive.

Эмодзи

Эмодзи, который используется в качестве реакции на сообщение.

Поля
Полевой content союза. Содержание эмодзи. content может быть только одним из следующих:
unicode

string

Основные смайлики, представленные строкой Unicode.

custom_emoji

CustomEmoji

Только вывод. Пользовательский смайлик.

Эмодзиреатзамман

Количество людей, которые отреагировали на сообщение с определенным смайликом.

Поля
emoji

Emoji

Эмодзи, связанные с реакциями.

reaction_count

int32

Общее количество реакций с использованием связанных эмодзи.

FindDirectMessAgeRequest

Запрос на получение прямого пространства сообщений на основе пользовательского ресурса.

Поля
name

string

Необходимый. Имя ресурса пользователя, чтобы найти прямое сообщение.

Format: users/{user} , где {user} является либо id для человека из API People, либо id для пользователя в API каталогов. Например, если идентификатор профиля People API составляет 123456789 , вы можете найти прямое сообщение с этим человеком, используя users/123456789 в качестве name . Когда вы аутентифицированы как пользователь , вы можете использовать электронную почту в качестве псевдонима для {user} . Например, users/example@gmail.com , где example@gmail.com - это письмо пользователя Google Chat.

GetAttachmentRequest

Просьба получить вложение.

Поля
name

string

Необходимый. Имя ресурса вложения, в spaces/{space}/messages/{message}/attachments/{attachment} .

GetMembershipRequest

Запрос получить членство в пространстве.

Поля
name

string

Необходимый. Название ресурса членства для извлечения.

Чтобы получить собственное членство в приложении с помощью аутентификации пользователя , вы можете при желании использовать spaces/{space}/members/app .

Формат: spaces/{space}/members/{member} или spaces/{space}/members/app

При аутентификации как пользователь вы можете использовать электронную почту пользователя в качестве псевдонима для {member} . Например, spaces/{space}/members/example@gmail.com , где example@gmail.com - электронное письмо пользователя Google Chat.

use_admin_access

bool

Когда true , метод работает с использованием привилегий администратора Google Respace пользователя.

Пользователь по вызову должен быть администратором Google Workspace с привилегией Manage CHAT и Spaces Trantings .

Требует chat.admin.memberships или chat.admin.memberships.readonly .

Получение членства в приложении в пространстве не поддерживается при использовании доступа к администратору.

GetMessageRequest

Запрос получить сообщение.

Поля
name

string

Необходимый. Имя ресурса сообщения.

Формат: spaces/{space}/messages/{message}

Если вы установили пользовательский идентификатор для вашего сообщения, вы можете использовать значение из поля clientAssignedMessageId для {message} . Для получения подробной информации см. Имя сообщения .

GetSpaceEventRequest

Запросить сообщение о получении космического мероприятия.

Поля
name

string

Необходимый. Название ресурса космического события.

Формат: spaces/{space}/spaceEvents/{spaceEvent}

GetSpacereadStateRequest

Запросить сообщение для API GetSpacereadState.

Поля
name

string

Необходимый. Название ресурса Космического чтения состояния для извлечения.

Поддерживает только получение состояния чтения для звонящего пользователя.

Чтобы обозначить пользователя по вызову, установите одно из следующих:

  • me псевдоним. Например, users/me/spaces/{space}/spaceReadState .

  • Их адрес электронной почты рабочей области. Например, users/user@example.com/spaces/{space}/spaceReadState /spacereadstate.

  • Их идентификатор пользователя. Например, users/123456789/spaces/{space}/spaceReadState .

Формат: users/{user}/spaces/{space}/spacereadstate

GetSpacerequest

Просьба вернуть одно пространство.

Поля
name

string

Необходимый. Имя ресурса пространства, в формах Form spaces/{space} .

Формат: spaces/{space}

use_admin_access

bool

Когда true , метод работает с использованием привилегий администратора Google Respace пользователя.

Пользователь по вызову должен быть администратором Google Workspace с привилегией Manage CHAT и Spaces Trantings .

Требует chat.admin.spaces chat.admin.spaces.readonly

GetThreadReadStateRequest

Запросить сообщение о GetThreadReadStateRequest API.

Поля
name

string

Необходимый. Название ресурса потока считываем состояние для извлечения.

Поддерживает только получение состояния чтения для звонящего пользователя.

Чтобы обозначить пользователя по вызову, установите одно из следующих:

  • me псевдоним. Например, users/me/spaces/{space}/threads/{thread}/threadReadState .

  • Их адрес электронной почты рабочей области. Например, users/user@example.com/spaces/{space}/threads/{thread}/threadReadState space/threads/{ the Readure/threadReadState.

  • Их идентификатор пользователя. Например, users/123456789/spaces/{space}/threads/{thread}/threadReadState .

Формат: users/{user}/spaces/{space}/threads/{thread}/threadReadState

Группа

Группа Google в чате Google.

Поля
name

string

Имя ресурса для группы Google.

Представляет группу в группе облачных идентификаторов API.

Формат: группы/{группа}

ИСТОРИЯ

Государство истории для сообщений и пространств. Определяет, как долго хранятся сообщения и беседы после создания.

Перечисления
HISTORY_STATE_UNSPECIFIED Значение по умолчанию. Не используйте.
HISTORY_OFF История выключена. Сообщения и потоки хранятся в течение 24 часов .
HISTORY_ON История на. Правила удержания хранилища организации указывают, как долго хранятся сообщения и потоки.

Listmembershipsrequest

Запросить сообщение о перечислении членства.

Поля
parent

string

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

Формат: пространства/{пространство}

page_size

int32

Необязательный. Максимальное количество членов для возврата. Сервис может вернуть меньше этого значения.

В случае неопределенности, не более 100 членов возвращаются.

Максимальное значение составляет 1000. Если вы используете значение более 1000, оно автоматически изменяется на 1000.

Отрицательные значения возвращают ошибку INVALID_ARGUMENT .

page_token

string

Необязательный. Токен страницы, полученный от предыдущего вызова для перечисления членов. Предоставьте этот параметр, чтобы получить последующую страницу.

При нанесении на страницу все другие предоставленные параметры должны соответствовать вызову, который предоставил токен страницы. Передача различных значений к другим параметрам может привести к неожиданным результатам.

filter

string

Необязательный. Фильтр запросов.

Вы можете отфильтровать членство с помощью роли ( role ) члена и типа ( member.type ).

Чтобы фильтровать по роли, установить role в ROLE_MEMBER или ROLE_MANAGER .

Чтобы фильтровать по типу, установите member.type на HUMAN или BOT . Предварительный просмотр разработчика: вы также можете отфильтровать для member.type с помощью оператора != .

Чтобы отфильтровать как роли, так и типом, используйте AND оператор. Чтобы фильтровать по роли или типу, используйте OR оператор.

Либо member.type = "HUMAN" или member.type != "BOT" use_admin_access Другие фильтры типа участника будут отклонены.

Например, следующие запросы действительны:

role = "ROLE_MANAGER" OR role = "ROLE_MEMBER"
member.type = "HUMAN" AND role = "ROLE_MANAGER"

member.type != "BOT"

Следующие запросы недействительны:

member.type = "HUMAN" AND member.type = "BOT"
role = "ROLE_MANAGER" AND role = "ROLE_MEMBER"

Неверные запросы отклоняются сервером с ошибкой INVALID_ARGUMENT .

show_groups

bool

Необязательный. Когда true также возвращает членство, связанное с Google Group , в дополнение к другим типам членства. Если установлен filter , членство Google Group , которое не соответствует критериям фильтра, не возвращаются.

show_invited

bool

Необязательный. Когда true , также возвращает членство, связанное с invited членами, в дополнение к другим типам членства. Если устанавливается фильтр, invited членства, которые не соответствуют критериям фильтра, не возвращаются.

В настоящее время требуется аутентификация пользователя .

use_admin_access

bool

Когда true , метод работает с использованием привилегий администратора Google Respace пользователя.

Пользователь по вызову должен быть администратором Google Workspace с привилегией Manage CHAT и Spaces Trantings .

Требует либо chat.admin.memberships.readonly chat.admin.memberships

Перечисление участников приложения в пространстве не поддерживается при использовании доступа к администратору.

Listmembershipsresponse

Ответ на членство в списке пространства.

Поля
memberships[]

Membership

Неупомянутый список. Список членов на запрошенной (или первой) странице.

next_page_token

string

Токен, который вы можете отправить в качестве pageToken , чтобы получить следующую страницу результатов. Если пустые, нет последующих страниц.

ListMessagesRequest

Перечисляет сообщения в указанном пространстве, что пользователь является членом.

Поля
parent

string

Необходимый. Имя ресурса пространства для перечисления сообщений.

Формат: spaces/{space}

page_size

int32

Максимальное количество сообщений возвращалось. Служба может вернуть меньше сообщений, чем это значение.

Если не указано, не более 25 возвращаются.

Максимальное значение составляет 1000. Если вы используете значение более 1000, оно автоматически изменяется на 1000.

Отрицательные значения возвращают ошибку INVALID_ARGUMENT .

page_token

string

Необязательно, если возобновить из предыдущего запроса.

Токен страницы, полученный из предыдущего вызова сообщений списка. Предоставьте этот параметр, чтобы получить последующую страницу.

При нанесении на страницу все другие предоставленные параметры должны соответствовать вызову, который предоставил токен страницы. Передача различных значений к другим параметрам может привести к неожиданным результатам.

filter

string

Фильтр запросов.

Вы можете отфильтровать сообщения по дате ( create_time ) и поток ( thread.name ).

Чтобы отфильтровать сообщения до даты, которую они были созданы, укажите The create_time с временной меткой в ​​формате RFC-3339 и двойных кавычках. Например, "2023-04-21T11:30:00-04:00" . Вы можете использовать больше, чем оператор > для перечисления сообщений, которые были созданы после метки времени, или меньше, чем оператор < для перечисления сообщений, которые были созданы до метки времени. Чтобы отфильтровать сообщения в интервал времени, используйте AND оператор между двумя временными метками.

Чтобы отфильтровать по потоку, укажите thread.name , отформатированный как spaces/{space}/threads/{thread} . Вы можете указать только один thread.name за запрос.

Чтобы фильтровать по потоке и дате, используйте AND оператор в своем запросе.

Например, следующие запросы действительны:

create_time > "2012-04-21T11:30:00-04:00"

create_time > "2012-04-21T11:30:00-04:00" AND
  thread.name = spaces/AAAAAAAAAAA/threads/123

create_time > "2012-04-21T11:30:00+00:00" AND

create_time < "2013-01-01T00:00:00+00:00" AND
  thread.name = spaces/AAAAAAAAAAA/threads/123

thread.name = spaces/AAAAAAAAAAA/threads/123

Неверные запросы отклоняются сервером с ошибкой INVALID_ARGUMENT .

order_by

string

Необязательно, если возобновить из предыдущего запроса.

Как упорядочен список сообщений. Укажите значение по заказу с помощью операции заказа. Допустимые значения операции заказа следующие:

  • ASC для восхождения.

  • DESC для спуска.

Порядок по умолчанию - create_time ASC .

show_deleted

bool

Должны ли включать удаленные сообщения. Удаленные сообщения включают удаленное время и метаданные об их удалении, но содержание сообщений недоступно.

ListMessagesResponse

Ответ Сообщение для перечисления сообщений.

Поля
messages[]

Message

Список сообщений.

next_page_token

string

Вы можете отправить токен в качестве pageToken , чтобы получить следующую страницу результатов. Если пустые, нет последующих страниц.

ListreactionSrequest

Перечисляет реакцию на сообщение.

Поля
parent

string

Необходимый. Пользователи сообщений отреагировали на.

Формат: spaces/{space}/messages/{message}

page_size

int32

Необязательный. Максимальное количество реакций возвращается. Служба может вернуть меньше реакций, чем это значение. В случае неопределенности значение по умолчанию составляет 25. Максимальное значение составляет 200; Значения выше 200 изменяются на 200.

page_token

string

Необязательный. (Если возобновить из предыдущего запроса.)

Токен страницы, полученный из предыдущего вызова реакций списка. Предоставьте это, чтобы получить последующую страницу.

При страничном значении фильтра должно соответствовать вызову, который предоставил токен страницы. Прохождение другого значения может привести к неожиданным результатам.

filter

string

Необязательный. Фильтр запросов.

Вы можете отфильтровать реакции с помощью Emoji (либо emoji.unicode , либо emoji.custom_emoji.uid ) и user ( user.name ).

Чтобы отфильтровать реакции для нескольких смайликов или пользователей, присоединяйтесь к аналогичным полям с оператором OR оператором, такими как emoji.unicode = "🙂" OR emoji.unicode = "👍" и user.name = "users/AAAAAA" OR user.name = "users/BBBBBB" .

Чтобы отфильтровать реакции с помощью Emoji и пользователя, используйте AND оператор, такой как emoji.unicode = "🙂" AND user.name = "users/AAAAAA" .

Если ваш запрос использует AND и или OR , сгруппируйте их с скобками.

Например, следующие запросы действительны:

user.name = "users/{user}"
emoji.unicode = "🙂"
emoji.custom_emoji.uid = "{uid}"
emoji.unicode = "🙂" OR emoji.unicode = "👍"
emoji.unicode = "🙂" OR emoji.custom_emoji.uid = "{uid}"
emoji.unicode = "🙂" AND user.name = "users/{user}"
(emoji.unicode = "🙂" OR emoji.custom_emoji.uid = "{uid}")
AND user.name = "users/{user}"

Следующие запросы недействительны:

emoji.unicode = "🙂" AND emoji.unicode = "👍"
emoji.unicode = "🙂" AND emoji.custom_emoji.uid = "{uid}"
emoji.unicode = "🙂" OR user.name = "users/{user}"
emoji.unicode = "🙂" OR emoji.custom_emoji.uid = "{uid}" OR
user.name = "users/{user}"
emoji.unicode = "🙂" OR emoji.custom_emoji.uid = "{uid}"
AND user.name = "users/{user}"

Неверные запросы отклоняются сервером с ошибкой INVALID_ARGUMENT .

ListreactionSresponse

Ответ на запрос на реакцию списка.

Поля
reactions[]

Reaction

Список реакций на запрошенной (или первой) странице.

next_page_token

string

Продолжение токена, чтобы получить следующую страницу результатов. Это пусто для последней страницы результатов.

Listspaceeventsrequest

Запросить сообщение о перечислении космических событий.

Поля
parent

string

Необходимый. Название ресурса в чате Google , где произошли события.

Формат: spaces/{space} .

page_size

int32

Необязательный. Максимальное количество космических событий возвращалось. Сервис может вернуть меньше этого значения.

Отрицательные значения возвращают ошибку INVALID_ARGUMENT .

page_token

string

Токен страницы, полученный из предыдущего звонка космических событий списка. Предоставьте это, чтобы получить последующую страницу.

При нанесении на страницу все остальные параметры, предоставленные для перечисления пространственных событий, должны соответствовать вызову, который предоставил токен страницы. Передача различных значений к другим параметрам может привести к неожиданным результатам.

filter

string

Необходимый. Фильтр запросов.

Вы должны указать хотя бы один тип события ( event_type ), используя оператор HASE : Чтобы отфильтровать по нескольким типам событий, используйте оператор OR . Опустите типы событий партии в вашем фильтре. Запрос автоматически возвращает любые связанные пакетные события. Например, если вы фильтровали новые реакции ( google.workspace.chat.reaction.v1.created ), сервер также возвращает партии новых событий реакций ( google.workspace.chat.reaction.v1.batchCreated ). Список поддерживаемых типов событий см. В справочной документации SpaceEvents .

При желании вы также можете отфильтровать по времени начала ( start_time ) и времени окончания ( end_time ):

  • start_time : Exclusive TimeStamp, с которой можно начать список космических событий. Вы можете перечислить события, которые произошли до 28 дней назад. Если не указано, перечисляет космические события за последние 28 дней.
  • end_time : включающая временная метка до тех пор, пока не будут перечислены космические события. В случае неопределенности перечислены события до времени запроса.

Чтобы указать время начала или окончания, используйте оператор Equals = Format в RFC-3339 . Чтобы отфильтровать как на start_time , так и end_time , используйте AND оператор.

Например, следующие запросы действительны:

start_time="2023-08-23T19:20:33+00:00" AND
end_time="2023-08-23T19:21:54+00:00"
start_time="2023-08-23T19:20:33+00:00" AND
(event_types:"google.workspace.chat.space.v1.updated" OR
event_types:"google.workspace.chat.message.v1.created")

Следующие запросы недействительны:

start_time="2023-08-23T19:20:33+00:00" OR
end_time="2023-08-23T19:21:54+00:00"
event_types:"google.workspace.chat.space.v1.updated" AND
event_types:"google.workspace.chat.message.v1.created"

Неверные запросы отклоняются сервером с ошибкой INVALID_ARGUMENT .

ListSpaceEventsResponse

Ответ Сообщение для перечисления космических событий.

Поля
space_events[]

SpaceEvent

Результаты возвращаются в хронологическом порядке (сначала самое старое событие).

next_page_token

string

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

ListspacesRequest

Запрос на перечисление пространств, которым является абонент.

Поля
page_size

int32

Необязательный. Максимальное количество пробелов для возврата. Сервис может вернуть меньше этого значения.

В случае неопределенности, не более 100 мест возвращаются.

Максимальное значение составляет 1000. Если вы используете значение более 1000, оно автоматически изменяется на 1000.

Отрицательные значения возвращают ошибку INVALID_ARGUMENT .

page_token

string

Необязательный. Токен страницы, полученный из предыдущего звонка в списках. Предоставьте этот параметр, чтобы получить последующую страницу.

При страничном значении фильтра должно соответствовать вызову, который предоставил токен страницы. Прохождение другого значения может привести к неожиданным результатам.

filter

string

Необязательный. Фильтр запросов.

Вы можете отфильтровать пространства по типу пространства ( space_type ).

Чтобы отфильтровать по типу пространства, вы должны указать допустимое значение Enum, такое как SPACE или GROUP_CHAT ( space_type не может быть SPACE_TYPE_UNSPECIFIED ). Чтобы запросить несколько типов пространства, используйте оператор OR .

Например, следующие запросы действительны:

space_type = "SPACE"
spaceType = "GROUP_CHAT" OR spaceType = "DIRECT_MESSAGE"

Неверные запросы отклоняются сервером с ошибкой INVALID_ARGUMENT .

Listspacesresponse

Ответ на запрос списков.

Поля
spaces[]

Space

Список пробелов на запрошенной (или первой) странице.

next_page_token

string

Вы можете отправить токен в качестве pageToken , чтобы получить следующую страницу результатов. Если пустые, нет последующих страниц.

Matchedurl

Соответствующий URL в сообщении в чате. Приложения чата могут предварительно просмотреть соответствующие URL -адреса. Для получения дополнительной информации см. Предварительные ссылки .

Поля
url

string

Только вывод. URL, который был сопоставлен.

Членство

Представляет собой отношение членства в чате Google, например, приглашается ли пользователь или приложение чата, часть или отсутствует в пространстве.

Поля
name

string

Имя ресурса членства, назначенное сервером.

Формат: spaces/{space}/members/{member}

state

MembershipState

Только вывод. Состояние членства.

role

MembershipRole

Необязательный. Роль пользователя в пространстве чата, которая определяет их разрешенные действия в пространстве.

Это поле можно использовать только в качестве ввода в UpdateMembership .

create_time

Timestamp

Необязательный. Неизменен. Время создания членства, например, когда член присоединился или был приглашен присоединиться к пространству. Это поле выводится только, за исключением случаев, когда используется для импорта исторического членства в местах импорта.

delete_time

Timestamp

Необязательный. Неизменен. Время удаления членства, например, когда член ушел или был удален из пространства. Это поле выводится только, за исключением случаев, когда используется для импорта исторического членства в местах импорта.

Union Field memberType . Участник связан с этим членством. Другие типы участников могут быть поддержаны в будущем. memberType может быть только одним из следующих:
member

User

Пользователь или приложение Google Chat, которому соответствует членство. Если ваше приложение в чате аутентифицируется как пользователь , вывод популяет name пользователя и type .

group_member

Group

Группа Google членство соответствует.

Членство

Представляет разрешенные действия пользователя в пространстве чата. Больше значений Enum может быть добавлено в будущем.

Перечисления
MEMBERSHIP_ROLE_UNSPECIFIED Значение по умолчанию. Для users : они не являются членом пространства, но могут быть приглашены. Для Google Groups : им всегда присваивается эта роль (другие значения перечисления могут использоваться в будущем).
ROLE_MEMBER Член пространства. У пользователя есть основные разрешения, такие как отправка сообщений в пространство. В 1: 1 и безымянных групповых разговорах у каждого есть эта роль.
ROLE_MANAGER Космический менеджер. У пользователя есть все основные разрешения плюс административные разрешения, которые позволяют им управлять пространством, например, добавление или удаление участников. Поддерживается только в SpaceType.SPACE .

Членство

Определяет отношения участника с пространством. Другие государства членства могут быть поддержаны в будущем.

Перечисления
MEMBERSHIP_STATE_UNSPECIFIED Значение по умолчанию. Не используйте.
JOINED Пользователь добавляется в пространство и может участвовать в пространстве.
INVITED Пользователь предлагается присоединиться к пространству, но не присоединился к нему.
NOT_A_MEMBER Пользователь не принадлежит к пространству и не имеет ожидающего приглашения присоединиться к пространству.

Членство BATCHCREATEDEVENTDATA

Полезная нагрузка на событие для нескольких новых членов.

Тип события: google.workspace.chat.membership.v1.batchCreated

Поля
memberships[]

MembershipCreatedEventData

Список новых членов.

Членство BatchdeleteDeventData

Полезная нагрузка на событие для нескольких удаленных членов.

Тип события: google.workspace.chat.membership.v1.batchDeleted

Поля
memberships[]

MembershipDeletedEventData

Список удаленных членов.

Членство BBATCHUPDATEDEVENTDATA

Полезная нагрузка на событие для нескольких обновленных членов.

Тип события: google.workspace.chat.membership.v1.batchUpdated

Поля
memberships[]

MembershipUpdatedEventData

Список обновленных членов.

Членство CREATEDEVENTDATA

Полезная нагрузка на событие для нового членства.

Тип события: google.workspace.chat.membership.v1.created .

Поля
membership

Membership

Новое членство.

Членатделевендата

Полезная нагрузка на мероприятие для удаленного членства.

Тип события: google.workspace.chat.membership.v1.deleted

Поля
membership

Membership

Удаленное членство. Только name и state поля заполнены.

Член и поступил

Полезная нагрузка на событие для обновленного членства.

Тип события: google.workspace.chat.membership.v1.updated

Поля
membership

Membership

Обновленное членство.

Сообщение

Сообщение в пространстве чата Google.

Поля
name

string

Имя ресурса сообщения.

Формат: spaces/{space}/messages/{message}

Где {space} -это идентификатор пространства, в котором публикуется сообщение, а {message} -это идентификатор, посвященный системе для сообщения. Например, spaces/AAAAAAAAAAA/messages/BBBBBBBBBBB.BBBBBBBBBBB .

Если вы установите пользовательский идентификатор при создании сообщения, вы можете использовать этот идентификатор для указания сообщения в запросе, заменив {message} на поле clientAssignedMessageId . Например, spaces/AAAAAAAAAAA/messages/client-custom-name . Для получения подробной информации см. Имя сообщения .

sender

User

Только вывод. Пользователь, который создал сообщение. Если ваше приложение в чате аутентифицируется как пользователь , вывод популяет name пользователя и type .

create_time

Timestamp

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

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

last_update_time

Timestamp

Только вывод. Время, в которое сообщение было в последний раз отредактировано пользователем. Если сообщение никогда не было отредактировано, это поле пустое.

delete_time

Timestamp

Только вывод. Время, в которое сообщение было удалено в чате Google. Если сообщение никогда не удалено, это поле пустое.

text

string

Простые текстовые тела сообщения. Первая ссылка на изображение, видео или веб -страницу генерирует чип предварительного просмотра . Вы также можете принять пользователя Google Chat или всех в пространстве.

Чтобы узнать о создании текстовых сообщений, см. Отправить текстовое сообщение .

formatted_text

string

Только вывод. Содержит text сообщения с разметками, добавленными для передачи форматирования. Это поле может не захватить все форматирование, видимое в пользовательском интерфейсе, но включает в себя следующее:

  • Синтаксис разметки для жирного шрифта, курсивного, ударного, монопрояжника, блока монопроизводства и списка с маркировкой.

  • Пользователь упоминает, используя формат <users/{user}> .

  • Пользовательские гиперссылки с использованием формата <{url}|{rendered_text}> где первая строка - URL, а вторая - текст рендеринга - например, <http://example.com|custom text> .

  • Пользовательский эмодзи с использованием формата :{emoji_name}: - например,: :smile: . Это не относится к Emoji Unicode, например U+1F600 для ухмыляющегося лица.

Для получения дополнительной информации см. Просмотр форматирования текста, отправленного в сообщении

cards[]
(deprecated)

Card

Устроенный: используйте cards_v2 вместо этого.

Богатые, отформатированные и интерактивные карты, которые вы можете использовать для отображения элементов пользовательского интерфейса, таких как: форматированные тексты, кнопки и кликабельные изображения. Карты обычно отображаются ниже простого тела сообщения. cards и cards_v2 могут иметь максимальный размер 32 КБ.

cards_v2[]

CardWithId

Множество карт .

Только приложения чата могут создавать карты. Если ваше приложение в чате аутентифицируется как пользователь , сообщения не могут содержать карты.

Чтобы узнать о картах и ​​как их создать, см. Отправить сообщения карты .

Создавайте и просматривайте карты с помощью Card Builder.

Откройте конструктор карточек

annotations[]

Annotation

Только вывод. Аннотации, связанные с text в этом сообщении.

thread

Thread

Поток, к которому принадлежит сообщение. Например, используйте, см. Запуск или ответьте на поток сообщения .

space

Space

Если ваше приложение в чате аутентифицируется как пользователь , вывод населяет name пространства .

fallback_text

string

Простой текстовое описание карт сообщения, используемое, когда фактические карты не могут быть отображены, например, мобильные уведомления.

action_response

ActionResponse

Только вход. Параметры, которые приложение чата может использовать для настройки того, как публикуется его ответ.

argument_text

string

Только вывод. Простые текстовые тела сообщения со всеми приложениями для чата разбросаны.

slash_command

SlashCommand

Только вывод. Информация о команде SLASH, если применимо.

attachment[]

Attachment

Пользовательская загруженная вложение.

matched_url

MatchedUrl

Только вывод. URL в spaces.messages.text , который соответствует шаблону предварительного просмотра ссылки. Для получения дополнительной информации см. Предварительные ссылки .

thread_reply

bool

Только вывод. Когда true , сообщение является ответом в потоке ответа. Когда false , сообщение видно в разговоре верхнего уровня пространства как первое сообщение потока или сообщение без ответов.

Если пространство не поддерживает ответ в потоках, это поле всегда false .

client_assigned_message_id

string

Необязательный. Пользовательский идентификатор для сообщения. Вы можете использовать поле для определения сообщения или для получения, удаления или обновления сообщения. Чтобы установить пользовательский идентификатор, укажите поле messageId при создании сообщения. Для получения подробной информации см. Имя сообщения .

emoji_reaction_summaries[]

EmojiReactionSummary

Только вывод. Список резюме реакции эмодзи на сообщении.

private_message_viewer

User

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

Только приложения чата могут отправлять личные сообщения. Если ваше приложение для чата является аутентификацией как пользователь для отправки сообщения, сообщение не может быть частным и должно опустить это поле.

Для получения подробной информации см. Отправить частные сообщения для пользователей Google Chat .

deletion_metadata

DeletionMetadata

Только вывод. Информация о удаленном сообщении. Сообщение удаляется при установке delete_time .

quoted_message_metadata

QuotedMessageMetadata

Только вывод. Информация о сообщении, которое цитируется пользователем Google Chat в пространстве. Пользователи Google Chat могут процитировать сообщение, чтобы ответить на него.

attached_gifs[]

AttachedGif

Только вывод. GIF -изображения, которые прикреплены к сообщению.

accessory_widgets[]

AccessoryWidget

Один или несколько интерактивных виджетов, которые появляются в нижней части сообщения. Вы можете добавить вспомогательные виджеты в сообщения, которые содержат текст, карты или текст и карты. Не поддерживается для сообщений, которые содержат диалоги. Для получения подробной информации см. Добавьте интерактивные виджеты внизу сообщения .

Создание сообщения с помощью аксессуаров требует аутентификации приложений .

MessageBatchCreatedEventData

Полезная нагрузка на событие для нескольких новых сообщений.

Тип события: google.workspace.chat.message.v1.batchCreated

Поля
messages[]

MessageCreatedEventData

Список новых сообщений.

MessageBatchDeleteDeventData

Полезная нагрузка на несколько удаленных сообщений.

Тип события: google.workspace.chat.message.v1.batchDeleted

Поля
messages[]

MessageDeletedEventData

Список удаленных сообщений.

MessageBatchUpdatedEventData

Полезная нагрузка на событие для нескольких обновленных сообщений.

Тип события: google.workspace.chat.message.v1.batchUpdated

Поля
messages[]

MessageUpdatedEventData

Список обновленных сообщений.

MessageCreatedEventdata

Полезная нагрузка на событие для нового сообщения.

Тип события: google.workspace.chat.message.v1.created

Поля
message

Message

Новое сообщение.

MessageDetedEventData

Полезная нагрузка на событие для удаленного сообщения.

Тип события: google.workspace.chat.message.v1.deleted

Поля
message

Message

Удаленное сообщение. Только поля name , createTime , deleteTime и deletionMetadata заполняются.

MessageUpdatedEventData

Полезная нагрузка на событие для обновленного сообщения.

Тип события: google.workspace.chat.message.v1.updated

Поля
message

Message

Обновленное сообщение.

Quytedmessagemetadata

Информация о цитируемом сообщении.

Поля
name

string

Только вывод. Имя ресурса цитируемого сообщения.

Формат: spaces/{space}/messages/{message}

last_update_time

Timestamp

Только вывод. Неэппаратная метка, когда цитируемое сообщение было создано или когда цитируемое сообщение была в последний раз обновлена.

Реакция

Реакция на сообщение.

Поля
name

string

Название ресурса реакции.

Формат: spaces/{space}/messages/{message}/reactions/{reaction}

user

User

Только вывод. Пользователь, который создал реакцию.

emoji

Emoji

Эмодзи, используемые в реакции.

Реакция BatchCreatedEventData

Полезная нагрузка на несколько новых реакций.

Тип события: google.workspace.chat.reaction.v1.batchCreated

Поля
reactions[]

ReactionCreatedEventData

Список новых реакций.

Реакция BatchDeleteDeventData

Полезная нагрузка на несколько удаленных реакций.

Тип события: google.workspace.chat.reaction.v1.batchDeleted

Поля
reactions[]

ReactionDeletedEventData

Список удаленных реакций.

Реакция CREATEDEVENTDATA

Полезная нагрузка на событие для новой реакции.

Тип события: google.workspace.chat.reaction.v1.created

Поля
reaction

Reaction

Новая реакция.

Реакция DELETEDEVENTDATA

Полезная нагрузка на удаленную реакцию.

Тип: google.workspace.chat.reaction.v1.deleted

Поля
reaction

Reaction

Удаленная реакция.

Richlinkmetadata

Богатая ссылка на ресурс.

Поля
uri

string

URI этой ссылки.

data поля объединения. Данные для связанного ресурса. data могут быть только одним из следующих:

Richlinktype

Богатый тип ссылки. В будущем может быть добавлено больше типов.

Перечисления
DRIVE_FILE Гугл диск, богатый тип ссылки.
CHAT_SPACE Тип ссылки на просмотр чата. Например, Space Smart Chip.

SearchspacesRequest

Запрос на поиск списка мест на основе запроса.

Поля
use_admin_access

bool

Когда true , метод работает с использованием привилегий администратора Google Respace пользователя.

Пользователь по вызову должен быть администратором Google Workspace с привилегией Manage CHAT и Spaces Trantings .

Требует либо chat.admin.spaces.readonly chat.admin.spaces

Этот метод в настоящее время поддерживает только доступ администратора, поэтому для этого поля принимается только true .

page_size

int32

Максимальное количество пробелов для возврата. Служба может вернуть меньше этого значения.

В случае неопределенности, не более 100 мест возвращаются.

Максимальное значение составляет 1000. Если вы используете значение более 1000, оно автоматически изменяется на 1000.

page_token

string

Токен, полученный от предыдущего вызова поискового пространства. Предоставьте этот параметр, чтобы получить последующую страницу.

При нанесении на страницу все другие предоставленные параметры должны соответствовать вызову, который предоставил токен страницы. Передача различных значений к другим параметрам может привести к неожиданным результатам.

query

string

Необходимый. Поисковый запрос.

Вы можете искать, используя следующие параметры:

  • create_time
  • customer
  • display_name
  • external_user_allowed
  • last_active_time
  • space_history_state
  • space_type

create_time и last_active_time Принимайте временную метку в формате RFC-3339 , а поддерживаемые операторы сравнения: = , < , > , <= , >= .

customer требуется и используется для указания, из какого клиента приносить места. customers/my_customer - единственная поддерживаемая ценность.

display_name только принимает оператор HAS ( : . Текст, который можно соответствовать, первым токенам, и каждый токен является сопоставлением префиксом, чувствительным к случаям и независимо в качестве подстроения в любом месте в пространстве display_name . Например, Fun Eve Match Match Fun event или The evening was fun , но не notFun event или even .

external_user_allowed принимает либо true , либо false .

space_history_state принимает только значения из поля historyState space ресурса.

space_type требуется, и единственное допустимое значение - SPACE .

В разных областях поддерживаются только AND . Допустимый пример - space_type = "SPACE" AND display_name:"Hello" , а неверный пример - space_type = "SPACE" OR display_name:"Hello" .

Среди той же поля space_type не поддерживает AND или OR операторы. display_name , 'space_history_state' и 'external_user_allowed' только поддержка OR операторы. last_active_time и create_time поддерживают как AND и OR операторы. AND может использоваться только для представления интервала, такого как last_active_time < "2022-01-01T00:00:00+00:00" AND last_active_time > "2023-01-01T00:00:00+00:00" .

Следующий пример запросов действительны:

customer = "customers/my_customer" AND space_type = "SPACE"

customer = "customers/my_customer" AND space_type = "SPACE" AND
display_name:"Hello World"

customer = "customers/my_customer" AND space_type = "SPACE" AND
(last_active_time < "2020-01-01T00:00:00+00:00" OR last_active_time >
"2022-01-01T00:00:00+00:00")

customer = "customers/my_customer" AND space_type = "SPACE" AND
(display_name:"Hello World" OR display_name:"Fun event") AND
(last_active_time > "2020-01-01T00:00:00+00:00" AND last_active_time <
"2022-01-01T00:00:00+00:00")

customer = "customers/my_customer" AND space_type = "SPACE" AND
(create_time > "2019-01-01T00:00:00+00:00" AND create_time <
"2020-01-01T00:00:00+00:00") AND (external_user_allowed = "true") AND
(space_history_state = "HISTORY_ON" OR space_history_state = "HISTORY_OFF")
order_by

string

Необязательный. Как упорядочен список пространств.

Поддерживаемые атрибуты по заказу

  • membership_count.joined_direct_human_user_count - обозначает количество людей, которые непосредственно присоединились к пространству.
  • last_active_time - обозначает время, когда последний подходящий элемент добавляется в любую тему этого пространства.
  • create_time - обозначает время создания пространства.

Допустимые значения операции на заказ:

  • ASC для восхождения. Значение по умолчанию.

  • DESC для спуска.

Поддерживаемый синтаксис:

  • membership_count.joined_direct_human_user_count DESC
  • membership_count.joined_direct_human_user_count ASC
  • last_active_time DESC
  • last_active_time ASC
  • create_time DESC
  • create_time ASC

SearchSpacesResponse

Ответ со списком пробелов, соответствующих запросу поискового пространства.

Поля
spaces[]

Space

Страница запрошенных пространств.

next_page_token

string

Токен, который можно использовать для получения следующей страницы. Если это поле пустое, нет последующих страниц.

total_size

int32

Общее количество пробелов, которые соответствуют запросу на всех страницах. Если результат составляет более 10000 мест, это значение является оценкой.

SetupSpacerequest

Запрос на создание места и добавить к нему указанных пользователей.

Поля
space

Space

Необходимый. Требуется поле Space.spaceType .

Чтобы создать пространство, установите Space.spaceType в SPACE и установите Space.displayName . Если вы получаете сообщение об ошибке ALREADY_EXISTS при настройке пространства, попробуйте другое displayName . Существующее пространство в организации Google Workspace может уже использовать это имя отображения.

Чтобы создать групповой чат, установите Space.spaceType на GROUP_CHAT . Не устанавливайте Space.displayName .

Чтобы создать разговор между людьми 1: 1, установите пространство false Space.spaceType to DIRECT_MESSAGE и установите Space.singleUserBotDm . Не устанавливайте Space.displayName или Space.spaceDetails .

Чтобы создать разговор 1: 1 между человеком и приложением для призывного чата, установите Space.spaceType на DIRECT_MESSAGE и Space.singleUserBotDm true . Не устанавливайте Space.displayName или Space.spaceDetails .

Если пространство DIRECT_MESSAGE уже существует, это пространство возвращается вместо создания нового пространства.

request_id

string

Необязательный. Уникальный идентификатор для этого запроса. Рекомендуется случайный UUID. Указание существующего идентификатора запроса возвращает пространство, созданное с помощью этого идентификатора вместо создания нового пространства. Указание существующего идентификатора запроса из одного и того же приложения чата с другим аутентифицированным пользователем возвращает ошибку.

memberships[]

Membership

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

Набор в настоящее время допускает до 20 членов (в дополнение к вызывающему абоненту).

Для человеческого членства в поле Membership.member должно содержать user с заполненным name (формат: users/{user} ) и type установленного на User.Type.HUMAN . Вы можете добавить людей только при настройке пространства (добавление приложений чата поддерживается только для прямой настройки сообщений с помощью приложения Calling). Вы также можете добавить участников, используя электронную почту пользователя в качестве псевдонима для {пользователя}. Например, user.name может быть users/example@gmail.com . Чтобы пригласить пользователей Gmail или пользователей из внешних доменов Google Workspace, электронная почта пользователя должна использоваться для {user} .

Для членства в группе Google в поле Membership.group_member должно содержать group с заполненным name (Format groups/{group} ). Вы можете добавить только группы Google только при установке Space.spaceType в SPACE .

Необязательно при установке Space.spaceType в SPACE .

Требуется при установке Space.spaceType to GROUP_CHAT , а также как минимум с двумя членами.

Требуется при установке Space.spaceType в DIRECT_MESSAGE с человеческим пользователем, а также ровно одно членство.

Должен быть пустым при создании разговора 1: 1 между человеком и приложением призывного чата (при установке Space.spaceType для DIRECT_MESSAGE и Space.singleUserBotDm true ).

Слэшкомманд

Команда Slash в чате Google.

Поля
command_id

int64

Идентификатор команды SLASH призван.

Slashcommammametadata

Метаданные аннотации для команд SLASH (/).

Поля
bot

User

Приложение чата, чья команда была вызвана.

type

Type

Тип команды SLASH.

command_name

string

Имя вызываемой команды Slash.

command_id

int64

Идентификатор команды вызываемой команды SLASH.

triggers_dialog

bool

Указывает, является ли команда SLASH для диалога.

Тип

Перечисления
TYPE_UNSPECIFIED Значение по умолчанию для перечисления. Не используйте.
ADD Add Chat app to space.
INVOKE Invoke slash command in space.

Космос

A space in Google Chat. Spaces are conversations between two or more users or 1:1 messages between a user and a Chat app.

Поля
name

string

Resource name of the space.

Format: spaces/{space}

type
(deprecated)

Type

Только вывод. Deprecated: Use space_type instead. The type of a space.

space_type

SpaceType

The type of space. Required when creating a space or updating the space type of a space. Output only for other usage.

single_user_bot_dm

bool

Необязательный. Whether the space is a DM between a Chat app and a single human.

threaded
(deprecated)

bool

Только вывод. Deprecated: Use spaceThreadingState instead. Whether messages are threaded in this space.

display_name

string

The space's display name. Required when creating a space . If you receive the error message ALREADY_EXISTS when creating a space or updating the displayName , try a different displayName . An existing space within the Google Workspace organization might already use this display name.

For direct messages, this field might be empty.

Supports up to 128 characters.

external_user_allowed

bool

Immutable. Whether this space permits any Google Chat user as a member. Input when creating a space in a Google Workspace organization. Omit this field when creating spaces in the following conditions:

  • The authenticated user uses a consumer account (unmanaged user account). By default, a space created by a consumer account permits any Google Chat user.

For existing spaces, this field is output only.

space_threading_state

SpaceThreadingState

Только вывод. The threading state in the Chat space.

space_details

SpaceDetails

Details about the space including description and rules.

space_history_state

HistoryState

The message history state for messages and threads in this space.

import_mode

bool

Необязательный. Whether this space is created in Import Mode as part of a data migration into Google Workspace. While spaces are being imported, they aren't visible to users until the import is complete.

create_time

Timestamp

Необязательный. Immutable. For spaces created in Chat, the time the space was created. This field is output only, except when used in import mode spaces.

For import mode spaces, set this field to the historical timestamp at which the space was created in the source in order to preserve the original creation time.

Only populated in the output when spaceType is GROUP_CHAT or SPACE .

last_active_time

Timestamp

Только вывод. Timestamp of the last message in the space.

admin_installed

bool

Только вывод. For direct message (DM) spaces with a Chat app, whether the space was created by a Google Workspace administrator. Administrators can install and set up a direct message with a Chat app on behalf of users in their organization.

To support admin install, your Chat app must feature direct messaging.

membership_count

MembershipCount

Только вывод. The count of joined memberships grouped by member type. Populated when the space_type is SPACE , DIRECT_MESSAGE or GROUP_CHAT .

access_settings

AccessSettings

Необязательный. Specifies the access setting of the space. Only populated when the space_type is SPACE .

space_uri

string

Только вывод. The URI for a user to access the space.

Union field space_permission_settings . Represents the permission settings of a space. Only populated when the space_type is SPACE . space_permission_settings can be only one of the following:
predefined_permission_settings

PredefinedPermissionSettings

Необязательный. Input only. Space permission settings. Input for creating a space, a collaboration space is created if this field is not set. After you create the space, settings are populated in the PermissionSettings field.

permission_settings

PermissionSettings

Необязательный. Exact permission settings which can be set to update the space. Input for updating a space. Otherwise, output only. For space creation, use predefined_permission_settings instead.

AccessSettings

Represents the access setting of the space.

Поля
access_state

AccessState

Только вывод. Indicates the access state of the space.

audience

string

Необязательный. The resource name of the target audience who can discover the space, join the space, and preview the messages in the space. If unset, only users or Google Groups who have been individually invited or added to the space can access it. For details, see Make a space discoverable to a target audience .

Format: audiences/{audience}

To use the default target audience for the Google Workspace organization, set to audiences/default .

AccessState

Represents the access state of the space.

Перечисления
ACCESS_STATE_UNSPECIFIED Access state is unknown or not supported in this API.
PRIVATE Only users or Google Groups that have been individually added or invited by other users or Google Workspace administrators can discover and access the space.
DISCOVERABLE A space manager has granted a target audience access to the space. Users or Google Groups that have been individually added or invited to the space can also discover and access the space. To learn more, see Make a space discoverable to specific users .

MembershipCount

Represents the count of memberships of a space, grouped into categories.

Поля
joined_direct_human_user_count

int32

Count of human users that have directly joined the space, not counting users joined by having membership in a joined group.

joined_group_count

int32

Count of all groups that have directly joined the space.

PermissionSetting

Represents a space permission setting.

Поля
managers_allowed

bool

Whether spaces managers have this permission.

members_allowed

bool

Whether non-manager members have this permission.

PermissionSettings

Permission settings for a named space. To set permission settings when creating a space, specify the PredefinedPermissionSettings field in your request.

Поля
manage_members_and_groups

PermissionSetting

Setting for managing members and groups in a space.

modify_space_details

PermissionSetting

Setting for updating space name, avatar, description and guidelines.

toggle_history

PermissionSetting

Setting for toggling space history on and off.

use_at_mention_all

PermissionSetting

Setting for using @all in a space.

manage_apps

PermissionSetting

Setting for managing apps in a space.

manage_webhooks

PermissionSetting

Setting for managing webhooks in a space.

post_messages

PermissionSetting

Только вывод. Setting for posting messages in a space.

reply_messages

PermissionSetting

Setting for replying to messages in a space.

PredefinedPermissionSettings

The space permission settings that you can specify when creating a named space. More settings might be added in the future. For details about permission settings for named spaces, see Learn about spaces .

Перечисления
PREDEFINED_PERMISSION_SETTINGS_UNSPECIFIED Не указано. Не используйте.
COLLABORATION_SPACE Setting to make the space a collaboration space where all members can post messages.
ANNOUNCEMENT_SPACE Setting to make the space an announcement space where only space managers can post messages.

SpaceDetails

Details about the space including description and rules.

Поля
description

string

Необязательный. A description of the space. For example, describe the space's discussion topic, functional purpose, or participants.

Supports up to 150 characters.

guidelines

string

Необязательный. The space's rules, expectations, and etiquette.

Supports up to 5,000 characters.

SpaceThreadingState

Specifies the type of threading state in the Chat space.

Перечисления
SPACE_THREADING_STATE_UNSPECIFIED Сдержанный.
THREADED_MESSAGES Named spaces that support message threads. When users respond to a message, they can reply in-thread, which keeps their response in the context of the original message.
GROUPED_MESSAGES Named spaces where the conversation is organized by topic. Topics and their replies are grouped together.
UNTHREADED_MESSAGES Direct messages (DMs) between two people and group conversations between 3 or more people.

SpaceType

The type of space. Required when creating or updating a space. Output only for other usage.

Перечисления
SPACE_TYPE_UNSPECIFIED Сдержанный.
SPACE A place where people send messages, share files, and collaborate. A SPACE can include Chat apps.
GROUP_CHAT Group conversations between 3 or more people. A GROUP_CHAT can include Chat apps.
DIRECT_MESSAGE 1:1 messages between two humans or a human and a Chat app.

Тип

Deprecated: Use SpaceType instead.

Перечисления
TYPE_UNSPECIFIED Сдержанный.
ROOM Conversations between two or more humans.
DM 1:1 Direct Message between a human and a Chat app, where all messages are flat. Note that this doesn't include direct messages between two humans.

SpaceBatchUpdatedEventData

Event payload for multiple updates to a space.

Event type: google.workspace.chat.space.v1.batchUpdated

Поля
spaces[]

SpaceUpdatedEventData

A list of updated spaces.

SpaceEvent

An event that represents a change or activity in a Google Chat space. To learn more, see Work with events from Google Chat .

Поля
name

string

Resource name of the space event.

Format: spaces/{space}/spaceEvents/{spaceEvent}

event_time

Timestamp

Time when the event occurred.

event_type

string

Type of space event. Each event type has a batch version, which represents multiple instances of the event type that occur in a short period of time. For spaceEvents.list() requests, omit batch event types in your query filter. By default, the server returns both event type and its batch version.

Supported event types for messages :

  • New message: google.workspace.chat.message.v1.created
  • Updated message: google.workspace.chat.message.v1.updated
  • Deleted message: google.workspace.chat.message.v1.deleted
  • Multiple new messages: google.workspace.chat.message.v1.batchCreated
  • Multiple updated messages: google.workspace.chat.message.v1.batchUpdated
  • Multiple deleted messages: google.workspace.chat.message.v1.batchDeleted

Supported event types for memberships :

  • New membership: google.workspace.chat.membership.v1.created
  • Updated membership: google.workspace.chat.membership.v1.updated
  • Deleted membership: google.workspace.chat.membership.v1.deleted
  • Multiple new memberships: google.workspace.chat.membership.v1.batchCreated
  • Multiple updated memberships: google.workspace.chat.membership.v1.batchUpdated
  • Multiple deleted memberships: google.workspace.chat.membership.v1.batchDeleted

Supported event types for reactions :

  • New reaction: google.workspace.chat.reaction.v1.created
  • Deleted reaction: google.workspace.chat.reaction.v1.deleted
  • Multiple new reactions: google.workspace.chat.reaction.v1.batchCreated
  • Multiple deleted reactions: google.workspace.chat.reaction.v1.batchDeleted

Supported event types about the space :

  • Updated space: google.workspace.chat.space.v1.updated
  • Multiple space updates: google.workspace.chat.space.v1.batchUpdated

Union field payload .

payload can be only one of the following:

message_created_event_data

MessageCreatedEventData

Event payload for a new message.

Event type: google.workspace.chat.message.v1.created

message_updated_event_data

MessageUpdatedEventData

Event payload for an updated message.

Event type: google.workspace.chat.message.v1.updated

message_deleted_event_data

MessageDeletedEventData

Event payload for a deleted message.

Event type: google.workspace.chat.message.v1.deleted

message_batch_created_event_data

MessageBatchCreatedEventData

Event payload for multiple new messages.

Event type: google.workspace.chat.message.v1.batchCreated

message_batch_updated_event_data

MessageBatchUpdatedEventData

Event payload for multiple updated messages.

Event type: google.workspace.chat.message.v1.batchUpdated

message_batch_deleted_event_data

MessageBatchDeletedEventData

Event payload for multiple deleted messages.

Event type: google.workspace.chat.message.v1.batchDeleted

space_updated_event_data

SpaceUpdatedEventData

Event payload for a space update.

Event type: google.workspace.chat.space.v1.updated

space_batch_updated_event_data

SpaceBatchUpdatedEventData

Event payload for multiple updates to a space.

Event type: google.workspace.chat.space.v1.batchUpdated

membership_created_event_data

MembershipCreatedEventData

Event payload for a new membership.

Event type: google.workspace.chat.membership.v1.created

membership_updated_event_data

MembershipUpdatedEventData

Event payload for an updated membership.

Event type: google.workspace.chat.membership.v1.updated

membership_deleted_event_data

MembershipDeletedEventData

Event payload for a deleted membership.

Event type: google.workspace.chat.membership.v1.deleted

membership_batch_created_event_data

MembershipBatchCreatedEventData

Event payload for multiple new memberships.

Event type: google.workspace.chat.membership.v1.batchCreated

membership_batch_updated_event_data

MembershipBatchUpdatedEventData

Event payload for multiple updated memberships.

Event type: google.workspace.chat.membership.v1.batchUpdated

membership_batch_deleted_event_data

MembershipBatchDeletedEventData

Event payload for multiple deleted memberships.

Event type: google.workspace.chat.membership.v1.batchDeleted

reaction_created_event_data

ReactionCreatedEventData

Event payload for a new reaction.

Event type: google.workspace.chat.reaction.v1.created

reaction_deleted_event_data

ReactionDeletedEventData

Event payload for a deleted reaction.

Event type: google.workspace.chat.reaction.v1.deleted

reaction_batch_created_event_data

ReactionBatchCreatedEventData

Event payload for multiple new reactions.

Event type: google.workspace.chat.reaction.v1.batchCreated

reaction_batch_deleted_event_data

ReactionBatchDeletedEventData

Event payload for multiple deleted reactions.

Event type: google.workspace.chat.reaction.v1.batchDeleted

SpaceReadState

A user's read state within a space, used to identify read and unread messages.

Поля
name

string

Resource name of the space read state.

Format: users/{user}/spaces/{space}/spaceReadState

last_read_time

Timestamp

Необязательный. The time when the user's space read state was updated. Usually this corresponds with either the timestamp of the last read message, or a timestamp specified by the user to mark the last read position in a space.

SpaceUpdatedEventData

Event payload for an updated space.

Event type: google.workspace.chat.space.v1.updated

Поля
space

Space

The updated space.

Нить

A thread in a Google Chat space. For example usage, see Start or reply to a message thread .

If you specify a thread when creating a message, you can set the messageReplyOption field to determine what happens if no matching thread is found.

Поля
name

string

Resource name of the thread.

Example: spaces/{space}/threads/{thread}

thread_key

string

Необязательный. Input for creating or updating a thread. Otherwise, output only. ID for the thread. Supports up to 4000 characters.

This ID is unique to the Chat app that sets it. For example, if multiple Chat apps create a message using the same thread key, the messages are posted in different threads. To reply in a thread created by a person or another Chat app, specify the thread name field instead.

ThreadReadState

A user's read state within a thread, used to identify read and unread messages.

Поля
name

string

Resource name of the thread read state.

Format: users/{user}/spaces/{space}/threads/{thread}/threadReadState

last_read_time

Timestamp

The time when the user's thread read state was updated. Usually this corresponds with the timestamp of the last read message in a thread.

UpdateMembershipRequest

Request message for updating a membership.

Поля
membership

Membership

Необходимый. The membership to update. Only fields specified by update_mask are updated.

update_mask

FieldMask

Необходимый. The field paths to update. Separate multiple values with commas or use * to update all field paths.

Currently supported field paths:

  • role
use_admin_access

bool

When true , the method runs using the user's Google Workspace administrator privileges.

The calling user must be a Google Workspace administrator with the manage chat and spaces conversations privilege .

Requires the chat.admin.memberships OAuth 2.0 scope .

UpdateMessageRequest

Request to update a message.

Поля
message

Message

Необходимый. Message with fields updated.

update_mask

FieldMask

Необходимый. The field paths to update. Separate multiple values with commas or use * to update all field paths.

Currently supported field paths:

allow_missing

bool

Необязательный. If true and the message isn't found, a new message is created and updateMask is ignored. The specified message ID must be client-assigned or the request fails.

UpdateSpaceReadStateRequest

Request message for UpdateSpaceReadState API.

Поля
space_read_state

SpaceReadState

Необходимый. The space read state and fields to update.

Only supports updating read state for the calling user.

To refer to the calling user, set one of the following:

  • The me alias. For example, users/me/spaces/{space}/spaceReadState .

  • Their Workspace email address. For example, users/user@example.com/spaces/{space}/spaceReadState .

  • Their user id. For example, users/123456789/spaces/{space}/spaceReadState .

Format: users/{user}/spaces/{space}/spaceReadState

update_mask

FieldMask

Необходимый. The field paths to update. Currently supported field paths:

  • last_read_time

When the last_read_time is before the latest message create time, the space appears as unread in the UI.

To mark the space as read, set last_read_time to any value later (larger) than the latest message create time. The last_read_time is coerced to match the latest message create time. Note that the space read state only affects the read state of messages that are visible in the space's top-level conversation. Replies in threads are unaffected by this timestamp, and instead rely on the thread read state.

UpdateSpaceRequest

A request to update a single space.

Поля
space

Space

Необходимый. Space with fields to be updated. Space.name must be populated in the form of spaces/{space} . Only fields specified by update_mask are updated.

update_mask

FieldMask

Необходимый. The updated field paths, comma separated if there are multiple.

You can update the following fields for a space:

  • space_details

  • display_name : Only supports updating the display name for spaces where spaceType field is SPACE . If you receive the error message ALREADY_EXISTS , try a different value. An existing space within the Google Workspace organization might already use this display name.

  • space_type : Only supports changing a GROUP_CHAT space type to SPACE . Include display_name together with space_type in the update mask and ensure that the specified space has a non-empty display name and the SPACE space type. Including the space_type mask and the SPACE type in the specified space when updating the display name is optional if the existing space already has the SPACE type. Trying to update the space type in other ways results in an invalid argument error. space_type is not supported with admin access.

  • space_history_state : Updates space history settings by turning history on or off for the space. Only supported if history settings are enabled for the Google Workspace organization. To update the space history state, you must omit all other field masks in your request. space_history_state is not supported with admin access.

  • access_settings.audience : Updates the access setting of who can discover the space, join the space, and preview the messages in named space where spaceType field is SPACE . If the existing space has a target audience, you can remove the audience and restrict space access by omitting a value for this field mask. To update access settings for a space, the authenticating user must be a space manager and omit all other field masks in your request. You can't update this field if the space is in import mode . To learn more, see Make a space discoverable to specific users . access_settings.audience is not supported with admin access.

  • Developer Preview: Supports changing the permission settings of a space, supported field paths include: permission_settings.manage_members_and_groups , permission_settings.modify_space_details , permission_settings.toggle_history , permission_settings.use_at_mention_all , permission_settings.manage_apps , permission_settings.manage_webhooks , permission_settings.reply_messages (Warning: mutually exclusive with all other non-permission settings field paths). permission_settings is not supported with admin access.

use_admin_access

bool

When true , the method runs using the user's Google Workspace administrator privileges.

The calling user must be a Google Workspace administrator with the manage chat and spaces conversations privilege .

Requires the chat.admin.spaces OAuth 2.0 scope .

Some FieldMask values are not supported using admin access. For details, see the description of update_mask .

Пользователь

A user in Google Chat. When returned as an output from a request, if your Chat app authenticates as a user , the output for a User resource only populates the user's name and type .

Поля
name

string

Resource name for a Google Chat user .

Format: users/{user} . users/app can be used as an alias for the calling app bot user.

For human users , {user} is the same user identifier as:

  • the id for the Person in the People API. For example, users/123456789 in Chat API represents the same person as the 123456789 Person profile ID in People API.

  • the id for a user in the Admin SDK Directory API.

  • the user's email address can be used as an alias for {user} in API requests. For example, if the People API Person profile ID for user@example.com is 123456789 , you can use users/user@example.com as an alias to reference users/123456789 . Only the canonical resource name (for example users/123456789 ) will be returned from the API.

display_name

string

Только вывод. The user's display name.

domain_id

string

Unique identifier of the user's Google Workspace domain.

type

Type

User type.

is_anonymous

bool

Только вывод. When true , the user is deleted or their profile is not visible.

Тип

Перечисления
TYPE_UNSPECIFIED Default value for the enum. НЕ ИСПОЛЬЗУЙТЕ.
HUMAN Human user.
BOT Chat app user.

UserMentionMetadata

Annotation metadata for user mentions (@).

Поля
user

User

The user mentioned.

type

Type

The type of user mention.

Тип

Перечисления
TYPE_UNSPECIFIED Default value for the enum. Не используйте.
ADD Add user to space.
MENTION Mention user in space.

WidgetMarkup

A widget is a UI element that presents text and images.

Поля
buttons[]

Button

Список кнопок. Buttons is also oneof data and only one of these fields should be set.

data поля объединения. A WidgetMarkup can only have one of the following items. You can use multiple WidgetMarkup fields to display more items. data могут быть только одним из следующих:
text_paragraph

TextParagraph

Display a text paragraph in this widget.

image

Image

Display an image in this widget.

key_value

KeyValue

Display a key value item in this widget.

Кнопка

Кнопка. Can be a text button or an image button.

Поля

Union field type .

type can be only one of the following:

text_button

TextButton

A button with text and onclick action.

image_button

ImageButton

A button with image and onclick action.

FormAction

A form action describes the behavior when the form is submitted. For example, you can invoke Apps Script to handle the form.

Поля
action_method_name

string

The method name is used to identify which part of the form triggered the form submission. This information is echoed back to the Chat app as part of the card click event. You can use the same method name for several elements that trigger a common behavior.

parameters[]

ActionParameter

Список параметров действия.

Параметр действия

Список строковых параметров, которые необходимо указать при вызове метода действия. For example, consider three snooze buttons: snooze now, snooze one day, snooze next week. Вы можете использовать action method = snooze() , передав тип и время повтора в списке строковых параметров.

Поля
key

string

Имя параметра сценария действия.

value

string

Значение параметра.

Икона

The set of supported icons.

Перечисления
ICON_UNSPECIFIED
AIRPLANE
BOOKMARK
BUS
CAR
CLOCK
CONFIRMATION_NUMBER_ICON
DOLLAR
DESCRIPTION
EMAIL
EVENT_PERFORMER
EVENT_SEAT
FLIGHT_ARRIVAL
FLIGHT_DEPARTURE
HOTEL
HOTEL_ROOM_TYPE
INVITE
MAP_PIN
MEMBERSHIP
MULTIPLE_PEOPLE
OFFER
PERSON
PHONE
RESTAURANT_ICON
SHOPPING_CART
STAR
STORE
TICKET
TRAIN
VIDEO_CAMERA
VIDEO_PLAY

Изображение

An image that's specified by a URL and can have an onclick action.

Поля
image_url

string

The URL of the image.

on_click

OnClick

The onclick action.

aspect_ratio

double

The aspect ratio of this image (width and height). This field lets you reserve the right height for the image while waiting for it to load. It's not meant to override the built-in aspect ratio of the image. If unset, the server fills it by prefetching the image.

ImageButton

An image button with an onclick action.

Поля
on_click

OnClick

The onclick action.

name

string

The name of this image_button that's used for accessibility. Default value is provided if this name isn't specified.

icons полей Союза. The icon can be specified by an Icon enum or a URL. icons могут быть только одним из следующих:
icon

Icon

The icon specified by an enum that indices to an icon provided by Chat API.

icon_url

string

The icon specified by a URL.

KeyValue

A UI element contains a key (label) and a value (content). This element can also contain some actions such as onclick button.

Поля
top_label

string

The text of the top label. Formatted text supported. Дополнительную информацию о форматировании текста см. в разделах «Форматирование текста в приложениях Google Chat» и «Форматирование текста в надстройках Google Workspace» .

content

string

The text of the content. Formatted text supported and always required. Дополнительную информацию о форматировании текста см. в разделах «Форматирование текста в приложениях Google Chat» и «Форматирование текста в надстройках Google Workspace» .

content_multiline

bool

If the content should be multiline.

bottom_label

string

The text of the bottom label. Formatted text supported. Дополнительную информацию о форматировании текста см. в разделах «Форматирование текста в приложениях Google Chat» и «Форматирование текста в надстройках Google Workspace» .

on_click

OnClick

The onclick action. Only the top label, bottom label, and content region are clickable.

icons полей Союза. At least one of icons, top_label and bottom_label must be defined. icons могут быть только одним из следующих:
icon

Icon

An enum value that's replaced by the Chat API with the corresponding icon image.

icon_url

string

The icon specified by a URL.

Полевой control Союза. A control widget. You can set either button or switch_widget , but not both. control может быть только одним из следующих:
button

Button

A button that can be clicked to trigger an action.

OnClick

An onclick action (for example, open a link).

Поля

data поля объединения.

data могут быть только одним из следующих:

action

FormAction

A form action is triggered by this onclick action if specified.

TextButton

A button with text and onclick action.

Поля
text

string

The text of the button.

on_click

OnClick

The onclick action of the button.

TextParagraph

A paragraph of text. Formatted text supported. Дополнительную информацию о форматировании текста см. в разделах «Форматирование текста в приложениях Google Chat» и «Форматирование текста в надстройках Google Workspace» .

Поля
text

string

,

Индекс

ChatService

Enables developers to build Chat apps and integrations on Google Chat Platform.

CompleteImportSpace

rpc CompleteImportSpace( CompleteImportSpaceRequest ) returns ( CompleteImportSpaceResponse )

Completes the import process for the specified space and makes it visible to users. Requires app authentication and domain-wide delegation. For more information, see Authorize Google Chat apps to import data .

Области авторизации

Требуется следующая область действия OAuth:

  • https://www.googleapis.com/auth/chat.import

For more information, see the Authorization guide .

CreateMembership

rpc CreateMembership( CreateMembershipRequest ) returns ( Membership )

Creates a human membership or app membership for the calling app. Creating memberships for other apps isn't supported. For an example, see Invite or add a user or a Google Chat app to a space . When creating a membership, if the specified member has their auto-accept policy turned off, then they're invited, and must accept the space invitation before joining. Otherwise, creating a membership adds the member directly to the specified space. Requires user authentication .

To specify the member to add, set the membership.member.name for the human or app member, or set the membership.group_member.name for the group member.

  • To add the calling app to a space or a direct message between two human users, use users/app . Unable to add other apps to the space.

  • To add a human user, use users/{user} , where {user} can be the email address for the user. For users in the same Workspace organization {user} can also be the id for the person from the People API, or the id for the user in the Directory API. For example, if the People API Person profile ID for user@example.com is 123456789 , you can add the user to the space by setting the membership.member.name to users/user@example.com or users/123456789 .

  • To add or invite a Google group in a named space, use groups/{group} , where {group} is the id for the group from the Cloud Identity Groups API. For example, you can use Cloud Identity Groups lookup API to retrieve the ID 123456789 for group email group@example.com , then you can add or invite the group to a named space by setting the membership.group_member.name to groups/123456789 . Group email is not supported, and Google groups can only be added as members in named spaces.

Области авторизации

Requires one of the following OAuth scopes:

  • https://www.googleapis.com/auth/chat.admin.memberships
  • https://www.googleapis.com/auth/chat.import
  • https://www.googleapis.com/auth/chat.memberships
  • https://www.googleapis.com/auth/chat.memberships.app

For more information, see the Authorization guide .

CreateMessage

rpc CreateMessage( CreateMessageRequest ) returns ( Message )

Creates a message in a Google Chat space. The maximum message size, including text and cards, is 32,000 bytes. For an example, see Send a message .

Calling this method requires authentication and supports the following authentication types:

  • For text messages, user authentication or app authentication are supported.
  • For card messages, only app authentication is supported. (Only Chat apps can create card messages.)
Области авторизации

Requires one of the following OAuth scopes:

  • https://www.googleapis.com/auth/chat.bot
  • https://www.googleapis.com/auth/chat.import
  • https://www.googleapis.com/auth/chat.messages
  • https://www.googleapis.com/auth/chat.messages.create

For more information, see the Authorization guide .

CreateReaction

rpc CreateReaction( CreateReactionRequest ) returns ( Reaction )

Creates a reaction and adds it to a message. Only unicode emojis are supported. For an example, see Add a reaction to a message . Requires user authentication .

Области авторизации

Requires one of the following OAuth scopes:

  • https://www.googleapis.com/auth/chat.import
  • https://www.googleapis.com/auth/chat.messages
  • https://www.googleapis.com/auth/chat.messages.reactions
  • https://www.googleapis.com/auth/chat.messages.reactions.create

For more information, see the Authorization guide .

Создать пространство

rpc CreateSpace( CreateSpaceRequest ) returns ( Space )

Creates a named space. Spaces grouped by topics aren't supported. For an example, see Create a space .

If you receive the error message ALREADY_EXISTS when creating a space, try a different displayName . An existing space within the Google Workspace organization might already use this display name.

Requires user authentication .

Области авторизации

Requires one of the following OAuth scopes:

  • https://www.googleapis.com/auth/chat.import
  • https://www.googleapis.com/auth/chat.spaces
  • https://www.googleapis.com/auth/chat.spaces.create

For more information, see the Authorization guide .

DeleteMembership

rpc DeleteMembership( DeleteMembershipRequest ) returns ( Membership )

Deletes a membership. For an example, see Remove a user or a Google Chat app from a space .

Requires user authentication .

Области авторизации

Requires one of the following OAuth scopes:

  • https://www.googleapis.com/auth/chat.admin.memberships
  • https://www.googleapis.com/auth/chat.import
  • https://www.googleapis.com/auth/chat.memberships
  • https://www.googleapis.com/auth/chat.memberships.app

For more information, see the Authorization guide .

DeleteMessage

rpc DeleteMessage( DeleteMessageRequest ) returns ( Empty )

Deletes a message. For an example, see Delete a message .

Requires authentication . Supports app authentication and user authentication . When using app authentication, requests can only delete messages created by the calling Chat app.

Области авторизации

Requires one of the following OAuth scopes:

  • https://www.googleapis.com/auth/chat.bot
  • https://www.googleapis.com/auth/chat.import
  • https://www.googleapis.com/auth/chat.messages

For more information, see the Authorization guide .

DeleteReaction

rpc DeleteReaction( DeleteReactionRequest ) returns ( Empty )

Deletes a reaction to a message. Only unicode emojis are supported. For an example, see Delete a reaction . Requires user authentication .

Области авторизации

Requires one of the following OAuth scopes:

  • https://www.googleapis.com/auth/chat.import
  • https://www.googleapis.com/auth/chat.messages
  • https://www.googleapis.com/auth/chat.messages.reactions

For more information, see the Authorization guide .

DeleteSpace

rpc DeleteSpace( DeleteSpaceRequest ) returns ( Empty )

Deletes a named space. Always performs a cascading delete, which means that the space's child resources—like messages posted in the space and memberships in the space—are also deleted. For an example, see Delete a space . Requires user authentication from a user who has permission to delete the space.

Области авторизации

Requires one of the following OAuth scopes:

  • https://www.googleapis.com/auth/chat.admin.delete
  • https://www.googleapis.com/auth/chat.import
  • https://www.googleapis.com/auth/chat.delete

For more information, see the Authorization guide .

FindDirectMessage

rpc FindDirectMessage( FindDirectMessageRequest ) returns ( Space )

Returns the existing direct message with the specified user. If no direct message space is found, returns a 404 NOT_FOUND error. For an example, see Find a direct message .

With user authentication , returns the direct message space between the specified user and the authenticated user.

With app authentication , returns the direct message space between the specified user and the calling Chat app.

Requires user authentication or app authentication .

Области авторизации

Requires one of the following OAuth scopes:

  • https://www.googleapis.com/auth/chat.spaces
  • https://www.googleapis.com/auth/chat.spaces.readonly
  • https://www.googleapis.com/auth/chat.bot

For more information, see the Authorization guide .

GetAttachment

rpc GetAttachment( GetAttachmentRequest ) returns ( Attachment )

Gets the metadata of a message attachment. The attachment data is fetched using the media API . For an example, see Get metadata about a message attachment . Requires app authentication .

Области авторизации

Требуется следующая область действия OAuth:

  • https://www.googleapis.com/auth/chat.bot

For more information, see the Authorization guide .

GetMembership

rpc GetMembership( GetMembershipRequest ) returns ( Membership )

Returns details about a membership. For an example, see Get details about a user's or Google Chat app's membership .

Requires authentication . Supports app authentication and user authentication .

Области авторизации

Requires one of the following OAuth scopes:

  • https://www.googleapis.com/auth/chat.admin.memberships
  • https://www.googleapis.com/auth/chat.admin.memberships.readonly
  • https://www.googleapis.com/auth/chat.bot
  • https://www.googleapis.com/auth/chat.memberships
  • https://www.googleapis.com/auth/chat.memberships.readonly

For more information, see the Authorization guide .

GetMessage

rpc GetMessage( GetMessageRequest ) returns ( Message )

Returns details about a message. For an example, see Get details about a message .

Requires authentication . Supports app authentication and user authentication .

Note: Might return a message from a blocked member or space.

Области авторизации

Requires one of the following OAuth scopes:

  • https://www.googleapis.com/auth/chat.bot
  • https://www.googleapis.com/auth/chat.messages
  • https://www.googleapis.com/auth/chat.messages.readonly

For more information, see the Authorization guide .

GetSpace

rpc GetSpace( GetSpaceRequest ) returns ( Space )

Returns details about a space. For an example, see Get details about a space .

Requires authentication . Supports app authentication and user authentication .

Области авторизации

Requires one of the following OAuth scopes:

  • https://www.googleapis.com/auth/chat.admin.spaces
  • https://www.googleapis.com/auth/chat.admin.spaces.readonly
  • https://www.googleapis.com/auth/chat.spaces
  • https://www.googleapis.com/auth/chat.spaces.readonly
  • https://www.googleapis.com/auth/chat.bot

For more information, see the Authorization guide .

GetSpaceEvent

rpc GetSpaceEvent( GetSpaceEventRequest ) returns ( SpaceEvent )

Returns an event from a Google Chat space. The event payload contains the most recent version of the resource that changed. For example, if you request an event about a new message but the message was later updated, the server returns the updated Message resource in the event payload.

Requires user authentication . To get an event, the authenticated user must be a member of the space.

For an example, see Get details about an event from a Google Chat space .

Области авторизации

Requires one of the following OAuth scopes:

  • https://www.googleapis.com/auth/chat.spaces
  • https://www.googleapis.com/auth/chat.spaces.readonly
  • https://www.googleapis.com/auth/chat.messages
  • https://www.googleapis.com/auth/chat.messages.readonly
  • https://www.googleapis.com/auth/chat.memberships
  • https://www.googleapis.com/auth/chat.memberships.readonly
  • https://www.googleapis.com/auth/chat.messages.reactions
  • https://www.googleapis.com/auth/chat.messages.reactions.readonly

For more information, see the Authorization guide .

GetSpaceReadState

rpc GetSpaceReadState( GetSpaceReadStateRequest ) returns ( SpaceReadState )

Returns details about a user's read state within a space, used to identify read and unread messages. For an example, see Get details about a user's space read state .

Requires user authentication .

Области авторизации

Requires one of the following OAuth scopes:

  • https://www.googleapis.com/auth/chat.users.readstate
  • https://www.googleapis.com/auth/chat.users.readstate.readonly

For more information, see the Authorization guide .

GetThreadReadState

rpc GetThreadReadState( GetThreadReadStateRequest ) returns ( ThreadReadState )

Returns details about a user's read state within a thread, used to identify read and unread messages. For an example, see Get details about a user's thread read state .

Requires user authentication .

Области авторизации

Requires one of the following OAuth scopes:

  • https://www.googleapis.com/auth/chat.users.readstate
  • https://www.googleapis.com/auth/chat.users.readstate.readonly

For more information, see the Authorization guide .

ListMemberships

rpc ListMemberships( ListMembershipsRequest ) returns ( ListMembershipsResponse )

Lists memberships in a space. For an example, see List users and Google Chat apps in a space . Listing memberships with app authentication lists memberships in spaces that the Chat app has access to, but excludes Chat app memberships, including its own. Listing memberships with User authentication lists memberships in spaces that the authenticated user has access to.

Requires authentication . Supports app authentication and user authentication .

Области авторизации

Requires one of the following OAuth scopes:

  • https://www.googleapis.com/auth/chat.admin.memberships
  • https://www.googleapis.com/auth/chat.admin.memberships.readonly
  • https://www.googleapis.com/auth/chat.import
  • https://www.googleapis.com/auth/chat.bot
  • https://www.googleapis.com/auth/chat.memberships
  • https://www.googleapis.com/auth/chat.memberships.readonly

For more information, see the Authorization guide .

ListMessages

rpc ListMessages( ListMessagesRequest ) returns ( ListMessagesResponse )

Lists messages in a space that the caller is a member of, including messages from blocked members and spaces. For an example, see List messages . Requires user authentication .

Области авторизации

Requires one of the following OAuth scopes:

  • https://www.googleapis.com/auth/chat.import
  • https://www.googleapis.com/auth/chat.messages
  • https://www.googleapis.com/auth/chat.messages.readonly

For more information, see the Authorization guide .

ListReactions

rpc ListReactions( ListReactionsRequest ) returns ( ListReactionsResponse )

Lists reactions to a message. For an example, see List reactions for a message . Requires user authentication .

Области авторизации

Requires one of the following OAuth scopes:

  • https://www.googleapis.com/auth/chat.messages
  • https://www.googleapis.com/auth/chat.messages.readonly
  • https://www.googleapis.com/auth/chat.messages.reactions
  • https://www.googleapis.com/auth/chat.messages.reactions.readonly

For more information, see the Authorization guide .

ListSpaceEvents

rpc ListSpaceEvents( ListSpaceEventsRequest ) returns ( ListSpaceEventsResponse )

Lists events from a Google Chat space. For each event, the payload contains the most recent version of the Chat resource. For example, if you list events about new space members, the server returns Membership resources that contain the latest membership details. If new members were removed during the requested period, the event payload contains an empty Membership resource.

Requires user authentication . To list events, the authenticated user must be a member of the space.

For an example, see List events from a Google Chat space .

Области авторизации

Requires one of the following OAuth scopes:

  • https://www.googleapis.com/auth/chat.spaces
  • https://www.googleapis.com/auth/chat.spaces.readonly
  • https://www.googleapis.com/auth/chat.messages
  • https://www.googleapis.com/auth/chat.messages.readonly
  • https://www.googleapis.com/auth/chat.memberships
  • https://www.googleapis.com/auth/chat.memberships.readonly
  • https://www.googleapis.com/auth/chat.messages.reactions
  • https://www.googleapis.com/auth/chat.messages.reactions.readonly

For more information, see the Authorization guide .

ListSpaces

rpc ListSpaces( ListSpacesRequest ) returns ( ListSpacesResponse )

Lists spaces the caller is a member of. Group chats and DMs aren't listed until the first message is sent. For an example, see List spaces .

Requires authentication . Supports app authentication and user authentication .

Lists spaces visible to the caller or authenticated user. Group chats and DMs aren't listed until the first message is sent.

To list all named spaces by Google Workspace organization, use the spaces.search() method using Workspace administrator privileges instead.

Области авторизации

Requires one of the following OAuth scopes:

  • https://www.googleapis.com/auth/chat.spaces
  • https://www.googleapis.com/auth/chat.spaces.readonly
  • https://www.googleapis.com/auth/chat.bot

For more information, see the Authorization guide .

SearchSpaces

rpc SearchSpaces( SearchSpacesRequest ) returns ( SearchSpacesResponse )

Returns a list of spaces based on a user's search. Requires user authentication . The user must be an administrator for the Google Workspace organization. In the request, set use_admin_access to true .

Области авторизации

Requires one of the following OAuth scopes:

  • https://www.googleapis.com/auth/chat.admin.spaces
  • https://www.googleapis.com/auth/chat.admin.spaces.readonly

For more information, see the Authorization guide .

SetUpSpace

rpc SetUpSpace( SetUpSpaceRequest ) returns ( Space )

Creates a space and adds specified users to it. The calling user is automatically added to the space, and shouldn't be specified as a membership in the request. For an example, see Set up a space with initial members .

To specify the human members to add, add memberships with the appropriate membership.member.name . To add a human user, use users/{user} , where {user} can be the email address for the user. For users in the same Workspace organization {user} can also be the id for the person from the People API, or the id for the user in the Directory API. For example, if the People API Person profile ID for user@example.com is 123456789 , you can add the user to the space by setting the membership.member.name to users/user@example.com or users/123456789 .

To specify the Google groups to add, add memberships with the appropriate membership.group_member.name . To add or invite a Google group, use groups/{group} , where {group} is the id for the group from the Cloud Identity Groups API. For example, you can use Cloud Identity Groups lookup API to retrieve the ID 123456789 for group email group@example.com , then you can add the group to the space by setting the membership.group_member.name to groups/123456789 . Group email is not supported, and Google groups can only be added as members in named spaces.

For a named space or group chat, if the caller blocks, or is blocked by some members, or doesn't have permission to add some members, then those members aren't added to the created space.

To create a direct message (DM) between the calling user and another human user, specify exactly one membership to represent the human user. If one user blocks the other, the request fails and the DM isn't created.

To create a DM between the calling user and the calling app, set Space.singleUserBotDm to true and don't specify any memberships. You can only use this method to set up a DM with the calling app. To add the calling app as a member of a space or an existing DM between two human users, see Invite or add a user or app to a space .

If a DM already exists between two users, even when one user blocks the other at the time a request is made, then the existing DM is returned.

Spaces with threaded replies aren't supported. If you receive the error message ALREADY_EXISTS when setting up a space, try a different displayName . An existing space within the Google Workspace organization might already use this display name.

Requires user authentication .

Области авторизации

Requires one of the following OAuth scopes:

  • https://www.googleapis.com/auth/chat.spaces
  • https://www.googleapis.com/auth/chat.spaces.create

For more information, see the Authorization guide .

UpdateMembership

rpc UpdateMembership( UpdateMembershipRequest ) returns ( Membership )

Updates a membership. For an example, see Update a user's membership in a space .

Requires user authentication .

Области авторизации

Requires one of the following OAuth scopes:

  • https://www.googleapis.com/auth/chat.admin.memberships
  • https://www.googleapis.com/auth/chat.import
  • https://www.googleapis.com/auth/chat.memberships

For more information, see the Authorization guide .

UpdateMessage

rpc UpdateMessage( UpdateMessageRequest ) returns ( Message )

Updates a message. There's a difference between the patch and update methods. The patch method uses a patch request while the update method uses a put request. We recommend using the patch method. For an example, see Update a message .

Requires authentication . Supports app authentication and user authentication . When using app authentication, requests can only update messages created by the calling Chat app.

Области авторизации

Requires one of the following OAuth scopes:

  • https://www.googleapis.com/auth/chat.bot
  • https://www.googleapis.com/auth/chat.import
  • https://www.googleapis.com/auth/chat.messages

For more information, see the Authorization guide .

UpdateSpace

rpc UpdateSpace( UpdateSpaceRequest ) returns ( Space )

Updates a space. For an example, see Update a space .

If you're updating the displayName field and receive the error message ALREADY_EXISTS , try a different display name.. An existing space within the Google Workspace organization might already use this display name.

Requires user authentication .

Области авторизации

Requires one of the following OAuth scopes:

  • https://www.googleapis.com/auth/chat.admin.spaces
  • https://www.googleapis.com/auth/chat.import
  • https://www.googleapis.com/auth/chat.spaces

For more information, see the Authorization guide .

UpdateSpaceReadState

rpc UpdateSpaceReadState( UpdateSpaceReadStateRequest ) returns ( SpaceReadState )

Updates a user's read state within a space, used to identify read and unread messages. For an example, see Update a user's space read state .

Requires user authentication .

Области авторизации

Требуется следующая область действия OAuth:

  • https://www.googleapis.com/auth/chat.users.readstate

For more information, see the Authorization guide .

AccessoryWidget

One or more interactive widgets that appear at the bottom of a message. For details, see Add interactive widgets at the bottom of a message .

Поля
Union field action . The type of action. action can be only one of the following:
button_list

ButtonList

Список кнопок.

ActionResponse

Parameters that a Chat app can use to configure how its response is posted.

Поля
type

ResponseType

Input only. The type of Chat app response.

url

string

Input only. URL for users to authenticate or configure. (Only for REQUEST_CONFIG response types.)

dialog_action

DialogAction

Input only. A response to an interaction event related to a dialog . Must be accompanied by ResponseType.Dialog .

updated_widget

UpdatedWidget

Input only. The response of the updated widget.

ResponseType

The type of Chat app response.

Перечисления
TYPE_UNSPECIFIED Default type that's handled as NEW_MESSAGE .
NEW_MESSAGE Post as a new message in the topic.
UPDATE_MESSAGE Update the Chat app's message. This is only permitted on a CARD_CLICKED event where the message sender type is BOT .
UPDATE_USER_MESSAGE_CARDS Update the cards on a user's message. This is only permitted as a response to a MESSAGE event with a matched url, or a CARD_CLICKED event where the message sender type is HUMAN . Text is ignored.
REQUEST_CONFIG Privately ask the user for additional authentication or configuration.
DIALOG Presents a dialog .
UPDATE_WIDGET Widget text autocomplete options query.

SelectionItems

List of widget autocomplete results.

Поля
items[]

SelectionItem

An array of the SelectionItem objects.

UpdatedWidget

The response of the updated widget. Used to provide autocomplete options for a widget.

Поля
widget

string

The ID of the updated widget. The ID must match the one for the widget that triggered the update request.

Union field updated_widget . The widget updated in response to a user action. updated_widget can be only one of the following:
suggestions

SelectionItems

List of widget autocomplete results

ActionStatus

Represents the status for a request to either invoke or submit a dialog .

Поля
status_code

Code

The status code.

user_facing_message

string

The message to send users about the status of their request. If unset, a generic message based on the status_code is sent.

Аннотация

Только вывод. Annotations associated with the plain-text body of the message. To add basic formatting to a text message, see Format text messages .

Example plain-text message body:

Hello @FooBot how are you!"

The corresponding annotations metadata:

"annotations":[{
  "type":"USER_MENTION",
  "startIndex":6,
  "length":7,
  "userMention": {
    "user": {
      "name":"users/{user}",
      "displayName":"FooBot",
      "avatarUrl":"https://goo.gl/aeDtrS",
      "type":"BOT"
    },
    "type":"MENTION"
   }
}]
Поля
type

AnnotationType

The type of this annotation.

length

int32

Length of the substring in the plain-text message body this annotation corresponds to.

start_index

int32

Start index (0-based, inclusive) in the plain-text message body this annotation corresponds to.

Union field metadata . Additional metadata about the annotation. metadata can be only one of the following:
user_mention

UserMentionMetadata

The metadata of user mention.

slash_command

SlashCommandMetadata

The metadata for a slash command.

AnnotationType

Type of the annotation.

Перечисления
ANNOTATION_TYPE_UNSPECIFIED Default value for the enum. Не используйте.
USER_MENTION A user is mentioned.
SLASH_COMMAND A slash command is invoked.

AttachedGif

A GIF image that's specified by a URL.

Поля
uri

string

Только вывод. The URL that hosts the GIF image.

Вложение

An attachment in Google Chat.

Поля
name

string

Resource name of the attachment, in the form spaces/{space}/messages/{message}/attachments/{attachment} .

content_name

string

Только вывод. The original file name for the content, not the full path.

content_type

string

Только вывод. The content type (MIME type) of the file.

thumbnail_uri

string

Только вывод. The thumbnail URL which should be used to preview the attachment to a human user. Chat apps shouldn't use this URL to download attachment content.

download_uri

string

Только вывод. The download URL which should be used to allow a human user to download the attachment. Chat apps shouldn't use this URL to download attachment content.

source

Source

Только вывод. The source of the attachment.

Union field data_ref . The data reference to the attachment. data_ref can be only one of the following:
attachment_data_ref

AttachmentDataRef

A reference to the attachment data. This field is used with the media API to download the attachment data.

drive_data_ref

DriveDataRef

Только вывод. A reference to the Google Drive attachment. This field is used with the Google Drive API.

Источник

The source of the attachment.

Перечисления
SOURCE_UNSPECIFIED Сдержанный.
DRIVE_FILE The file is a Google Drive file.
UPLOADED_CONTENT The file is uploaded to Chat.

AttachmentDataRef

A reference to the attachment data.

Поля
resource_name

string

The resource name of the attachment data. This field is used with the media API to download the attachment data.

attachment_upload_token

string

Opaque token containing a reference to an uploaded attachment. Treated by clients as an opaque string and used to create or update Chat messages with attachments.

CardWithId

A card in a Google Chat message.

Only Chat apps can create cards. If your Chat app authenticates as a user , the message can't contain cards.

Создавайте и просматривайте карты с помощью Card Builder.

Откройте конструктор карточек

Поля
card_id

string

Required if the message contains multiple cards. A unique identifier for a card in a message.

card

Card

A card. Maximum size is 32 KB.

ChatSpaceLinkData

Data for Chat space links.

Поля
space

string

The space of the linked Chat space resource.

Format: spaces/{space}

thread

string

The thread of the linked Chat space resource.

Format: spaces/{space}/threads/{thread}

message

string

The message of the linked Chat space resource.

Format: spaces/{space}/messages/{message}

CompleteImportSpaceRequest

Request message for completing the import process for a space.

Поля
name

string

Необходимый. Resource name of the import mode space.

Format: spaces/{space}

CompleteImportSpaceResponse

Response message for completing the import process for a space.

Поля
space

Space

The import mode space.

ContextualAddOnMarkup

Этот тип не имеет полей.

The markup for developers to specify the contents of a contextual AddOn.

Карта

A card is a UI element that can contain UI widgets such as text and images.

Поля
header

CardHeader

Заголовок карты. A header usually contains a title and an image.

sections[]

Section

Sections are separated by a line divider.

card_actions[]

CardAction

The actions of this card.

name

string

Название карты.

КартаДействие

Действие карты — это действие, связанное с картой. For an invoice card, a typical action would be: delete invoice, email invoice or open the invoice in browser.

Not supported by Google Chat apps.

Поля
action_label

string

The label used to be displayed in the action menu item.

on_click

OnClick

The onclick action for this action item.

Заголовок карты

Поля
title

string

The title must be specified. The header has a fixed height: if both a title and subtitle is specified, each takes up one line. Если указан только заголовок, он занимает обе строки.

subtitle

string

Подзаголовок шапки карты.

image_style

ImageStyle

The image's type (for example, square border or circular border).

image_url

string

The URL of the image in the card header.

ImageStyle

Перечисления
IMAGE_STYLE_UNSPECIFIED
IMAGE Square border.
AVATAR Circular border.

Раздел

A section contains a collection of widgets that are rendered (vertically) in the order that they are specified. Across all platforms, cards have a narrow fixed width, so there's currently no need for layout properties (for example, float).

Поля
header

string

The header of the section. Formatted text is supported. Дополнительную информацию о форматировании текста см. в разделах «Форматирование текста в приложениях Google Chat» и «Форматирование текста в надстройках Google Workspace» .

widgets[]

WidgetMarkup

A section must contain at least one widget.

CreateMembershipRequest

Request message for creating a membership.

Поля
parent

string

Необходимый. The resource name of the space for which to create the membership.

Format: spaces/{space}

membership

Membership

Необходимый. The membership relation to create. The memberType field must contain a user with the user.name and user.type fields populated. The server will assign a resource name and overwrite anything specified. When a Chat app creates a membership relation for a human user, it must use the chat.memberships scope, set user.type to HUMAN , and set user.name with format users/{user} , where {user} can be the email address for the user. For users in the same Workspace organization {user} can also be the id of the person from the People API, or the id for the user in the Directory API. For example, if the People API Person profile ID for user@example.com is 123456789 , you can add the user to the space by setting the membership.member.name to users/user@example.com or users/123456789 . When a Chat app creates a membership relation for itself, it must use the chat.memberships.app scope, set user.type to BOT , and set user.name to users/app .

use_admin_access

bool

When true , the method runs using the user's Google Workspace administrator privileges.

The calling user must be a Google Workspace administrator with the manage chat and spaces conversations privilege .

Requires the chat.admin.memberships OAuth 2.0 scope .

Creating app memberships or creating memberships for users outside the administrator's Google Workspace organization isn't supported using admin access.

CreateMessageRequest

Creates a message.

Поля
parent

string

Необходимый. The resource name of the space in which to create a message.

Format: spaces/{space}

message

Message

Необходимый. Message body.

thread_key
(deprecated)

string

Необязательный. Deprecated: Use thread.thread_key instead. ID for the thread. Supports up to 4000 characters. To start or add to a thread, create a message and specify a threadKey or the thread.name . For example usage, see Start or reply to a message thread .

request_id

string

Необязательный. A unique request ID for this message. Specifying an existing request ID returns the message created with that ID instead of creating a new message.

message_reply_option

MessageReplyOption

Необязательный. Specifies whether a message starts a thread or replies to one. Only supported in named spaces.

message_id

string

Необязательный. A custom ID for a message. Lets Chat apps get, update, or delete a message without needing to store the system-assigned ID in the message's resource name (represented in the message name field).

The value for this field must meet the following requirements:

  • Begins with client- . For example, client-custom-name is a valid custom ID, but custom-name is not.
  • Contains up to 63 characters and only lowercase letters, numbers, and hyphens.
  • Is unique within a space. A Chat app can't use the same custom ID for different messages.

For details, see Name a message .

MessageReplyOption

Specifies how to reply to a message. More states might be added in the future.

Перечисления
MESSAGE_REPLY_OPTION_UNSPECIFIED По умолчанию. Starts a new thread. Using this option ignores any thread ID or thread_key that's included.
REPLY_MESSAGE_FALLBACK_TO_NEW_THREAD Creates the message as a reply to the thread specified by thread ID or thread_key . If it fails, the message starts a new thread instead.
REPLY_MESSAGE_OR_FAIL Creates the message as a reply to the thread specified by thread ID or thread_key . If a new thread_key is used, a new thread is created. If the message creation fails, a NOT_FOUND error is returned instead.

CreateReactionRequest

Creates a reaction to a message.

Поля
parent

string

Необходимый. The message where the reaction is created.

Format: spaces/{space}/messages/{message}

reaction

Reaction

Необходимый. The reaction to create.

CreateSpaceRequest

A request to create a named space.

Поля
space

Space

Необходимый. The displayName and spaceType fields must be populated. Only SpaceType.SPACE is supported.

If you receive the error message ALREADY_EXISTS , try a different displayName . An existing space within the Google Workspace organization might already use this display name.

The space name is assigned on the server so anything specified in this field will be ignored.

request_id

string

Необязательный. A unique identifier for this request. A random UUID is recommended. Specifying an existing request ID returns the space created with that ID instead of creating a new space. Specifying an existing request ID from the same Chat app with a different authenticated user returns an error.

CustomEmoji

Represents a custom emoji.

Поля
uid

string

Только вывод. Unique key for the custom emoji resource.

DeleteMembershipRequest

Request to delete a membership in a space.

Поля
name

string

Необходимый. Resource name of the membership to delete. Chat apps can delete human users' or their own memberships. Chat apps can't delete other apps' memberships.

When deleting a human membership, requires the chat.memberships scope and spaces/{space}/members/{member} format. You can use the email as an alias for {member} . For example, spaces/{space}/members/example@gmail.com where example@gmail.com is the email of the Google Chat user.

When deleting an app membership, requires the chat.memberships.app scope and spaces/{space}/members/app format.

Format: spaces/{space}/members/{member} or spaces/{space}/members/app .

use_admin_access

bool

When true , the method runs using the user's Google Workspace administrator privileges.

The calling user must be a Google Workspace administrator with the manage chat and spaces conversations privilege .

Requires the chat.admin.memberships OAuth 2.0 scope .

Deleting app memberships in a space isn't supported using admin access.

DeleteMessageRequest

Request to delete a message.

Поля
name

string

Необходимый. Resource name of the message.

Format: spaces/{space}/messages/{message}

If you've set a custom ID for your message, you can use the value from the clientAssignedMessageId field for {message} . For details, see Name a message .

force

bool

When true , deleting a message also deletes its threaded replies. When false , if a message has threaded replies, deletion fails.

Only applies when authenticating as a user . Has no effect when authenticating as a Chat app .

DeleteReactionRequest

Deletes a reaction to a message.

Поля
name

string

Необходимый. Name of the reaction to delete.

Format: spaces/{space}/messages/{message}/reactions/{reaction}

DeleteSpaceRequest

Request for deleting a space.

Поля
name

string

Необходимый. Resource name of the space to delete.

Format: spaces/{space}

use_admin_access

bool

When true , the method runs using the user's Google Workspace administrator privileges.

The calling user must be a Google Workspace administrator with the manage chat and spaces conversations privilege .

Requires the chat.admin.delete OAuth 2.0 scope .

DeletionMetadata

Information about a deleted message. A message is deleted when delete_time is set.

Поля
deletion_type

DeletionType

Indicates who deleted the message.

DeletionType

Who deleted the message and how it was deleted.

Перечисления
DELETION_TYPE_UNSPECIFIED This value is unused.
CREATOR User deleted their own message.
SPACE_OWNER The space owner deleted the message.
ADMIN A Google Workspace admin deleted the message.
APP_MESSAGE_EXPIRY A Chat app deleted its own message when it expired.
CREATOR_VIA_APP A Chat app deleted the message on behalf of the user.
SPACE_OWNER_VIA_APP A Chat app deleted the message on behalf of the space owner.

Диалог

Wrapper around the card body of the dialog.

Поля
body

Card

Input only. Body of the dialog, which is rendered in a modal. Google Chat apps don't support the following card entities: DateTimePicker , OnChangeAction .

DialogAction

Contains a dialog and request status code.

Fields
action_status

ActionStatus

Input only. Status for a request to either invoke or submit a dialog . Displays a status and message to users, if necessary. For example, in case of an error or success.

Union field action . Action to perform. action can be only one of the following:
dialog

Dialog

Input only. Dialog for the request.

DriveDataRef

A reference to the data of a drive attachment.

Поля
drive_file_id

string

The ID for the drive file. Use with the Drive API.

DriveLinkData

Data for Google Drive links.

Fields
drive_data_ref

DriveDataRef

A DriveDataRef which references a Google Drive file.

mime_type

string

The mime type of the linked Google Drive resource.

Эмодзи

An emoji that is used as a reaction to a message.

Fields
Полевой content союза. The content of the emoji. content может быть только одним из следующих:
unicode

string

A basic emoji represented by a unicode string.

custom_emoji

CustomEmoji

Только вывод. A custom emoji.

EmojiReactionSummary

The number of people who reacted to a message with a specific emoji.

Fields
emoji

Emoji

Emoji associated with the reactions.

reaction_count

int32

The total number of reactions using the associated emoji.

FindDirectMessageRequest

A request to get direct message space based on the user resource.

Fields
name

string

Необходимый. Resource name of the user to find direct message with.

Format: users/{user} , where {user} is either the id for the person from the People API, or the id for the user in the Directory API. For example, if the People API profile ID is 123456789 , you can find a direct message with that person by using users/123456789 as the name . When authenticated as a user , you can use the email as an alias for {user} . For example, users/example@gmail.com where example@gmail.com is the email of the Google Chat user.

GetAttachmentRequest

Request to get an attachment.

Fields
name

string

Необходимый. Resource name of the attachment, in the form spaces/{space}/messages/{message}/attachments/{attachment} .

GetMembershipRequest

Request to get a membership of a space.

Fields
name

string

Необходимый. Resource name of the membership to retrieve.

To get the app's own membership by using user authentication , you can optionally use spaces/{space}/members/app .

Format: spaces/{space}/members/{member} or spaces/{space}/members/app

When authenticated as a user , you can use the user's email as an alias for {member} . For example, spaces/{space}/members/example@gmail.com where example@gmail.com is the email of the Google Chat user.

use_admin_access

bool

When true , the method runs using the user's Google Workspace administrator privileges.

The calling user must be a Google Workspace administrator with the manage chat and spaces conversations privilege .

Requires the chat.admin.memberships or chat.admin.memberships.readonly OAuth 2.0 scopes .

Getting app memberships in a space isn't supported when using admin access.

GetMessageRequest

Request to get a message.

Fields
name

string

Необходимый. Resource name of the message.

Format: spaces/{space}/messages/{message}

If you've set a custom ID for your message, you can use the value from the clientAssignedMessageId field for {message} . For details, see Name a message .

GetSpaceEventRequest

Request message for getting a space event.

Fields
name

string

Необходимый. The resource name of the space event.

Format: spaces/{space}/spaceEvents/{spaceEvent}

GetSpaceReadStateRequest

Request message for GetSpaceReadState API.

Поля
name

string

Необходимый. Resource name of the space read state to retrieve.

Only supports getting read state for the calling user.

To refer to the calling user, set one of the following:

  • The me alias. For example, users/me/spaces/{space}/spaceReadState .

  • Their Workspace email address. For example, users/user@example.com/spaces/{space}/spaceReadState .

  • Their user id. For example, users/123456789/spaces/{space}/spaceReadState .

Format: users/{user}/spaces/{space}/spaceReadState

GetSpaceRequest

A request to return a single space.

Fields
name

string

Необходимый. Resource name of the space, in the form spaces/{space} .

Format: spaces/{space}

use_admin_access

bool

When true , the method runs using the user's Google Workspace administrator privileges.

The calling user must be a Google Workspace administrator with the manage chat and spaces conversations privilege .

Requires the chat.admin.spaces or chat.admin.spaces.readonly OAuth 2.0 scopes .

GetThreadReadStateRequest

Request message for GetThreadReadStateRequest API.

Fields
name

string

Необходимый. Resource name of the thread read state to retrieve.

Only supports getting read state for the calling user.

To refer to the calling user, set one of the following:

  • The me alias. For example, users/me/spaces/{space}/threads/{thread}/threadReadState .

  • Their Workspace email address. For example, users/user@example.com/spaces/{space}/threads/{thread}/threadReadState .

  • Their user id. For example, users/123456789/spaces/{space}/threads/{thread}/threadReadState .

Format: users/{user}/spaces/{space}/threads/{thread}/threadReadState

Группа

A Google Group in Google Chat.

Fields
name

string

Resource name for a Google Group.

Represents a group in Cloud Identity Groups API.

Format: groups/{group}

HistoryState

The history state for messages and spaces. Specifies how long messages and conversation threads are kept after creation.

Перечисления
HISTORY_STATE_UNSPECIFIED Значение по умолчанию. Не используйте.
HISTORY_OFF History off. Messages and threads are kept for 24 hours .
HISTORY_ON History on. The organization's Vault retention rules specify for how long messages and threads are kept.

ListMembershipsRequest

Request message for listing memberships.

Fields
parent

string

Необходимый. The resource name of the space for which to fetch a membership list.

Format: spaces/{space}

page_size

int32

Необязательный. The maximum number of memberships to return. The service might return fewer than this value.

If unspecified, at most 100 memberships are returned.

The maximum value is 1000. If you use a value more than 1000, it's automatically changed to 1000.

Negative values return an INVALID_ARGUMENT error.

page_token

string

Необязательный. A page token, received from a previous call to list memberships. Provide this parameter to retrieve the subsequent page.

When paginating, all other parameters provided should match the call that provided the page token. Passing different values to the other parameters might lead to unexpected results.

filter

string

Необязательный. A query filter.

You can filter memberships by a member's role ( role ) and type ( member.type ).

To filter by role, set role to ROLE_MEMBER or ROLE_MANAGER .

To filter by type, set member.type to HUMAN or BOT . Developer Preview: You can also filter for member.type using the != operator.

To filter by both role and type, use the AND operator. To filter by either role or type, use the OR operator.

Either member.type = "HUMAN" or member.type != "BOT" is required when use_admin_access is set to true. Other member type filters will be rejected.

For example, the following queries are valid:

role = "ROLE_MANAGER" OR role = "ROLE_MEMBER"
member.type = "HUMAN" AND role = "ROLE_MANAGER"

member.type != "BOT"

The following queries are invalid:

member.type = "HUMAN" AND member.type = "BOT"
role = "ROLE_MANAGER" AND role = "ROLE_MEMBER"

Invalid queries are rejected by the server with an INVALID_ARGUMENT error.

show_groups

bool

Необязательный. When true , also returns memberships associated with a Google Group , in addition to other types of memberships. If a filter is set, Google Group memberships that don't match the filter criteria aren't returned.

show_invited

bool

Необязательный. When true , also returns memberships associated with invited members, in addition to other types of memberships. If a filter is set, invited memberships that don't match the filter criteria aren't returned.

Currently requires user authentication .

use_admin_access

bool

When true , the method runs using the user's Google Workspace administrator privileges.

The calling user must be a Google Workspace administrator with the manage chat and spaces conversations privilege .

Requires either the chat.admin.memberships.readonly or chat.admin.memberships OAuth 2.0 scope .

Listing app memberships in a space isn't supported when using admin access.

ListMembershipsResponse

Response to list memberships of the space.

Fields
memberships[]

Membership

Unordered list. List of memberships in the requested (or first) page.

next_page_token

string

A token that you can send as pageToken to retrieve the next page of results. If empty, there are no subsequent pages.

ListMessagesRequest

Lists messages in the specified space, that the user is a member of.

Поля
parent

string

Необходимый. The resource name of the space to list messages from.

Format: spaces/{space}

page_size

int32

The maximum number of messages returned. The service might return fewer messages than this value.

If unspecified, at most 25 are returned.

The maximum value is 1000. If you use a value more than 1000, it's automatically changed to 1000.

Negative values return an INVALID_ARGUMENT error.

page_token

string

Optional, if resuming from a previous query.

A page token received from a previous list messages call. Provide this parameter to retrieve the subsequent page.

When paginating, all other parameters provided should match the call that provided the page token. Passing different values to the other parameters might lead to unexpected results.

filter

string

A query filter.

You can filter messages by date ( create_time ) and thread ( thread.name ).

To filter messages by the date they were created, specify the create_time with a timestamp in RFC-3339 format and double quotation marks. For example, "2023-04-21T11:30:00-04:00" . You can use the greater than operator > to list messages that were created after a timestamp, or the less than operator < to list messages that were created before a timestamp. To filter messages within a time interval, use the AND operator between two timestamps.

To filter by thread, specify the thread.name , formatted as spaces/{space}/threads/{thread} . You can only specify one thread.name per query.

To filter by both thread and date, use the AND operator in your query.

For example, the following queries are valid:

create_time > "2012-04-21T11:30:00-04:00"

create_time > "2012-04-21T11:30:00-04:00" AND
  thread.name = spaces/AAAAAAAAAAA/threads/123

create_time > "2012-04-21T11:30:00+00:00" AND

create_time < "2013-01-01T00:00:00+00:00" AND
  thread.name = spaces/AAAAAAAAAAA/threads/123

thread.name = spaces/AAAAAAAAAAA/threads/123

Invalid queries are rejected by the server with an INVALID_ARGUMENT error.

order_by

string

Optional, if resuming from a previous query.

How the list of messages is ordered. Specify a value to order by an ordering operation. Valid ordering operation values are as follows:

  • ASC for ascending.

  • DESC for descending.

The default ordering is create_time ASC .

show_deleted

bool

Whether to include deleted messages. Deleted messages include deleted time and metadata about their deletion, but message content is unavailable.

ListMessagesResponse

Response message for listing messages.

Fields
messages[]

Message

List of messages.

next_page_token

string

You can send a token as pageToken to retrieve the next page of results. If empty, there are no subsequent pages.

ListReactionsRequest

Lists reactions to a message.

Fields
parent

string

Необходимый. The message users reacted to.

Format: spaces/{space}/messages/{message}

page_size

int32

Необязательный. The maximum number of reactions returned. The service can return fewer reactions than this value. If unspecified, the default value is 25. The maximum value is 200; values above 200 are changed to 200.

page_token

string

Необязательный. (If resuming from a previous query.)

A page token received from a previous list reactions call. Provide this to retrieve the subsequent page.

When paginating, the filter value should match the call that provided the page token. Passing a different value might lead to unexpected results.

filter

string

Необязательный. A query filter.

You can filter reactions by emoji (either emoji.unicode or emoji.custom_emoji.uid ) and user ( user.name ).

To filter reactions for multiple emojis or users, join similar fields with the OR operator, such as emoji.unicode = "🙂" OR emoji.unicode = "👍" and user.name = "users/AAAAAA" OR user.name = "users/BBBBBB" .

To filter reactions by emoji and user, use the AND operator, such as emoji.unicode = "🙂" AND user.name = "users/AAAAAA" .

If your query uses both AND and OR , group them with parentheses.

For example, the following queries are valid:

user.name = "users/{user}"
emoji.unicode = "🙂"
emoji.custom_emoji.uid = "{uid}"
emoji.unicode = "🙂" OR emoji.unicode = "👍"
emoji.unicode = "🙂" OR emoji.custom_emoji.uid = "{uid}"
emoji.unicode = "🙂" AND user.name = "users/{user}"
(emoji.unicode = "🙂" OR emoji.custom_emoji.uid = "{uid}")
AND user.name = "users/{user}"

The following queries are invalid:

emoji.unicode = "🙂" AND emoji.unicode = "👍"
emoji.unicode = "🙂" AND emoji.custom_emoji.uid = "{uid}"
emoji.unicode = "🙂" OR user.name = "users/{user}"
emoji.unicode = "🙂" OR emoji.custom_emoji.uid = "{uid}" OR
user.name = "users/{user}"
emoji.unicode = "🙂" OR emoji.custom_emoji.uid = "{uid}"
AND user.name = "users/{user}"

Invalid queries are rejected by the server with an INVALID_ARGUMENT error.

ListReactionsResponse

Response to a list reactions request.

Fields
reactions[]

Reaction

List of reactions in the requested (or first) page.

next_page_token

string

Continuation token to retrieve the next page of results. It's empty for the last page of results.

ListSpaceEventsRequest

Request message for listing space events.

Fields
parent

string

Необходимый. Resource name of the Google Chat space where the events occurred.

Format: spaces/{space} .

page_size

int32

Необязательный. The maximum number of space events returned. The service might return fewer than this value.

Negative values return an INVALID_ARGUMENT error.

page_token

string

A page token, received from a previous list space events call. Provide this to retrieve the subsequent page.

When paginating, all other parameters provided to list space events must match the call that provided the page token. Passing different values to the other parameters might lead to unexpected results.

filter

string

Необходимый. A query filter.

You must specify at least one event type ( event_type ) using the has : operator. To filter by multiple event types, use the OR operator. Omit batch event types in your filter. The request automatically returns any related batch events. For example, if you filter by new reactions ( google.workspace.chat.reaction.v1.created ), the server also returns batch new reactions events ( google.workspace.chat.reaction.v1.batchCreated ). For a list of supported event types, see the SpaceEvents reference documentation .

Optionally, you can also filter by start time ( start_time ) and end time ( end_time ):

  • start_time : Exclusive timestamp from which to start listing space events. You can list events that occurred up to 28 days ago. If unspecified, lists space events from the past 28 days.
  • end_time : Inclusive timestamp until which space events are listed. If unspecified, lists events up to the time of the request.

To specify a start or end time, use the equals = operator and format in RFC-3339 . To filter by both start_time and end_time , use the AND operator.

For example, the following queries are valid:

start_time="2023-08-23T19:20:33+00:00" AND
end_time="2023-08-23T19:21:54+00:00"
start_time="2023-08-23T19:20:33+00:00" AND
(event_types:"google.workspace.chat.space.v1.updated" OR
event_types:"google.workspace.chat.message.v1.created")

The following queries are invalid:

start_time="2023-08-23T19:20:33+00:00" OR
end_time="2023-08-23T19:21:54+00:00"
event_types:"google.workspace.chat.space.v1.updated" AND
event_types:"google.workspace.chat.message.v1.created"

Invalid queries are rejected by the server with an INVALID_ARGUMENT error.

ListSpaceEventsResponse

Response message for listing space events.

Fields
space_events[]

SpaceEvent

Results are returned in chronological order (oldest event first).

next_page_token

string

Continuation token used to fetch more events. If this field is omitted, there are no subsequent pages.

ListSpacesRequest

A request to list the spaces the caller is a member of.

Fields
page_size

int32

Необязательный. The maximum number of spaces to return. The service might return fewer than this value.

If unspecified, at most 100 spaces are returned.

The maximum value is 1000. If you use a value more than 1000, it's automatically changed to 1000.

Negative values return an INVALID_ARGUMENT error.

page_token

string

Необязательный. A page token, received from a previous list spaces call. Provide this parameter to retrieve the subsequent page.

When paginating, the filter value should match the call that provided the page token. Passing a different value may lead to unexpected results.

filter

string

Необязательный. A query filter.

You can filter spaces by the space type ( space_type ).

To filter by space type, you must specify valid enum value, such as SPACE or GROUP_CHAT (the space_type can't be SPACE_TYPE_UNSPECIFIED ). To query for multiple space types, use the OR operator.

For example, the following queries are valid:

space_type = "SPACE"
spaceType = "GROUP_CHAT" OR spaceType = "DIRECT_MESSAGE"

Invalid queries are rejected by the server with an INVALID_ARGUMENT error.

ListSpacesResponse

The response for a list spaces request.

Fields
spaces[]

Space

List of spaces in the requested (or first) page.

next_page_token

string

You can send a token as pageToken to retrieve the next page of results. If empty, there are no subsequent pages.

MatchedUrl

A matched URL in a Chat message. Chat apps can preview matched URLs. For more information, see Preview links .

Fields
url

string

Только вывод. The URL that was matched.

Членство

Represents a membership relation in Google Chat, such as whether a user or Chat app is invited to, part of, or absent from a space.

Fields
name

string

Resource name of the membership, assigned by the server.

Format: spaces/{space}/members/{member}

state

MembershipState

Только вывод. State of the membership.

role

MembershipRole

Необязательный. User's role within a Chat space, which determines their permitted actions in the space.

This field can only be used as input in UpdateMembership .

create_time

Timestamp

Необязательный. Immutable. The creation time of the membership, such as when a member joined or was invited to join a space. This field is output only, except when used to import historical memberships in import mode spaces.

delete_time

Timestamp

Необязательный. Immutable. The deletion time of the membership, such as when a member left or was removed from a space. This field is output only, except when used to import historical memberships in import mode spaces.

Union field memberType . Member associated with this membership. Other member types might be supported in the future. memberType can be only one of the following:
member

User

The Google Chat user or app the membership corresponds to. If your Chat app authenticates as a user , the output populates the user name and type .

group_member

Group

The Google Group the membership corresponds to.

MembershipRole

Represents a user's permitted actions in a Chat space. More enum values might be added in the future.

Перечисления
MEMBERSHIP_ROLE_UNSPECIFIED Значение по умолчанию. For users : they aren't a member of the space, but can be invited. For Google Groups : they're always assigned this role (other enum values might be used in the future).
ROLE_MEMBER A member of the space. The user has basic permissions, like sending messages to the space. In 1:1 and unnamed group conversations, everyone has this role.
ROLE_MANAGER A space manager. The user has all basic permissions plus administrative permissions that let them manage the space, like adding or removing members. Only supported in SpaceType.SPACE .

MembershipState

Specifies the member's relationship with a space. Other membership states might be supported in the future.

Перечисления
MEMBERSHIP_STATE_UNSPECIFIED Значение по умолчанию. Не используйте.
JOINED The user is added to the space, and can participate in the space.
INVITED The user is invited to join the space, but hasn't joined it.
NOT_A_MEMBER The user doesn't belong to the space and doesn't have a pending invitation to join the space.

MembershipBatchCreatedEventData

Event payload for multiple new memberships.

Event type: google.workspace.chat.membership.v1.batchCreated

Fields
memberships[]

MembershipCreatedEventData

A list of new memberships.

MembershipBatchDeletedEventData

Event payload for multiple deleted memberships.

Event type: google.workspace.chat.membership.v1.batchDeleted

Fields
memberships[]

MembershipDeletedEventData

A list of deleted memberships.

MembershipBatchUpdatedEventData

Event payload for multiple updated memberships.

Event type: google.workspace.chat.membership.v1.batchUpdated

Fields
memberships[]

MembershipUpdatedEventData

A list of updated memberships.

MembershipCreatedEventData

Event payload for a new membership.

Event type: google.workspace.chat.membership.v1.created .

Fields
membership

Membership

The new membership.

MembershipDeletedEventData

Event payload for a deleted membership.

Event type: google.workspace.chat.membership.v1.deleted

Fields
membership

Membership

The deleted membership. Only the name and state fields are populated.

MembershipUpdatedEventData

Event payload for an updated membership.

Event type: google.workspace.chat.membership.v1.updated

Fields
membership

Membership

The updated membership.

Сообщение

A message in a Google Chat space.

Fields
name

string

Resource name of the message.

Format: spaces/{space}/messages/{message}

Where {space} is the ID of the space where the message is posted and {message} is a system-assigned ID for the message. For example, spaces/AAAAAAAAAAA/messages/BBBBBBBBBBB.BBBBBBBBBBB .

If you set a custom ID when you create a message, you can use this ID to specify the message in a request by replacing {message} with the value from the clientAssignedMessageId field. For example, spaces/AAAAAAAAAAA/messages/client-custom-name . For details, see Name a message .

sender

User

Только вывод. The user who created the message. If your Chat app authenticates as a user , the output populates the user name and type .

create_time

Timestamp

Необязательный. Immutable. For spaces created in Chat, the time at which the message was created. This field is output only, except when used in import mode spaces.

For import mode spaces, set this field to the historical timestamp at which the message was created in the source in order to preserve the original creation time.

last_update_time

Timestamp

Только вывод. The time at which the message was last edited by a user. If the message has never been edited, this field is empty.

delete_time

Timestamp

Только вывод. The time at which the message was deleted in Google Chat. If the message is never deleted, this field is empty.

text

string

Plain-text body of the message. The first link to an image, video, or web page generates a preview chip . You can also @mention a Google Chat user , or everyone in the space.

To learn about creating text messages, see Send a text message .

formatted_text

string

Только вывод. Contains the message text with markups added to communicate formatting. This field might not capture all formatting visible in the UI, but includes the following:

  • Markup syntax for bold, italic, strikethrough, monospace, monospace block, and bulleted list.

  • User mentions using the format <users/{user}> .

  • Custom hyperlinks using the format <{url}|{rendered_text}> where the first string is the URL and the second is the rendered text—for example, <http://example.com|custom text> .

  • Custom emoji using the format :{emoji_name}: —for example, :smile: . This doesn't apply to Unicode emoji, such as U+1F600 for a grinning face emoji.

For more information, see View text formatting sent in a message

cards[]
(deprecated)

Card

Deprecated: Use cards_v2 instead.

Rich, formatted, and interactive cards that you can use to display UI elements such as: formatted texts, buttons, and clickable images. Cards are normally displayed below the plain-text body of the message. cards and cards_v2 can have a maximum size of 32 KB.

cards_v2[]

CardWithId

An array of cards .

Only Chat apps can create cards. If your Chat app authenticates as a user , the messages can't contain cards.

To learn about cards and how to create them, see Send card messages .

Создавайте и просматривайте карты с помощью Card Builder.

Откройте конструктор карточек

annotations[]

Annotation

Только вывод. Annotations associated with the text in this message.

thread

Thread

The thread the message belongs to. For example usage, see Start or reply to a message thread .

space

Space

If your Chat app authenticates as a user , the output populates the space name .

fallback_text

string

A plain-text description of the message's cards, used when the actual cards can't be displayed—for example, mobile notifications.

action_response

ActionResponse

Input only. Parameters that a Chat app can use to configure how its response is posted.

argument_text

string

Только вывод. Plain-text body of the message with all Chat app mentions stripped out.

slash_command

SlashCommand

Только вывод. Slash command information, if applicable.

attachment[]

Attachment

User-uploaded attachment.

matched_url

MatchedUrl

Только вывод. A URL in spaces.messages.text that matches a link preview pattern. For more information, see Preview links .

thread_reply

bool

Только вывод. When true , the message is a response in a reply thread. When false , the message is visible in the space's top-level conversation as either the first message of a thread or a message with no threaded replies.

If the space doesn't support reply in threads, this field is always false .

client_assigned_message_id

string

Необязательный. A custom ID for the message. You can use field to identify a message, or to get, delete, or update a message. To set a custom ID, specify the messageId field when you create the message. For details, see Name a message .

emoji_reaction_summaries[]

EmojiReactionSummary

Только вывод. The list of emoji reaction summaries on the message.

private_message_viewer

User

Immutable. Input for creating a message, otherwise output only. The user that can view the message. When set, the message is private and only visible to the specified user and the Chat app. Link previews and attachments aren't supported for private messages.

Only Chat apps can send private messages. If your Chat app authenticates as a user to send a message, the message can't be private and must omit this field.

For details, see Send private messages to Google Chat users .

deletion_metadata

DeletionMetadata

Только вывод. Information about a deleted message. A message is deleted when delete_time is set.

quoted_message_metadata

QuotedMessageMetadata

Только вывод. Information about a message that's quoted by a Google Chat user in a space. Google Chat users can quote a message to reply to it.

attached_gifs[]

AttachedGif

Только вывод. GIF images that are attached to the message.

accessory_widgets[]

AccessoryWidget

One or more interactive widgets that appear at the bottom of a message. You can add accessory widgets to messages that contain text, cards, or both text and cards. Not supported for messages that contain dialogs. For details, see Add interactive widgets at the bottom of a message .

Creating a message with accessory widgets requires app authentication .

MessageBatchCreatedEventData

Event payload for multiple new messages.

Event type: google.workspace.chat.message.v1.batchCreated

Fields
messages[]

MessageCreatedEventData

A list of new messages.

MessageBatchDeletedEventData

Event payload for multiple deleted messages.

Event type: google.workspace.chat.message.v1.batchDeleted

Fields
messages[]

MessageDeletedEventData

A list of deleted messages.

MessageBatchUpdatedEventData

Event payload for multiple updated messages.

Event type: google.workspace.chat.message.v1.batchUpdated

Fields
messages[]

MessageUpdatedEventData

A list of updated messages.

MessageCreatedEventData

Event payload for a new message.

Event type: google.workspace.chat.message.v1.created

Fields
message

Message

The new message.

MessageDeletedEventData

Event payload for a deleted message.

Event type: google.workspace.chat.message.v1.deleted

Fields
message

Message

The deleted message. Only the name , createTime , deleteTime , and deletionMetadata fields are populated.

MessageUpdatedEventData

Event payload for an updated message.

Event type: google.workspace.chat.message.v1.updated

Fields
message

Message

The updated message.

QuotedMessageMetadata

Information about a quoted message.

Поля
name

string

Только вывод. Resource name of the quoted message.

Format: spaces/{space}/messages/{message}

last_update_time

Timestamp

Только вывод. The timestamp when the quoted message was created or when the quoted message was last updated.

Реакция

A reaction to a message.

Fields
name

string

The resource name of the reaction.

Format: spaces/{space}/messages/{message}/reactions/{reaction}

user

User

Только вывод. The user who created the reaction.

emoji

Emoji

The emoji used in the reaction.

ReactionBatchCreatedEventData

Event payload for multiple new reactions.

Event type: google.workspace.chat.reaction.v1.batchCreated

Fields
reactions[]

ReactionCreatedEventData

A list of new reactions.

ReactionBatchDeletedEventData

Event payload for multiple deleted reactions.

Event type: google.workspace.chat.reaction.v1.batchDeleted

Fields
reactions[]

ReactionDeletedEventData

A list of deleted reactions.

ReactionCreatedEventData

Event payload for a new reaction.

Event type: google.workspace.chat.reaction.v1.created

Fields
reaction

Reaction

The new reaction.

ReactionDeletedEventData

Event payload for a deleted reaction.

Type: google.workspace.chat.reaction.v1.deleted

Fields
reaction

Reaction

The deleted reaction.

RichLinkMetadata

A rich link to a resource.

Fields
uri

string

The URI of this link.

data поля объединения. Data for the linked resource. data могут быть только одним из следующих:

RichLinkType

The rich link type. More types might be added in the future.

Перечисления
DRIVE_FILE A Google Drive rich link type.
CHAT_SPACE A Chat space rich link type. For example, a space smart chip.

SearchSpacesRequest

Request to search for a list of spaces based on a query.

Fields
use_admin_access

bool

When true , the method runs using the user's Google Workspace administrator privileges.

The calling user must be a Google Workspace administrator with the manage chat and spaces conversations privilege .

Requires either the chat.admin.spaces.readonly or chat.admin.spaces OAuth 2.0 scope .

This method currently only supports admin access, thus only true is accepted for this field.

page_size

int32

The maximum number of spaces to return. The service may return fewer than this value.

If unspecified, at most 100 spaces are returned.

The maximum value is 1000. If you use a value more than 1000, it's automatically changed to 1000.

page_token

string

A token, received from the previous search spaces call. Provide this parameter to retrieve the subsequent page.

When paginating, all other parameters provided should match the call that provided the page token. Passing different values to the other parameters might lead to unexpected results.

query

string

Необходимый. A search query.

You can search by using the following parameters:

  • create_time
  • customer
  • display_name
  • external_user_allowed
  • last_active_time
  • space_history_state
  • space_type

create_time and last_active_time accept a timestamp in RFC-3339 format and the supported comparison operators are: = , < , > , <= , >= .

customer is required and is used to indicate which customer to fetch spaces from. customers/my_customer is the only supported value.

display_name only accepts the HAS ( : ) operator. The text to match is first tokenized into tokens and each token is prefix-matched case-insensitively and independently as a substring anywhere in the space's display_name . For example, Fun Eve matches Fun event or The evening was fun , but not notFun event or even .

external_user_allowed accepts either true or false .

space_history_state only accepts values from the historyState field of a space resource.

space_type is required and the only valid value is SPACE .

Across different fields, only AND operators are supported. A valid example is space_type = "SPACE" AND display_name:"Hello" and an invalid example is space_type = "SPACE" OR display_name:"Hello" .

Among the same field, space_type doesn't support AND or OR operators. display_name , 'space_history_state', and 'external_user_allowed' only support OR operators. last_active_time and create_time support both AND and OR operators. AND can only be used to represent an interval, such as last_active_time < "2022-01-01T00:00:00+00:00" AND last_active_time > "2023-01-01T00:00:00+00:00" .

The following example queries are valid:

customer = "customers/my_customer" AND space_type = "SPACE"

customer = "customers/my_customer" AND space_type = "SPACE" AND
display_name:"Hello World"

customer = "customers/my_customer" AND space_type = "SPACE" AND
(last_active_time < "2020-01-01T00:00:00+00:00" OR last_active_time >
"2022-01-01T00:00:00+00:00")

customer = "customers/my_customer" AND space_type = "SPACE" AND
(display_name:"Hello World" OR display_name:"Fun event") AND
(last_active_time > "2020-01-01T00:00:00+00:00" AND last_active_time <
"2022-01-01T00:00:00+00:00")

customer = "customers/my_customer" AND space_type = "SPACE" AND
(create_time > "2019-01-01T00:00:00+00:00" AND create_time <
"2020-01-01T00:00:00+00:00") AND (external_user_allowed = "true") AND
(space_history_state = "HISTORY_ON" OR space_history_state = "HISTORY_OFF")
order_by

string

Необязательный. How the list of spaces is ordered.

Supported attributes to order by are:

  • membership_count.joined_direct_human_user_count — Denotes the count of human users that have directly joined a space.
  • last_active_time — Denotes the time when last eligible item is added to any topic of this space.
  • create_time — Denotes the time of the space creation.

Valid ordering operation values are:

  • ASC for ascending. Значение по умолчанию.

  • DESC for descending.

The supported syntax are:

  • membership_count.joined_direct_human_user_count DESC
  • membership_count.joined_direct_human_user_count ASC
  • last_active_time DESC
  • last_active_time ASC
  • create_time DESC
  • create_time ASC

SearchSpacesResponse

Response with a list of spaces corresponding to the search spaces request.

Fields
spaces[]

Space

A page of the requested spaces.

next_page_token

string

A token that can be used to retrieve the next page. If this field is empty, there are no subsequent pages.

total_size

int32

The total number of spaces that match the query, across all pages. If the result is over 10,000 spaces, this value is an estimate.

SetUpSpaceRequest

Request to create a space and add specified users to it.

Fields
space

Space

Необходимый. The Space.spaceType field is required.

To create a space, set Space.spaceType to SPACE and set Space.displayName . If you receive the error message ALREADY_EXISTS when setting up a space, try a different displayName . An existing space within the Google Workspace organization might already use this display name.

To create a group chat, set Space.spaceType to GROUP_CHAT . Don't set Space.displayName .

To create a 1:1 conversation between humans, set Space.spaceType to DIRECT_MESSAGE and set Space.singleUserBotDm to false . Don't set Space.displayName or Space.spaceDetails .

To create an 1:1 conversation between a human and the calling Chat app, set Space.spaceType to DIRECT_MESSAGE and Space.singleUserBotDm to true . Don't set Space.displayName or Space.spaceDetails .

If a DIRECT_MESSAGE space already exists, that space is returned instead of creating a new space.

request_id

string

Необязательный. A unique identifier for this request. A random UUID is recommended. Specifying an existing request ID returns the space created with that ID instead of creating a new space. Specifying an existing request ID from the same Chat app with a different authenticated user returns an error.

memberships[]

Membership

Необязательный. The Google Chat users or groups to invite to join the space. Omit the calling user, as they are added automatically.

The set currently allows up to 20 memberships (in addition to the caller).

For human membership, the Membership.member field must contain a user with name populated (format: users/{user} ) and type set to User.Type.HUMAN . You can only add human users when setting up a space (adding Chat apps is only supported for direct message setup with the calling app). You can also add members using the user's email as an alias for {user}. For example, the user.name can be users/example@gmail.com . To invite Gmail users or users from external Google Workspace domains, user's email must be used for {user} .

For Google group membership, the Membership.group_member field must contain a group with name populated (format groups/{group} ). You can only add Google groups when setting Space.spaceType to SPACE .

Optional when setting Space.spaceType to SPACE .

Required when setting Space.spaceType to GROUP_CHAT , along with at least two memberships.

Required when setting Space.spaceType to DIRECT_MESSAGE with a human user, along with exactly one membership.

Must be empty when creating a 1:1 conversation between a human and the calling Chat app (when setting Space.spaceType to DIRECT_MESSAGE and Space.singleUserBotDm to true ).

SlashCommand

A slash command in Google Chat.

Fields
command_id

int64

The ID of the slash command invoked.

SlashCommandMetadata

Annotation metadata for slash commands (/).

Fields
bot

User

The Chat app whose command was invoked.

type

Type

The type of slash command.

command_name

string

The name of the invoked slash command.

command_id

int64

The command ID of the invoked slash command.

triggers_dialog

bool

Indicates whether the slash command is for a dialog.

Тип

Перечисления
TYPE_UNSPECIFIED Default value for the enum. Не используйте.
ADD Add Chat app to space.
INVOKE Invoke slash command in space.

Космос

A space in Google Chat. Spaces are conversations between two or more users or 1:1 messages between a user and a Chat app.

Fields
name

string

Resource name of the space.

Format: spaces/{space}

type
(deprecated)

Type

Только вывод. Deprecated: Use space_type instead. The type of a space.

space_type

SpaceType

The type of space. Required when creating a space or updating the space type of a space. Output only for other usage.

single_user_bot_dm

bool

Необязательный. Whether the space is a DM between a Chat app and a single human.

threaded
(deprecated)

bool

Только вывод. Deprecated: Use spaceThreadingState instead. Whether messages are threaded in this space.

display_name

string

The space's display name. Required when creating a space . If you receive the error message ALREADY_EXISTS when creating a space or updating the displayName , try a different displayName . An existing space within the Google Workspace organization might already use this display name.

For direct messages, this field might be empty.

Supports up to 128 characters.

external_user_allowed

bool

Immutable. Whether this space permits any Google Chat user as a member. Input when creating a space in a Google Workspace organization. Omit this field when creating spaces in the following conditions:

  • The authenticated user uses a consumer account (unmanaged user account). By default, a space created by a consumer account permits any Google Chat user.

For existing spaces, this field is output only.

space_threading_state

SpaceThreadingState

Только вывод. The threading state in the Chat space.

space_details

SpaceDetails

Details about the space including description and rules.

space_history_state

HistoryState

The message history state for messages and threads in this space.

import_mode

bool

Необязательный. Whether this space is created in Import Mode as part of a data migration into Google Workspace. While spaces are being imported, they aren't visible to users until the import is complete.

create_time

Timestamp

Необязательный. Immutable. For spaces created in Chat, the time the space was created. This field is output only, except when used in import mode spaces.

For import mode spaces, set this field to the historical timestamp at which the space was created in the source in order to preserve the original creation time.

Only populated in the output when spaceType is GROUP_CHAT or SPACE .

last_active_time

Timestamp

Только вывод. Timestamp of the last message in the space.

admin_installed

bool

Только вывод. For direct message (DM) spaces with a Chat app, whether the space was created by a Google Workspace administrator. Administrators can install and set up a direct message with a Chat app on behalf of users in their organization.

To support admin install, your Chat app must feature direct messaging.

membership_count

MembershipCount

Только вывод. The count of joined memberships grouped by member type. Populated when the space_type is SPACE , DIRECT_MESSAGE or GROUP_CHAT .

access_settings

AccessSettings

Необязательный. Specifies the access setting of the space. Only populated when the space_type is SPACE .

space_uri

string

Только вывод. The URI for a user to access the space.

Union field space_permission_settings . Represents the permission settings of a space. Only populated when the space_type is SPACE . space_permission_settings can be only one of the following:
predefined_permission_settings

PredefinedPermissionSettings

Необязательный. Input only. Space permission settings. Input for creating a space, a collaboration space is created if this field is not set. After you create the space, settings are populated in the PermissionSettings field.

permission_settings

PermissionSettings

Необязательный. Exact permission settings which can be set to update the space. Input for updating a space. Otherwise, output only. For space creation, use predefined_permission_settings instead.

AccessSettings

Represents the access setting of the space.

Fields
access_state

AccessState

Только вывод. Indicates the access state of the space.

audience

string

Необязательный. The resource name of the target audience who can discover the space, join the space, and preview the messages in the space. If unset, only users or Google Groups who have been individually invited or added to the space can access it. For details, see Make a space discoverable to a target audience .

Format: audiences/{audience}

To use the default target audience for the Google Workspace organization, set to audiences/default .

AccessState

Represents the access state of the space.

Перечисления
ACCESS_STATE_UNSPECIFIED Access state is unknown or not supported in this API.
PRIVATE Only users or Google Groups that have been individually added or invited by other users or Google Workspace administrators can discover and access the space.
DISCOVERABLE A space manager has granted a target audience access to the space. Users or Google Groups that have been individually added or invited to the space can also discover and access the space. To learn more, see Make a space discoverable to specific users .

MembershipCount

Represents the count of memberships of a space, grouped into categories.

Fields
joined_direct_human_user_count

int32

Count of human users that have directly joined the space, not counting users joined by having membership in a joined group.

joined_group_count

int32

Count of all groups that have directly joined the space.

PermissionSetting

Represents a space permission setting.

Fields
managers_allowed

bool

Whether spaces managers have this permission.

members_allowed

bool

Whether non-manager members have this permission.

PermissionSettings

Permission settings for a named space. To set permission settings when creating a space, specify the PredefinedPermissionSettings field in your request.

Fields
manage_members_and_groups

PermissionSetting

Setting for managing members and groups in a space.

modify_space_details

PermissionSetting

Setting for updating space name, avatar, description and guidelines.

toggle_history

PermissionSetting

Setting for toggling space history on and off.

use_at_mention_all

PermissionSetting

Setting for using @all in a space.

manage_apps

PermissionSetting

Setting for managing apps in a space.

manage_webhooks

PermissionSetting

Setting for managing webhooks in a space.

post_messages

PermissionSetting

Только вывод. Setting for posting messages in a space.

reply_messages

PermissionSetting

Setting for replying to messages in a space.

PredefinedPermissionSettings

The space permission settings that you can specify when creating a named space. More settings might be added in the future. For details about permission settings for named spaces, see Learn about spaces .

Перечисления
PREDEFINED_PERMISSION_SETTINGS_UNSPECIFIED Не указано. Не используйте.
COLLABORATION_SPACE Setting to make the space a collaboration space where all members can post messages.
ANNOUNCEMENT_SPACE Setting to make the space an announcement space where only space managers can post messages.

SpaceDetails

Details about the space including description and rules.

Fields
description

string

Необязательный. A description of the space. For example, describe the space's discussion topic, functional purpose, or participants.

Supports up to 150 characters.

guidelines

string

Необязательный. The space's rules, expectations, and etiquette.

Supports up to 5,000 characters.

SpaceThreadingState

Specifies the type of threading state in the Chat space.

Перечисления
SPACE_THREADING_STATE_UNSPECIFIED Сдержанный.
THREADED_MESSAGES Named spaces that support message threads. When users respond to a message, they can reply in-thread, which keeps their response in the context of the original message.
GROUPED_MESSAGES Named spaces where the conversation is organized by topic. Topics and their replies are grouped together.
UNTHREADED_MESSAGES Direct messages (DMs) between two people and group conversations between 3 or more people.

SpaceType

The type of space. Required when creating or updating a space. Output only for other usage.

Перечисления
SPACE_TYPE_UNSPECIFIED Сдержанный.
SPACE A place where people send messages, share files, and collaborate. A SPACE can include Chat apps.
GROUP_CHAT Group conversations between 3 or more people. A GROUP_CHAT can include Chat apps.
DIRECT_MESSAGE 1:1 messages between two humans or a human and a Chat app.

Тип

Deprecated: Use SpaceType instead.

Перечисления
TYPE_UNSPECIFIED Сдержанный.
ROOM Conversations between two or more humans.
DM 1:1 Direct Message between a human and a Chat app, where all messages are flat. Note that this doesn't include direct messages between two humans.

SpaceBatchUpdatedEventData

Event payload for multiple updates to a space.

Event type: google.workspace.chat.space.v1.batchUpdated

Fields
spaces[]

SpaceUpdatedEventData

A list of updated spaces.

SpaceEvent

An event that represents a change or activity in a Google Chat space. To learn more, see Work with events from Google Chat .

Fields
name

string

Resource name of the space event.

Format: spaces/{space}/spaceEvents/{spaceEvent}

event_time

Timestamp

Time when the event occurred.

event_type

string

Type of space event. Each event type has a batch version, which represents multiple instances of the event type that occur in a short period of time. For spaceEvents.list() requests, omit batch event types in your query filter. By default, the server returns both event type and its batch version.

Supported event types for messages :

  • New message: google.workspace.chat.message.v1.created
  • Updated message: google.workspace.chat.message.v1.updated
  • Deleted message: google.workspace.chat.message.v1.deleted
  • Multiple new messages: google.workspace.chat.message.v1.batchCreated
  • Multiple updated messages: google.workspace.chat.message.v1.batchUpdated
  • Multiple deleted messages: google.workspace.chat.message.v1.batchDeleted

Supported event types for memberships :

  • New membership: google.workspace.chat.membership.v1.created
  • Updated membership: google.workspace.chat.membership.v1.updated
  • Deleted membership: google.workspace.chat.membership.v1.deleted
  • Multiple new memberships: google.workspace.chat.membership.v1.batchCreated
  • Multiple updated memberships: google.workspace.chat.membership.v1.batchUpdated
  • Multiple deleted memberships: google.workspace.chat.membership.v1.batchDeleted

Supported event types for reactions :

  • New reaction: google.workspace.chat.reaction.v1.created
  • Deleted reaction: google.workspace.chat.reaction.v1.deleted
  • Multiple new reactions: google.workspace.chat.reaction.v1.batchCreated
  • Multiple deleted reactions: google.workspace.chat.reaction.v1.batchDeleted

Supported event types about the space :

  • Updated space: google.workspace.chat.space.v1.updated
  • Multiple space updates: google.workspace.chat.space.v1.batchUpdated

Union field payload .

payload can be only one of the following:

message_created_event_data

MessageCreatedEventData

Event payload for a new message.

Event type: google.workspace.chat.message.v1.created

message_updated_event_data

MessageUpdatedEventData

Event payload for an updated message.

Event type: google.workspace.chat.message.v1.updated

message_deleted_event_data

MessageDeletedEventData

Event payload for a deleted message.

Event type: google.workspace.chat.message.v1.deleted

message_batch_created_event_data

MessageBatchCreatedEventData

Event payload for multiple new messages.

Event type: google.workspace.chat.message.v1.batchCreated

message_batch_updated_event_data

MessageBatchUpdatedEventData

Event payload for multiple updated messages.

Event type: google.workspace.chat.message.v1.batchUpdated

message_batch_deleted_event_data

MessageBatchDeletedEventData

Event payload for multiple deleted messages.

Event type: google.workspace.chat.message.v1.batchDeleted

space_updated_event_data

SpaceUpdatedEventData

Event payload for a space update.

Event type: google.workspace.chat.space.v1.updated

space_batch_updated_event_data

SpaceBatchUpdatedEventData

Event payload for multiple updates to a space.

Event type: google.workspace.chat.space.v1.batchUpdated

membership_created_event_data

MembershipCreatedEventData

Event payload for a new membership.

Event type: google.workspace.chat.membership.v1.created

membership_updated_event_data

MembershipUpdatedEventData

Event payload for an updated membership.

Event type: google.workspace.chat.membership.v1.updated

membership_deleted_event_data

MembershipDeletedEventData

Event payload for a deleted membership.

Event type: google.workspace.chat.membership.v1.deleted

membership_batch_created_event_data

MembershipBatchCreatedEventData

Event payload for multiple new memberships.

Event type: google.workspace.chat.membership.v1.batchCreated

membership_batch_updated_event_data

MembershipBatchUpdatedEventData

Event payload for multiple updated memberships.

Event type: google.workspace.chat.membership.v1.batchUpdated

membership_batch_deleted_event_data

MembershipBatchDeletedEventData

Event payload for multiple deleted memberships.

Event type: google.workspace.chat.membership.v1.batchDeleted

reaction_created_event_data

ReactionCreatedEventData

Event payload for a new reaction.

Event type: google.workspace.chat.reaction.v1.created

reaction_deleted_event_data

ReactionDeletedEventData

Event payload for a deleted reaction.

Event type: google.workspace.chat.reaction.v1.deleted

reaction_batch_created_event_data

ReactionBatchCreatedEventData

Event payload for multiple new reactions.

Event type: google.workspace.chat.reaction.v1.batchCreated

reaction_batch_deleted_event_data

ReactionBatchDeletedEventData

Event payload for multiple deleted reactions.

Event type: google.workspace.chat.reaction.v1.batchDeleted

SpaceReadState

A user's read state within a space, used to identify read and unread messages.

Fields
name

string

Resource name of the space read state.

Format: users/{user}/spaces/{space}/spaceReadState

last_read_time

Timestamp

Необязательный. The time when the user's space read state was updated. Usually this corresponds with either the timestamp of the last read message, or a timestamp specified by the user to mark the last read position in a space.

SpaceUpdatedEventData

Event payload for an updated space.

Event type: google.workspace.chat.space.v1.updated

Fields
space

Space

The updated space.

Нить

A thread in a Google Chat space. For example usage, see Start or reply to a message thread .

If you specify a thread when creating a message, you can set the messageReplyOption field to determine what happens if no matching thread is found.

Fields
name

string

Resource name of the thread.

Example: spaces/{space}/threads/{thread}

thread_key

string

Необязательный. Input for creating or updating a thread. Otherwise, output only. ID for the thread. Supports up to 4000 characters.

This ID is unique to the Chat app that sets it. For example, if multiple Chat apps create a message using the same thread key, the messages are posted in different threads. To reply in a thread created by a person or another Chat app, specify the thread name field instead.

ThreadReadState

A user's read state within a thread, used to identify read and unread messages.

Fields
name

string

Resource name of the thread read state.

Format: users/{user}/spaces/{space}/threads/{thread}/threadReadState

last_read_time

Timestamp

The time when the user's thread read state was updated. Usually this corresponds with the timestamp of the last read message in a thread.

UpdateMembershipRequest

Request message for updating a membership.

Fields
membership

Membership

Необходимый. The membership to update. Only fields specified by update_mask are updated.

update_mask

FieldMask

Необходимый. The field paths to update. Separate multiple values with commas or use * to update all field paths.

Currently supported field paths:

  • role
use_admin_access

bool

When true , the method runs using the user's Google Workspace administrator privileges.

The calling user must be a Google Workspace administrator with the manage chat and spaces conversations privilege .

Requires the chat.admin.memberships OAuth 2.0 scope .

UpdateMessageRequest

Request to update a message.

Fields
message

Message

Необходимый. Message with fields updated.

update_mask

FieldMask

Необходимый. The field paths to update. Separate multiple values with commas or use * to update all field paths.

Currently supported field paths:

allow_missing

bool

Необязательный. If true and the message isn't found, a new message is created and updateMask is ignored. The specified message ID must be client-assigned or the request fails.

UpdateSpaceReadStateRequest

Request message for UpdateSpaceReadState API.

Fields
space_read_state

SpaceReadState

Необходимый. The space read state and fields to update.

Only supports updating read state for the calling user.

To refer to the calling user, set one of the following:

  • The me alias. For example, users/me/spaces/{space}/spaceReadState .

  • Their Workspace email address. For example, users/user@example.com/spaces/{space}/spaceReadState .

  • Their user id. For example, users/123456789/spaces/{space}/spaceReadState .

Format: users/{user}/spaces/{space}/spaceReadState

update_mask

FieldMask

Необходимый. The field paths to update. Currently supported field paths:

  • last_read_time

When the last_read_time is before the latest message create time, the space appears as unread in the UI.

To mark the space as read, set last_read_time to any value later (larger) than the latest message create time. The last_read_time is coerced to match the latest message create time. Note that the space read state only affects the read state of messages that are visible in the space's top-level conversation. Replies in threads are unaffected by this timestamp, and instead rely on the thread read state.

UpdateSpaceRequest

A request to update a single space.

Fields
space

Space

Необходимый. Space with fields to be updated. Space.name must be populated in the form of spaces/{space} . Only fields specified by update_mask are updated.

update_mask

FieldMask

Необходимый. The updated field paths, comma separated if there are multiple.

You can update the following fields for a space:

  • space_details

  • display_name : Only supports updating the display name for spaces where spaceType field is SPACE . If you receive the error message ALREADY_EXISTS , try a different value. An existing space within the Google Workspace organization might already use this display name.

  • space_type : Only supports changing a GROUP_CHAT space type to SPACE . Include display_name together with space_type in the update mask and ensure that the specified space has a non-empty display name and the SPACE space type. Including the space_type mask and the SPACE type in the specified space when updating the display name is optional if the existing space already has the SPACE type. Trying to update the space type in other ways results in an invalid argument error. space_type is not supported with admin access.

  • space_history_state : Updates space history settings by turning history on or off for the space. Only supported if history settings are enabled for the Google Workspace organization. To update the space history state, you must omit all other field masks in your request. space_history_state is not supported with admin access.

  • access_settings.audience : Updates the access setting of who can discover the space, join the space, and preview the messages in named space where spaceType field is SPACE . If the existing space has a target audience, you can remove the audience and restrict space access by omitting a value for this field mask. To update access settings for a space, the authenticating user must be a space manager and omit all other field masks in your request. You can't update this field if the space is in import mode . To learn more, see Make a space discoverable to specific users . access_settings.audience is not supported with admin access.

  • Developer Preview: Supports changing the permission settings of a space, supported field paths include: permission_settings.manage_members_and_groups , permission_settings.modify_space_details , permission_settings.toggle_history , permission_settings.use_at_mention_all , permission_settings.manage_apps , permission_settings.manage_webhooks , permission_settings.reply_messages (Warning: mutually exclusive with all other non-permission settings field paths). permission_settings is not supported with admin access.

use_admin_access

bool

When true , the method runs using the user's Google Workspace administrator privileges.

The calling user must be a Google Workspace administrator with the manage chat and spaces conversations privilege .

Requires the chat.admin.spaces OAuth 2.0 scope .

Some FieldMask values are not supported using admin access. For details, see the description of update_mask .

Пользователь

A user in Google Chat. When returned as an output from a request, if your Chat app authenticates as a user , the output for a User resource only populates the user's name and type .

Fields
name

string

Resource name for a Google Chat user .

Format: users/{user} . users/app can be used as an alias for the calling app bot user.

For human users , {user} is the same user identifier as:

  • the id for the Person in the People API. For example, users/123456789 in Chat API represents the same person as the 123456789 Person profile ID in People API.

  • the id for a user in the Admin SDK Directory API.

  • the user's email address can be used as an alias for {user} in API requests. For example, if the People API Person profile ID for user@example.com is 123456789 , you can use users/user@example.com as an alias to reference users/123456789 . Only the canonical resource name (for example users/123456789 ) will be returned from the API.

display_name

string

Только вывод. The user's display name.

domain_id

string

Unique identifier of the user's Google Workspace domain.

type

Type

User type.

is_anonymous

bool

Только вывод. When true , the user is deleted or their profile is not visible.

Тип

Перечисления
TYPE_UNSPECIFIED Default value for the enum. НЕ ИСПОЛЬЗУЙТЕ.
HUMAN Human user.
BOT Chat app user.

UserMentionMetadata

Annotation metadata for user mentions (@).

Fields
user

User

The user mentioned.

type

Type

The type of user mention.

Тип

Перечисления
TYPE_UNSPECIFIED Default value for the enum. Не используйте.
ADD Add user to space.
MENTION Mention user in space.

WidgetMarkup

A widget is a UI element that presents text and images.

Fields
buttons[]

Button

Список кнопок. Buttons is also oneof data and only one of these fields should be set.

data поля объединения. A WidgetMarkup can only have one of the following items. You can use multiple WidgetMarkup fields to display more items. data могут быть только одним из следующих:
text_paragraph

TextParagraph

Display a text paragraph in this widget.

image

Image

Display an image in this widget.

key_value

KeyValue

Display a key value item in this widget.

Кнопка

Кнопка. Can be a text button or an image button.

Fields

Union field type .

type can be only one of the following:

text_button

TextButton

A button with text and onclick action.

image_button

ImageButton

A button with image and onclick action.

FormAction

A form action describes the behavior when the form is submitted. For example, you can invoke Apps Script to handle the form.

Fields
action_method_name

string

The method name is used to identify which part of the form triggered the form submission. This information is echoed back to the Chat app as part of the card click event. You can use the same method name for several elements that trigger a common behavior.

parameters[]

ActionParameter

Список параметров действия.

Параметр действия

Список строковых параметров, которые необходимо указать при вызове метода действия. For example, consider three snooze buttons: snooze now, snooze one day, snooze next week. Вы можете использовать action method = snooze() , передав тип и время повтора в списке строковых параметров.

Fields
key

string

Имя параметра сценария действия.

value

string

Значение параметра.

Икона

The set of supported icons.

Перечисления
ICON_UNSPECIFIED
AIRPLANE
BOOKMARK
BUS
CAR
CLOCK
CONFIRMATION_NUMBER_ICON
DOLLAR
DESCRIPTION
EMAIL
EVENT_PERFORMER
EVENT_SEAT
FLIGHT_ARRIVAL
FLIGHT_DEPARTURE
HOTEL
HOTEL_ROOM_TYPE
INVITE
MAP_PIN
MEMBERSHIP
MULTIPLE_PEOPLE
OFFER
PERSON
PHONE
RESTAURANT_ICON
SHOPPING_CART
STAR
STORE
TICKET
TRAIN
VIDEO_CAMERA
VIDEO_PLAY

Изображение

An image that's specified by a URL and can have an onclick action.

Fields
image_url

string

The URL of the image.

on_click

OnClick

The onclick action.

aspect_ratio

double

The aspect ratio of this image (width and height). This field lets you reserve the right height for the image while waiting for it to load. It's not meant to override the built-in aspect ratio of the image. If unset, the server fills it by prefetching the image.

ImageButton

An image button with an onclick action.

Fields
on_click

OnClick

The onclick action.

name

string

The name of this image_button that's used for accessibility. Default value is provided if this name isn't specified.

icons полей Союза. The icon can be specified by an Icon enum or a URL. icons могут быть только одним из следующих:
icon

Icon

The icon specified by an enum that indices to an icon provided by Chat API.

icon_url

string

The icon specified by a URL.

KeyValue

A UI element contains a key (label) and a value (content). This element can also contain some actions such as onclick button.

Fields
top_label

string

The text of the top label. Formatted text supported. Дополнительную информацию о форматировании текста см. в разделах «Форматирование текста в приложениях Google Chat» и «Форматирование текста в надстройках Google Workspace» .

content

string

The text of the content. Formatted text supported and always required. Дополнительную информацию о форматировании текста см. в разделах «Форматирование текста в приложениях Google Chat» и «Форматирование текста в надстройках Google Workspace» .

content_multiline

bool

If the content should be multiline.

bottom_label

string

The text of the bottom label. Formatted text supported. Дополнительную информацию о форматировании текста см. в разделах «Форматирование текста в приложениях Google Chat» и «Форматирование текста в надстройках Google Workspace» .

on_click

OnClick

The onclick action. Only the top label, bottom label, and content region are clickable.

icons полей Союза. At least one of icons, top_label and bottom_label must be defined. icons могут быть только одним из следующих:
icon

Icon

An enum value that's replaced by the Chat API with the corresponding icon image.

icon_url

string

The icon specified by a URL.

Полевой control Союза. A control widget. You can set either button or switch_widget , but not both. control может быть только одним из следующих:
button

Button

A button that can be clicked to trigger an action.

OnClick

An onclick action (for example, open a link).

Fields

data поля объединения.

data могут быть только одним из следующих:

action

FormAction

A form action is triggered by this onclick action if specified.

TextButton

A button with text and onclick action.

Fields
text

string

The text of the button.

on_click

OnClick

The onclick action of the button.

TextParagraph

A paragraph of text. Formatted text supported. Дополнительную информацию о форматировании текста см. в разделах «Форматирование текста в приложениях Google Chat» и «Форматирование текста в надстройках Google Workspace» .

Fields
text

string