Отправьте сообщение с помощью Google Chat API

В этом руководстве объясняется, как вызвать метод messages.create() Google Chat API, чтобы выполнить любое из следующих действий:

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

Максимальный размер сообщения (включая любой текст и карточки) — 32 000 байт. Чтобы отправить сообщение, размер которого превышает этот размер, ваше приложение Chat должно вместо этого отправить несколько сообщений.

Помимо вызова метода messages.create() , приложения чата могут создавать и отправлять сообщения в ответ на действия пользователя, например публиковать приветственное сообщение после того, как пользователь добавляет приложение чата в пространство. При ответе на взаимодействие приложения чата могут использовать другие типы функций обмена сообщениями, включая интерактивные диалоги и интерфейсы предварительного просмотра ссылок. Чтобы ответить пользователю, приложение Chat возвращает сообщение синхронно, без вызова API Chat. Подробнее об отправке сообщений в ответ на взаимодействие см. в разделе Получение и ответ на взаимодействие с помощью приложения Google Chat .

Как Chat отображает и атрибутирует сообщения, созданные с помощью Chat API

Вы можете вызвать метод messages.create() используя аутентификацию приложения и аутентификацию пользователя . Chat атрибутирует отправителя сообщения по-разному в зависимости от используемого типа аутентификации.

Когда вы проходите аутентификацию в приложении Chat, приложение Chat отправляет сообщение.

Вызов метода messages.create() с аутентификацией приложения.
Рисунок 1. При аутентификации приложения приложение Chat отправляет сообщение. Чтобы отметить, что отправитель не является человеком, рядом с именем Chat отображается App .

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

Вызов метода messages.create() с аутентификацией пользователя.
Рисунок 2. При аутентификации пользователя пользователь отправляет сообщение, а Chat отображает имя приложения Chat рядом с именем пользователя.

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

В этом руководстве объясняется, как использовать любой тип аутентификации для отправки сообщения с помощью Chat API.

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

Node.js

Питон

Ява

Скрипт приложений

Отправьте сообщение через приложение чата

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

Сообщение отправлено с аутентификацией приложения
Рис. 4. Приложение Chat отправляет сообщение с текстом, карточкой и дополнительной кнопкой.

Чтобы вызвать messages.create() с использованием аутентификации приложения, необходимо указать в запросе следующие поля:

  • Область авторизации chat.bot .
  • Ресурс Space , в котором вы хотите разместить сообщение. Приложение Chat должно быть участником пространства.
  • Ресурс Message , который необходимо создать. Чтобы определить содержимое сообщения, вы можете включить форматированный текст ( text ), один или несколько интерфейсов карты ( cardsV2 ) или оба.

По желанию вы можете включить следующее:

В следующем коде показан пример того, как приложение Chat может отправить сообщение, опубликованное как приложение Chat, содержащее текст, карточку и кнопку, на которую можно нажать, внизу сообщения:

Node.js

чат/клиент-библиотеки/облако/create-message-app-cred.js
import {createClientWithAppCredentials} from './authentication-utils.js';

