Wysyłanie wiadomości przy użyciu interfejsu Google Chat API

Ten przewodnik wyjaśnia, jak używać metody create() w zasobie Message interfejsu Google Chat API, aby wykonać dowolną z tych czynności:

  • wysyłać wiadomości zawierające tekst, karty i interaktywne widżety;
  • wysyłać wiadomości prywatne do konkretnego użytkownika Google Chat;
  • rozpoczynać wątki wiadomości i odpowiadać na nie;
  • Nadaj wiadomości nazwę, aby można było ją określić w innych żądaniach interfejsu Chat API.

Maksymalny rozmiar wiadomości (wraz z tekstem i kartami) to 32 000 bajtów. Aby wysłać wiadomość, która przekracza ten rozmiar, aplikacja Chat musi wysłać kilka wiadomości.

Oprócz wywoływania interfejsu Chat API w celu tworzenia wiadomości aplikacje do obsługi czatu mogą tworzyć i wysyłać wiadomości w odpowiedzi na interakcje użytkowników, np. publikować wiadomość powitalną po dodaniu aplikacji do obsługi czatu do pokoju. Podczas odpowiadania na interakcje aplikacje Google Chat mogą korzystać z innych typów funkcji przesyłania wiadomości, w tym interaktywnych okien dialogowych i interfejsów podglądu linków. Aby odpowiedzieć użytkownikowi, aplikacja Chat zwraca wiadomość synchronicznie, bez wywoływania interfejsu Chat API. Więcej informacji o wysyłaniu wiadomości w odpowiedzi na interakcje znajdziesz w artykule Odbieranie interakcji z aplikacją Google Chat i odpowiadanie na nie.

Sposób wyświetlania i przypisywania wiadomości utworzonych za pomocą interfejsu Chat API

Metodę create() możesz wywołać za pomocą uwierzytelniania aplikacjiuwierzytelniania użytkownika. Chat przypisuje nadawcę wiadomości w różny sposób w zależności od typu używanego uwierzytelniania.

Gdy uwierzytelnienie nastąpi w aplikacji Google Chat, wyśle ona wiadomość.

Wywołanie metody create() z uwierzytelnianiem aplikacji.
Ilustracja 1. W przypadku uwierzytelniania aplikacji wiadomość wysyła aplikacja Chat. Aby zaznaczyć, że nadawca nie jest osobą, Chat wyświetla obok jego nazwy symbol App.

Gdy uwierzytelnienie nastąpi jako użytkownik, aplikacja do obsługi czatu wyśle wiadomość w imieniu użytkownika. Chat przypisuje też aplikację Chat do wiadomości, wyświetlając jej nazwę.

Wywołanie metody create() z uwierzytelnianiem użytkownika.
Ilustracja 2. Po uwierzytelnieniu użytkownik wysyła wiadomość, a Google Chat wyświetla nazwę aplikacji do obsługi czatu obok nazwy użytkownika.

Typ uwierzytelniania określa też, które funkcje i interfejsy wiadomości możesz uwzględnić w wiadomości. Dzięki uwierzytelnianiu aplikacji aplikacje do obsługi czatu mogą wysyłać wiadomości zawierające tekst sformatowany, interfejsy oparte na kartach i interaktywne widżety. Użytkownicy Google Chat mogą wysyłać w wiadomościach tylko tekst, więc podczas tworzenia wiadomości z użyciem uwierzytelniania użytkownika możesz uwzględniać tylko tekst. Więcej informacji o funkcjach przesyłania wiadomości dostępnych w interfejsie Chat API znajdziesz w przeglądzie wiadomości w Google Chat.

Z tego przewodnika dowiesz się, jak używać obu typów uwierzytelniania do wysyłania wiadomości za pomocą interfejsu Chat API.

Wymagania wstępne

Node.js

  • Pokój Google Chat, w którym uwierzytelniony użytkownik lub aplikacja do czatu wywołująca połączenie jest członkiem. Aby uwierzytelnić się jako aplikacja do czatu, dodaj ją do pokoju.

Python

  • Pokój Google Chat, w którym uwierzytelniony użytkownik lub aplikacja do czatu wywołująca połączenie jest członkiem. Aby uwierzytelnić się jako aplikacja do czatu, dodaj ją do pokoju.

Java

  • Pokój Google Chat, w którym uwierzytelniony użytkownik lub aplikacja do czatu wywołująca połączenie jest członkiem. Aby uwierzytelnić się jako aplikacja do czatu, dodaj ją do pokoju.

Google Apps Script

  • Pokój Google Chat, w którym uwierzytelniony użytkownik lub aplikacja do czatu wywołująca połączenie jest członkiem. Aby uwierzytelnić się jako aplikacja do czatu, dodaj ją do pokoju.

Wysyłanie wiadomości w aplikacji Google Chat

W tej sekcji dowiesz się, jak wysyłać wiadomości zawierające tekst, karty i interaktywne widżety akcesoriów za pomocą uwierzytelniania aplikacji.