// This sample shows how to create message with app credential
async function main() {
  // Create a client
  const chatClient = createClientWithAppCredentials();

  // Initialize request argument(s)
  const request = {
    // Replace SPACE_NAME here.
    parent: 'spaces/SPACE_NAME',
    message: {
      text: '👋🌎 Hello world! I created this message by calling ' +
            'the Chat API\'s `messages.create()` method.',
      cardsV2 : [{ card: {
        header: {
          title: 'About this message',
          imageUrl: 'https://fonts.gstatic.com/s/i/short-term/release/googlesymbols/info/default/24px.svg'
        },
        sections: [{
          header: 'Contents',
          widgets: [{ textParagraph: {
              text: '🔡 <b>Text</b> which can include ' +
                    'hyperlinks 🔗, emojis 😄🎉, and @mentions 🗣️.'
            }}, { textParagraph: {
              text: '🖼️ A <b>card</b> to display visual elements' +
                    'and request information such as text 🔤, ' +
                    'dates and times 📅, and selections ☑️.'
            }}, { textParagraph: {
              text: '👉🔘 An <b>accessory widget</b> which adds ' +
                    'a button to the bottom of a message.'
            }}
          ]}, {
            header: "What's next",
            collapsible: true,
            widgets: [{ textParagraph: {
                text: "❤️ <a href='https://developers.google.com/workspace/chat/api/reference/rest/v1/spaces.messages.reactions/create'>Add a reaction</a>."
              }}, { textParagraph: {
                text: "🔄 <a href='https://developers.google.com/workspace/chat/api/reference/rest/v1/spaces.messages/patch'>Update</a> " +
                      "or  <a href='https://developers.google.com/workspace/chat/api/reference/rest/v1/spaces.messages/delete'>delete</a> " +
                      "the message."
              }
            }]
          }
        ]
      }}],
      accessoryWidgets: [{ buttonList: { buttons: [{
        text: 'View documentation',
        icon: { materialIcon: { name: 'link' }},
        onClick: { openLink: {
          url: 'https://developers.google.com/workspace/chat/create-messages'
        }}
      }]}}]
    }
  };

  // Make the request
  const response = await chatClient.createMessage(request);

  // Handle the response
  console.log(response);
}

main().catch(console.error);

Питон

чат/клиент-библиотеки/cloud/create_message_app_cred.py
from authentication_utils import create_client_with_app_credentials
from google.apps import chat_v1 as google_chat

# This sample shows how to create message with app credential
def create_message_with_app_cred():
    # Create a client
    client = create_client_with_app_credentials()

    # Initialize request argument(s)
    request = google_chat.CreateMessageRequest(
        # Replace SPACE_NAME here.
        parent = "spaces/SPACE_NAME",
        message = {
            "text": '👋🌎 Hello world! I created this message by calling ' +
                    'the Chat API\'s `messages.create()` method.',
            "cards_v2" : [{ "card": {
                "header": {
                    "title": 'About this message',
                    "image_url": 'https://fonts.gstatic.com/s/i/short-term/release/googlesymbols/info/default/24px.svg'
                },
                "sections": [{
                    "header": "Contents",
                    "widgets": [{ "text_paragraph": {
                            "text": '🔡 <b>Text</b> which can include ' +
                                    'hyperlinks 🔗, emojis 😄🎉, and @mentions 🗣️.'
                        }}, { "text_paragraph": {
                            "text": '🖼️ A <b>card</b> to display visual elements' +
                                    'and request information such as text 🔤, ' +
                                    'dates and times 📅, and selections ☑️.'
                        }}, { "text_paragraph": {
                            "text": '👉🔘 An <b>accessory widget</b> which adds ' +
                                    'a button to the bottom of a message.'
                        }}
                    ]}, {
                        "header": "What's next",
                        "collapsible": True,
                        "widgets": [{ "text_paragraph": {
                                "text": "❤️ <a href='https://developers.google.com/workspace/chat/api/reference/rest/v1/spaces.messages.reactions/create'>Add a reaction</a>."
                            }}, { "text_paragraph": {
                                "text": "🔄 <a href='https://developers.google.com/workspace/chat/api/reference/rest/v1/spaces.messages/patch'>Update</a> " +
                                        "or  <a href='https://developers.google.com/workspace/chat/api/reference/rest/v1/spaces.messages/delete'>delete</a> " +
                                        "the message."
                            }
                        }]
                    }
                ]
            }}],
            "accessory_widgets": [{ "button_list": { "buttons": [{
                "text": 'View documentation',
                "icon": { "material_icon": { "name": 'link' }},
                "on_click": { "open_link": {
                    "url": 'https://developers.google.com/workspace/chat/create-messages'
                }}
            }]}}]
        }
    )

    # Make the request
    response = client.create_message(request)

    # Handle the response
    print(response)

create_message_with_app_cred()

Ява

чат/клиент-библиотеки/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMessageAppCred.java
import com.google.apps.card.v1.Button;
import com.google.apps.card.v1.ButtonList;
import com.google.apps.card.v1.Card;
import com.google.apps.card.v1.Icon;
import com.google.apps.card.v1.MaterialIcon;
import com.google.apps.card.v1.OnClick;
import com.google.apps.card.v1.OpenLink;
import com.google.apps.card.v1.TextParagraph;
import com.google.apps.card.v1.Widget;
import com.google.apps.card.v1.Card.CardHeader;
import com.google.apps.card.v1.Card.Section;
import com.google.chat.v1.AccessoryWidget;
import com.google.chat.v1.CardWithId;
import com.google.chat.v1.ChatServiceClient;
import com.google.chat.v1.CreateMessageRequest;
import com.google.chat.v1.Message;

// This sample shows how to create message with app credential.
public class CreateMessageAppCred {

  public static void main(String[] args) throws Exception {
    try (ChatServiceClient chatServiceClient =
        AuthenticationUtils.createClientWithAppCredentials()) {
      CreateMessageRequest.Builder request = CreateMessageRequest.newBuilder()
        // Replace SPACE_NAME here.
        .setParent("spaces/SPACE_NAME")
        .setMessage(Message.newBuilder()
          .setText( "👋🌎 Hello world! I created this message by calling " +
                    "the Chat API\'s `messages.create()` method.")
          .addCardsV2(CardWithId.newBuilder().setCard(Card.newBuilder()
            .setHeader(CardHeader.newBuilder()
              .setTitle("About this message")
              .setImageUrl("https://fonts.gstatic.com/s/i/short-term/release/googlesymbols/info/default/24px.svg"))
            .addSections(Section.newBuilder()
              .setHeader("Contents")
              .addWidgets(Widget.newBuilder().setTextParagraph(TextParagraph.newBuilder().setText(
                "🔡 <b>Text</b> which can include " +
                "hyperlinks 🔗, emojis 😄🎉, and @mentions 🗣️.")))
              .addWidgets(Widget.newBuilder().setTextParagraph(TextParagraph.newBuilder().setText(
                "🖼️ A <b>card</b> to display visual elements " +
                "and request information such as text 🔤, " +
                "dates and times 📅, and selections ☑️.")))
              .addWidgets(Widget.newBuilder().setTextParagraph(TextParagraph.newBuilder().setText(
                "👉🔘 An <b>accessory widget</b> which adds " +
                "a button to the bottom of a message."))))
            .addSections(Section.newBuilder()
              .setHeader("What's next")
              .setCollapsible(true)
              .addWidgets(Widget.newBuilder().setTextParagraph(TextParagraph.newBuilder().setText(
                "❤️ <a href='https://developers.google.com/workspace/chat/api/reference/rest/v1/spaces.messages.reactions/create'>Add a reaction</a>.")))
              .addWidgets(Widget.newBuilder().setTextParagraph(TextParagraph.newBuilder().setText(
                "🔄 <a href='https://developers.google.com/workspace/chat/api/reference/rest/v1/spaces.messages/patch'>Update</a> " +
                "or  <a href='https://developers.google.com/workspace/chat/api/reference/rest/v1/spaces.messages/delete'>delete</a> " +
                "the message."))))))
          .addAccessoryWidgets(AccessoryWidget.newBuilder()
            .setButtonList(ButtonList.newBuilder()
              .addButtons(Button.newBuilder()
                .setText("View documentation")
                .setIcon(Icon.newBuilder()
                  .setMaterialIcon(MaterialIcon.newBuilder().setName("link")))
                .setOnClick(OnClick.newBuilder()
                  .setOpenLink(OpenLink.newBuilder()
                    .setUrl("https://developers.google.com/workspace/chat/create-messages")))))));
      Message response = chatServiceClient.createMessage(request.build());

      System.out.println(JsonFormat.printer().print(response));
    }
  }
}

Скрипт приложений

чат/расширенный сервис/Main.gs
/**
 * This sample shows how to create message with app credential
 * 
 * It relies on the OAuth2 scope 'https://www.googleapis.com/auth/chat.bot'
 * used by service accounts.
 */