Wiadomość wysłana z uwierzytelnianiem aplikacji
Rysunek 4. Aplikacja w Google Chat wysyła wiadomość z tekstem, kartą i przyciskiem dodatkowym.

Aby wywołać metodę CreateMessage() za pomocą uwierzytelniania aplikacji, musisz podać w żądaniu te pola:

Opcjonalnie możesz dodać:

Poniższy kod pokazuje, jak aplikacja do obsługi czatu może wysłać wiadomość opublikowaną jako aplikacja do obsługi czatu, która zawiera tekst, kartę i klikany przycisk u dołu wiadomości:

Node.js

chat/client-libraries/cloud/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);

Python

chat/client-libraries/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()

Java

chat/client-libraries/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));
    }
  }
}

Google Apps Script

chat/advanced-service/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);
}

Aby uruchomić ten przykład, zastąp SPACE_NAME identyfikatorem z pola name przestrzeni. Możesz go uzyskać, wywołując metodę ListSpaces() lub z adresu URL pokoju.

Dodawanie interaktywnych widżetów u dołu wiadomości

W pierwszym przykładzie kodu w tym przewodniku wiadomość aplikacji do czatu zawiera klikalny przycisk u dołu wiadomości, zwany widżetem dodatkowym. Widżety dodatkowe wyświetlają się po tekście lub kartach w wiadomości. Za pomocą tych widżetów możesz zachęcać użytkowników do interakcji z wiadomością na wiele sposobów, m.in.:

  • Oceń dokładność lub zadowolenie z wiadomości.
  • Zgłoś problem z wiadomością lub aplikacją do obsługi czatu.
  • Otwórz link do powiązanych treści, np. dokumentacji.
  • Odrzucanie lub odkładanie podobnych wiadomości z aplikacji Chat na określony czas.

Aby dodać widżety akcesoriów, w treści żądania umieść pole accessoryWidgets[] i określ co najmniej 1 widżet, który chcesz uwzględnić.

Na ilustracji poniżej widać aplikację Google Chat, która dołącza do wiadomości tekstowej widżety dodatkowe, aby użytkownicy mogli ocenić swoje wrażenia z korzystania z niej.

Widżet akcesoriów.
Ilustracja 5. Wiadomość w aplikacji do czatowania z tekstem i widżetami akcesoriów.

Poniżej przedstawiono treść żądania, które tworzy wiadomość tekstową z 2 przyciskami akcesoriów. Gdy użytkownik kliknie przycisk, odpowiednia funkcja (np. doUpvote) przetworzy interakcję:

{
  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"
    }}
  }]}}]
}

Wysyłanie wiadomości prywatnej

Aplikacje do obsługi czatu mogą wysyłać wiadomości prywatne, tak aby były one widoczne tylko dla określonego użytkownika w pokoju. Gdy aplikacja do czatowania wysyła wiadomość prywatną, wyświetla się etykieta informująca użytkownika, że wiadomość jest widoczna tylko dla niego.

Aby wysłać wiadomość prywatną za pomocą interfejsu Chat API, w treści żądania określ pole privateMessageViewer. Aby określić użytkownika, ustaw wartość na User, czyli zasób reprezentujący użytkownika Google Chat. Możesz też użyć pola name w zasobie User, jak pokazano w tym przykładzie:

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

Aby użyć tego przykładu, zastąp USER_ID unikalnym identyfikatorem użytkownika, np. 12345678987654321 lub hao@cymbalgroup.com. Więcej informacji o określaniu użytkowników znajdziesz w artykule Identyfikowanie i określanie użytkowników Google Chat.

Aby wysłać wiadomość prywatną, w żądaniu musisz pominąć te elementy:

Wysyłanie SMS-a w imieniu użytkownika

W tej sekcji wyjaśniamy, jak wysyłać wiadomości w imieniu użytkownika za pomocą uwierzytelniania użytkownika. W przypadku uwierzytelniania użytkownika treść wiadomości może zawierać tylko tekst i nie może zawierać funkcji przesyłania wiadomości dostępnych tylko w aplikacjach do czatu, w tym interfejsów kart i interaktywnych widżetów.

Wiadomość wysłana z uwierzytelnianiem użytkownika
Rysunek 3. Aplikacja Google Chat wysyła wiadomość tekstową w imieniu użytkownika.

Aby wywołać metodę CreateMessage() za pomocą uwierzytelniania użytkownika, musisz w żądaniu podać te pola:

Opcjonalnie możesz dodać:

Poniższy kod pokazuje, jak aplikacja Google Chat może wysłać wiadomość tekstową w danym pokoju w imieniu uwierzytelnionego użytkownika:

Node.js

chat/client-libraries/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);

Python

chat/client-libraries/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()

Java

chat/client-libraries/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));
    }
  }
}

Google Apps Script

chat/advanced-service/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);
}

Aby uruchomić ten przykład, zastąp SPACE_NAME identyfikatorem z pola name przestrzeni. Możesz go uzyskać, wywołując metodę ListSpaces() lub z adresu URL pokoju.