function createMessageAppCred() {
  // Initialize request argument(s)
  // TODO(developer): Replace SPACE_NAME here.
  const parent = 'spaces/SPACE_NAME';
  const message = {
    text: '👋🌎 Hello world! I created this message by calling ' +
          'the Chat API\'s `messages.create()` method.',
    cardsV2 : [{ card: {
      header: {
        title: 'About this message',
        imageUrl: 'https://fonts.gstatic.com/s/i/short-term/release/googlesymbols/info/default/24px.svg'
      },
      sections: [{
        header: 'Contents',
        widgets: [{ textParagraph: {
            text: '🔡 <b>Text</b> which can include ' +
                  'hyperlinks 🔗, emojis 😄🎉, and @mentions 🗣️.'
          }}, { textParagraph: {
            text: '🖼️ A <b>card</b> to display visual elements' +
                  'and request information such as text 🔤, ' +
                  'dates and times 📅, and selections ☑️.'
          }}, { textParagraph: {
            text: '👉🔘 An <b>accessory widget</b> which adds ' +
                  'a button to the bottom of a message.'
          }}
        ]}, {
          header: "What's next",
          collapsible: true,
          widgets: [{ textParagraph: {
              text: "❤️ <a href='https://developers.google.com/workspace/chat/api/reference/rest/v1/spaces.messages.reactions/create'>Add a reaction</a>."
            }}, { textParagraph: {
              text: "🔄 <a href='https://developers.google.com/workspace/chat/api/reference/rest/v1/spaces.messages/patch'>Update</a> " +
                    "or  <a href='https://developers.google.com/workspace/chat/api/reference/rest/v1/spaces.messages/delete'>delete</a> " +
                    "the message."
            }
          }]
        }
      ]
    }}],
    accessoryWidgets: [{ buttonList: { buttons: [{
      text: 'View documentation',
      icon: { materialIcon: { name: 'link' }},
      onClick: { openLink: {
        url: 'https://developers.google.com/workspace/chat/create-messages'
      }}
    }]}}]
  };
  const parameters = {};

  // Make the request
  const response = Chat.Spaces.Messages.create(
    message, parent, parameters, getHeaderWithAppCredentials()
  );

  // Handle the response
  console.log(response);
}

Чтобы запустить этот пример, замените SPACE_NAME идентификатором из поля name пространства. Вы можете получить идентификатор, вызвав метод spaces.list() или по URL-адресу пространства.

Добавляйте интерактивные виджеты внизу сообщения

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

  • Оцените точность или удовлетворенность сообщения.
  • Сообщите о проблеме с сообщением или приложением чата.
  • Откройте ссылку на связанный контент, например документацию.
  • Отклоняйте или откладывайте похожие сообщения из приложения «Чат» на определенный период времени.

Чтобы добавить вспомогательные виджеты, включите поле accessoryWidgets[] в тело вашего запроса и укажите один или несколько виджетов, которые вы хотите включить.

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

Аксессуарный виджет.
Рис. 5. Сообщение приложения Chat с текстом и дополнительными виджетами.

Ниже показано тело запроса, который создает текстовое сообщение с двумя дополнительными кнопками. Когда пользователь нажимает кнопку, соответствующая функция (например, doUpvote ) обрабатывает взаимодействие:

{
  text: "Rate your experience with this Chat app.",
  accessoryWidgets: [{ buttonList: { buttons: [{
    icon: { material_icon: {
      name: "thumb_up"
    }},
    color: { red: 0, blue: 255, green: 0 },
    onClick: { action: {
      function: "doUpvote"
    }}
  }, {
    icon: { material_icon: {
      name: "thumb_down"
    }},
    color: { red: 0, blue: 255, green: 0 },
    onClick: { action: {
      function: "doDownvote"
    }}
  }]}}]
}

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

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

Чтобы отправить сообщение конфиденциально с помощью Chat API, укажите поле privateMessageViewer в тексте вашего запроса. Чтобы указать пользователя, вы устанавливаете значение для ресурса User , который представляет пользователя Chat. Вы также можете использовать поле name ресурса User , как показано в следующем примере:

{
  text: "Hello private world!",
  privateMessageViewer: {
    name: "users/USER_ID"
  }
}

Чтобы использовать этот пример, замените USER_ID уникальным идентификатором пользователя, например 12345678987654321 или [email protected] . Дополнительную информацию об указании пользователей см. в разделе Идентификация и указание пользователей Google Chat .

Чтобы отправить сообщение конфиденциально, в запросе необходимо опустить следующее:

Отправка текстового сообщения от имени пользователя

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

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

Чтобы вызвать messages.create() с использованием аутентификации пользователя, необходимо указать в запросе следующие поля:

  • Область авторизации , поддерживающая аутентификацию пользователя для этого метода. В следующем примере используется область chat.messages.create .
  • Ресурс Space , в котором вы хотите разместить сообщение. Аутентифицированный пользователь должен быть участником пространства.
  • Ресурс Message , который необходимо создать. Чтобы определить содержание сообщения, необходимо включить text поле.

По желанию вы можете включить следующее:

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

Node.js

чат/клиент-библиотеки/cloud/create-message-user-cred.js
import {createClientWithUserCredentials} from './authentication-utils.js';

const USER_AUTH_OAUTH_SCOPES = ['https://www.googleapis.com/auth/chat.messages.create'];

// This sample shows how to create message with user credential
async function main() {
  // Create a client
  const chatClient = await createClientWithUserCredentials(USER_AUTH_OAUTH_SCOPES);

  // Initialize request argument(s)
  const request = {
    // Replace SPACE_NAME here.
    parent: 'spaces/SPACE_NAME',
    message: {
      text: '👋🌎 Hello world!' +
            'Text messages can contain things like:\n\n' +
            '* Hyperlinks 🔗\n' +
            '* Emojis 😄🎉\n' +
            '* Mentions of other Chat users `@` \n\n' +
            'For details, see the ' +
            '<https://developers.google.com/workspace/chat/format-messages' +
            '|Chat API developer documentation>.'
    }
  };

  // Make the request
  const response = await chatClient.createMessage(request);

  // Handle the response
  console.log(response);
}

main().catch(console.error);

Питон

чат/клиент-библиотеки/cloud/create_message_user_cred.py
from authentication_utils import create_client_with_user_credentials
from google.apps import chat_v1 as google_chat

SCOPES = ["https://www.googleapis.com/auth/chat.messages.create"]

def create_message_with_user_cred():
    # Create a client
    client = create_client_with_user_credentials(SCOPES)

    # Initialize request argument(s)
    request = google_chat.CreateMessageRequest(
        # Replace SPACE_NAME here.
        parent = "spaces/SPACE_NAME",
        message = {
            "text": '👋🌎 Hello world!' +
                    'Text messages can contain things like:\n\n' +
                    '* Hyperlinks 🔗\n' +
                    '* Emojis 😄🎉\n' +
                    '* Mentions of other Chat users `@` \n\n' +
                    'For details, see the ' +
                    '<https://developers.google.com/workspace/chat/format-messages' +
                    '|Chat API developer documentation>.'
        }
    )

    # Make the request
    response = client.create_message(request)

    # Handle the response
    print(response)

create_message_with_user_cred()

Ява

чат/клиент-библиотеки/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMessageUserCred.java
import com.google.chat.v1.ChatServiceClient;
import com.google.chat.v1.CreateMessageRequest;
import com.google.chat.v1.Message;

// This sample shows how to create message with user credential.
public class CreateMessageUserCred {

  private static final String SCOPE =
    "https://www.googleapis.com/auth/chat.messages.create";

  public static void main(String[] args) throws Exception {
    try (ChatServiceClient chatServiceClient =
        AuthenticationUtils.createClientWithUserCredentials(
          ImmutableList.of(SCOPE))) {
      CreateMessageRequest.Builder request = CreateMessageRequest.newBuilder()
        // Replace SPACE_NAME here.
        .setParent("spaces/SPACE_NAME")
        .setMessage(Message.newBuilder()
          .setText( "👋🌎 Hello world!" +
                    "Text messages can contain things like:\n\n" +
                    "* Hyperlinks 🔗\n" +
                    "* Emojis 😄🎉\n" +
                    "* Mentions of other Chat users `@` \n\n" +
                    "For details, see the " +
                    "<https://developers.google.com/workspace/chat/format-messages" +
                    "|Chat API developer documentation>."));
      Message response = chatServiceClient.createMessage(request.build());

      System.out.println(JsonFormat.printer().print(response));
    }
  }
}