Rozpoczynanie wątku lub odpowiadanie w wątku

W przypadku pokoi, w których używane są wątki, możesz określić, czy nowa wiadomość rozpoczyna wątek, czy jest odpowiedzią na istniejący wątek.

Domyślnie wiadomości tworzone za pomocą interfejsu Chat API rozpoczynają nowy wątek. Aby ułatwić Ci identyfikację wątku i późniejsze odpowiadanie na niego, możesz w żądaniu podać klucz wątku:

Aby utworzyć wiadomość, która będzie odpowiedzią w istniejącym wątku:

  • W treści żądania umieść pole thread. Jeśli jest ustawiony, możesz określić utworzony przez siebie threadKey. W innym przypadku musisz użyć name wątku.
  • Określ parametr zapytania messageReplyOption.

Poniższy kod pokazuje, jak aplikacja Google Chat może wysłać wiadomość tekstową, która rozpoczyna lub odpowiada na dany wątek zidentyfikowany przez klucz danego pokoju w imieniu uwierzytelnionego użytkownika:

Node.js

chat/client-libraries/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);

Python

chat/client-libraries/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()

Java

chat/client-libraries/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));
    }
  }
}

Google Apps Script

chat/advanced-service/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);
}

Aby uruchomić ten przykład, zastąp te elementy:

  • THREAD_KEY: istniejący klucz wątku w przestrzeni lub, aby utworzyć nowy wątek, unikalną nazwę wątku.
  • SPACE_NAME: identyfikator z pola name pokoju. Możesz go uzyskać, wywołując metodę ListSpaces() lub z adresu URL pokoju.

Nadawanie nazwy wiadomości

Aby w przyszłych wywołaniach interfejsu API pobrać lub określić wiadomość, możesz ją nazwać, ustawiając w żądaniu pole messageId. Nazwanie wiadomości pozwala określić wiadomość bez konieczności przechowywania przypisanego przez system identyfikatora z nazwy zasobu wiadomości (reprezentowanego w polu name).

Aby na przykład pobrać wiadomość za pomocą metody get(), użyj nazwy zasobu, aby określić, którą wiadomość chcesz pobrać. Nazwa zasobu ma format spaces/{space}/messages/{message}, gdzie {message} to identyfikator przypisany przez system lub nazwa niestandardowa ustawiona podczas tworzenia wiadomości.

Aby nadać nazwę wiadomości, podczas jej tworzenia podaj niestandardowy identyfikator w polu messageId. Pole messageId ustawia wartość pola clientAssignedMessageId zasobu Message.

Wiadomość możesz nazwać tylko podczas jej tworzenia. Nie możesz nadawać ani modyfikować niestandardowego identyfikatora w przypadku istniejących wiadomości. Niestandardowy identyfikator musi spełniać te wymagania:

  • Zaczyna się od client-. Na przykład client-custom-name to prawidłowy identyfikator niestandardowy, ale custom-name już nie.
  • Zawiera maksymalnie 63 znaki, które mogą być tylko małymi literami, cyframi i łącznikami.
  • Jest unikalny w obrębie przestrzeni. Aplikacja Google Chat nie może używać tego samego identyfikatora niestandardowego w przypadku różnych wiadomości.

Poniższy kod pokazuje, jak aplikacja do obsługi czatu może wysłać wiadomość tekstową z identyfikatorem do danego pokoju w imieniu uwierzytelnionego użytkownika:

Node.js

chat/client-libraries/cloud/create-message-user-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);

Python

chat/client-libraries/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()

Java

chat/client-libraries/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));
    }
  }
}

Google Apps Script

chat/advanced-service/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);
}

Aby uruchomić ten przykład, zastąp te elementy:

  • SPACE_NAME: identyfikator z pola name pokoju. Możesz go uzyskać, wywołując metodę ListSpaces() lub z adresu URL pokoju.
  • MESSAGE-ID: nazwę wiadomości, która zaczyna się od custom-. Nie może się powtarzać z nazwami innych wiadomości utworzonych przez aplikację do obsługi czatu w określonej przestrzeni.

Rozwiązywanie problemów

Gdy aplikacja Google Chat lub karta zwraca błąd, w interfejsie Google Chat pojawia się komunikat „Coś poszło nie tak”. lub „Nie udało się przetworzyć Twojej prośby”. Czasami interfejs Google Chat nie wyświetla żadnego komunikatu o błędzie, ale aplikacja lub karta Google Chat daje nieoczekiwany wynik, np. wiadomość na karcie może się nie pojawić.

Chociaż w interfejsie czatu może nie wyświetlać się komunikat o błędzie, opisowe komunikaty o błędach i dane logowania są dostępne, aby pomóc w naprawieniu błędów, gdy rejestrowanie błędów w aplikacjach na czat jest włączone. Pomoc dotyczącą wyświetlania, debugowania i naprawiania błędów znajdziesz w artykule Rozwiązywanie problemów z Google Chat.