Скрипт приложений

чат/расширенный сервис/Main.gs
/**
 * This sample shows how to create message with user credential
 * 
 * It relies on the OAuth2 scope 'https://www.googleapis.com/auth/chat.messages.create'
 * referenced in the manifest file (appsscript.json).
 */
function createMessageUserCred() {
  // Initialize request argument(s)
  // TODO(developer): Replace SPACE_NAME here.
  const parent = 'spaces/SPACE_NAME';
  const message = {
    text: '👋🌎 Hello world!' +
          'Text messages can contain things like:\n\n' +
          '* Hyperlinks 🔗\n' +
          '* Emojis 😄🎉\n' +
          '* Mentions of other Chat users `@` \n\n' +
          'For details, see the ' +
          '<https://developers.google.com/workspace/chat/format-messages' +
          '|Chat API developer documentation>.'
  };

  // Make the request
  const response = Chat.Spaces.Messages.create(message, parent);

  // Handle the response
  console.log(response);
}

Чтобы запустить этот пример, замените SPACE_NAME идентификатором из поля name пространства. Вы можете получить идентификатор, вызвав метод spaces.list() или по URL-адресу пространства.

Начать или ответить в теме

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

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

  • В теле запроса укажите поле thread.threadKey .
  • Укажите параметр запроса messageReplyOption чтобы определить, что произойдет, если ключ уже существует.

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

  • В тексте вашего запроса включите поле thread . Если установлено, вы можете указать созданный вами threadKey . В противном случае вы должны использовать name потока.
  • Укажите параметр запроса messageReplyOption .

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

Node.js

чат/клиент-библиотеки/cloud/create-message-user-cred-thread-key.js
import {createClientWithUserCredentials} from './authentication-utils.js';
const {MessageReplyOption} = require('@google-apps/chat').protos.google.chat.v1.CreateMessageRequest;

const USER_AUTH_OAUTH_SCOPES = ['https://www.googleapis.com/auth/chat.messages.create'];

// This sample shows how to create message with user credential with thread key
async function main() {
  // Create a client
  const chatClient = await createClientWithUserCredentials(USER_AUTH_OAUTH_SCOPES);

  // Initialize request argument(s)
  const request = {
    // Replace SPACE_NAME here.
    parent: 'spaces/SPACE_NAME',
    // Creates the message as a reply to the thread specified by thread_key
    // If it fails, the message starts a new thread instead
    messageReplyOption: MessageReplyOption.REPLY_MESSAGE_FALLBACK_TO_NEW_THREAD,
    message: {
      text: 'Hello with user credential!',
      thread: {
        // Thread key specifies a thread and is unique to the chat app
        // that sets it
        threadKey: 'THREAD_KEY'
      }
    }
  };

  // Make the request
  const response = await chatClient.createMessage(request);

  // Handle the response
  console.log(response);
}

main().catch(console.error);

Питон

чат/клиент-библиотеки/cloud/create_message_user_cred_thread_key.py
from authentication_utils import create_client_with_user_credentials
from google.apps import chat_v1 as google_chat

import google.apps.chat_v1.CreateMessageRequest.MessageReplyOption

SCOPES = ["https://www.googleapis.com/auth/chat.messages.create"]

# This sample shows how to create message with user credential with thread key
def create_message_with_user_cred_thread_key():
    # Create a client
    client = create_client_with_user_credentials(SCOPES)

    # Initialize request argument(s)
    request = google_chat.CreateMessageRequest(
        # Replace SPACE_NAME here
        parent = "spaces/SPACE_NAME",
        # Creates the message as a reply to the thread specified by thread_key.
        # If it fails, the message starts a new thread instead.
        message_reply_option = MessageReplyOption.REPLY_MESSAGE_FALLBACK_TO_NEW_THREAD,
        message = {
            "text": "Hello with user credential!",
            "thread": {
                # Thread key specifies a thread and is unique to the chat app
                # that sets it.
                "thread_key": "THREAD_KEY"
            }
        }
    )

    # Make the request
    response = client.create_message(request)

    # Handle the response
    print(response)

create_message_with_user_cred_thread_key()

Ява

чат/клиент-библиотеки/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMessageUserCredThreadKey.java
import com.google.chat.v1.ChatServiceClient;
import com.google.chat.v1.CreateMessageRequest;
import com.google.chat.v1.CreateMessageRequest.MessageReplyOption;
import com.google.chat.v1.Message;
import com.google.chat.v1.Thread;

// This sample shows how to create message with a thread key with user
// credential.
public class CreateMessageUserCredThreadKey {

  private static final String SCOPE =
    "https://www.googleapis.com/auth/chat.messages.create";

  public static void main(String[] args) throws Exception {
    try (ChatServiceClient chatServiceClient =
        AuthenticationUtils.createClientWithUserCredentials(
          ImmutableList.of(SCOPE))) {
      CreateMessageRequest.Builder request = CreateMessageRequest.newBuilder()
        // Replace SPACE_NAME here.
        .setParent("spaces/SPACE_NAME")
        // Creates the message as a reply to the thread specified by thread_key.
        // If it fails, the message starts a new thread instead.
        .setMessageReplyOption(
          MessageReplyOption.REPLY_MESSAGE_FALLBACK_TO_NEW_THREAD)
        .setMessage(Message.newBuilder()
          .setText("Hello with user credentials!")
          // Thread key specifies a thread and is unique to the chat app
          // that sets it.
          .setThread(Thread.newBuilder().setThreadKey("THREAD_KEY")));
      Message response = chatServiceClient.createMessage(request.build());

      System.out.println(JsonFormat.printer().print(response));
    }
  }
}

Скрипт приложений

чат/расширенный сервис/Main.gs
/**
 * This sample shows how to create message with user credential with thread key
 * 
 * It relies on the OAuth2 scope 'https://www.googleapis.com/auth/chat.messages.create'
 * referenced in the manifest file (appsscript.json).
 */
function createMessageUserCredThreadKey() {
  // Initialize request argument(s)
  // TODO(developer): Replace SPACE_NAME here.
  const parent = 'spaces/SPACE_NAME';
  // Creates the message as a reply to the thread specified by thread_key
  // If it fails, the message starts a new thread instead
  const messageReplyOption = 'REPLY_MESSAGE_FALLBACK_TO_NEW_THREAD';
  const message = {
    text: 'Hello with user credential!',
    thread: {
      // Thread key specifies a thread and is unique to the chat app
      // that sets it
      threadKey: 'THREAD_KEY'
    }
  };

  // Make the request
  const response = Chat.Spaces.Messages.create(message, parent, {
    messageReplyOption: messageReplyOption
  });

  // Handle the response
  console.log(response);
}

Чтобы запустить этот пример, замените следующее:

  • THREAD_KEY : существующий ключ потока в пространстве или для создания нового потока — уникальное имя потока.
  • SPACE_NAME : идентификатор из поля name пространства. Вы можете получить идентификатор, вызвав метод spaces.list() или по URL-адресу пространства.

Назовите сообщение

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

Например, чтобы получить сообщение с помощью метода get() , вы используете имя ресурса, чтобы указать, какое сообщение нужно получить. Имя ресурса форматируется как spaces/{space}/messages/{message} , где {message} представляет собой назначенный системой идентификатор или пользовательское имя, которое вы установили при создании сообщения.

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

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

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

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

Node.js

чат/клиент-библиотеки/облако/создать-сообщение-пользователь-cred-message-id.js
import {createClientWithUserCredentials} from './authentication-utils.js';

const USER_AUTH_OAUTH_SCOPES = ['https://www.googleapis.com/auth/chat.messages.create'];

// This sample shows how to create message with user credential with message id
async function main() {
  // Create a client
  const chatClient = await createClientWithUserCredentials(USER_AUTH_OAUTH_SCOPES);

  // Initialize request argument(s)
  const request = {
    // Replace SPACE_NAME here.
    parent: 'spaces/SPACE_NAME',
    // Message id lets chat apps get, update or delete a message without needing
    // to store the system assigned ID in the message's resource name
    messageId: 'client-MESSAGE-ID',
    message: { text: 'Hello with user credential!' }
  };

  // Make the request
  const response = await chatClient.createMessage(request);

  // Handle the response
  console.log(response);
}

main().catch(console.error);

Питон

чат/клиент-библиотеки/cloud/create_message_user_cred_message_id.py
from authentication_utils import create_client_with_user_credentials
from google.apps import chat_v1 as google_chat

SCOPES = ["https://www.googleapis.com/auth/chat.messages.create"]

# This sample shows how to create message with user credential with message id
def create_message_with_user_cred_message_id():
    # Create a client
    client = create_client_with_user_credentials(SCOPES)

    # Initialize request argument(s)
    request = google_chat.CreateMessageRequest(
        # Replace SPACE_NAME here
        parent = "spaces/SPACE_NAME",
        # Message id let chat apps get, update or delete a message without needing
        # to store the system assigned ID in the message's resource name.
        message_id = "client-MESSAGE-ID",
        message = {
            "text": "Hello with user credential!"
        }
    )

    # Make the request
    response = client.create_message(request)

    # Handle the response
    print(response)

create_message_with_user_cred_message_id()

Ява

чат/клиент-библиотеки/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMessageUserCredMessageId.java
import com.google.chat.v1.ChatServiceClient;
import com.google.chat.v1.CreateMessageRequest;
import com.google.chat.v1.Message;

// This sample shows how to create message with message id specified with user
// credential.
public class CreateMessageUserCredMessageId {

  private static final String SCOPE =
    "https://www.googleapis.com/auth/chat.messages.create";

  public static void main(String[] args) throws Exception {
    try (ChatServiceClient chatServiceClient =
        AuthenticationUtils.createClientWithUserCredentials(
          ImmutableList.of(SCOPE))) {
      CreateMessageRequest.Builder request = CreateMessageRequest.newBuilder()
        // Replace SPACE_NAME here.
        .setParent("spaces/SPACE_NAME")
        .setMessage(Message.newBuilder()
          .setText("Hello with user credentials!"))
        // Message ID lets chat apps get, update or delete a message without
        // needing to store the system assigned ID in the message's resource
        // name.
        .setMessageId("client-MESSAGE-ID");
      Message response = chatServiceClient.createMessage(request.build());

      System.out.println(JsonFormat.printer().print(response));
    }
  }
}

Скрипт приложений

чат/расширенный сервис/Main.gs
/**
 * This sample shows how to create message with user credential with message id
 * 
 * It relies on the OAuth2 scope 'https://www.googleapis.com/auth/chat.messages.create'
 * referenced in the manifest file (appsscript.json).
 */
function createMessageUserCredMessageId() {
  // Initialize request argument(s)
  // TODO(developer): Replace SPACE_NAME here.
  const parent = 'spaces/SPACE_NAME';
  // Message id lets chat apps get, update or delete a message without needing
  // to store the system assigned ID in the message's resource name
  const messageId = 'client-MESSAGE-ID';
  const message = { text: 'Hello with user credential!' };

  // Make the request
  const response = Chat.Spaces.Messages.create(message, parent, {
    messageId: messageId
  });

  // Handle the response
  console.log(response);
}

Чтобы запустить этот пример, замените следующее:

  • SPACE_NAME : идентификатор из поля name пространства. Вы можете получить идентификатор, вызвав метод spaces.list() или по URL-адресу пространства.
  • MESSAGE-ID : имя сообщения, которое начинается с custom- . Должно быть уникальным среди любых других имен сообщений, созданных приложением Chat в указанном пространстве.

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

Когда приложение или карточка Google Chat возвращает ошибку, в интерфейсе Chat отображается сообщение «Что-то пошло не так». или «Невозможно обработать ваш запрос». Иногда в пользовательском интерфейсе чата не отображается сообщение об ошибке, но приложение или карточка чата выдает неожиданный результат; например, сообщение с карточкой может не появиться.

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