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

Z tego przewodnika dowiesz się, jak wywoływać funkcje interfejsu Google Chat API messages.create() wykonując dowolną z tych czynności:

  • Wysyłaj wiadomości zawierające tekst, karty i interaktywne widżety.
  • Wysyłanie prywatnych wiadomości do określonego użytkownika Google Chat
  • Rozpocznij wątek wiadomości lub odpowiedz na niego.
  • Nazwij wiadomość, aby móc ją określić w innym interfejsie Chat API żądań.

Maksymalny rozmiar wiadomości (wraz z tekstem i kartami) to 32 000 bajtów. Aby wysyłać wiadomości większe niż ten rozmiar, aplikacja Google Chat musi wysłać kilka wiadomości.

Oprócz wywoływania metody messages.create() aplikacje Google Chat mogą tworzyć i wysyłać wiadomości, aby odpowiedzieć na interakcje użytkowników, takie jak opublikowanie wiadomość powitalną, gdy użytkownik doda aplikację Google Chat do kosmosu. Gdy odpowiadasz na interakcje, aplikacje do obsługi czatu mogą używać innych różne typy funkcji komunikacji, w tym interaktywne okna i podgląd linków i interfejsów. Aby odpowiedzieć użytkownikowi, aplikacja Google Chat wraca wiadomości są wysyłane synchronicznie i bez wywoływania interfejsu Chat API. Aby się uczyć o wysyłaniu wiadomości w celu odpowiadania na interakcje, zobacz Odbieranie interakcji w aplikacji Google Chat i odpowiadanie na nie

Jak Google Chat wyświetla i atrybuty wiadomości utworzone za pomocą interfejsu Chat API

Możesz wywołać metodę messages.create() za pomocą uwierzytelnianie aplikacji i uwierzytelnianie użytkowników. Google Chat inaczej przypisuje nadawcę wiadomości w zależności od wybranego typu uwierzytelniania.

Gdy uwierzytelnisz się jako aplikacja Google Chat, aplikacja Google Chat wyśle wiadomość.

Wywołanie metody messages.create() z uwierzytelnianiem aplikacji.
Rysunek 1. Po uwierzytelnieniu aplikacja Google Chat wysyła wiadomość. Aby poinformować, że nadawca nie jest osobą, obok jej nazwy w Google Chat pojawia się App.

Gdy uwierzytelnisz się jako użytkownik, aplikacja Google Chat wysyła w imieniu użytkownika. Google Chat przypisuje też wartości atrybutów do aplikacji Google Chat, wyświetlając jej nazwę.

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

Typ uwierzytelniania określa też, które funkcje i interfejsy komunikacji które możesz umieścić w wiadomości. Dzięki uwierzytelnianiu aplikacji Aplikacje do obsługi czatu mogą wysyłać wiadomości zawierające tekst sformatowany, z interfejsami kartowymi i interaktywnymi widżetami. Użytkownicy Google Chat mogą wysyłać SMS-y tylko w wiadomościach, więc uwzględniaj tekst tylko podczas tworzenia wiadomości z użyciem uwierzytelniania użytkownika. Aby dowiedzieć się więcej o funkcji przesyłania wiadomości funkcji dostępnych w interfejsie Chat API, zapoznaj się z Omówienie wiadomości w Google Chat

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

Wymagania wstępne

Node.js

Python

Java

Google Apps Script

Wysyłanie wiadomości jako aplikacji Google Chat

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

Wiadomość wysłana z uwierzytelnianiem aplikacji
Rysunek 4. Aplikacja do obsługi czatu wysyła wiadomość z: tekst, kartę i przycisk akcesorium.

Aby wywołać messages.create() za pomocą uwierzytelniania aplikacji, musisz podać następujące pola w żądaniu:

  • Zakres autoryzacji chat.bot.
  • Zasób Space, w którym w którym chcesz opublikować wiadomość. Aplikacja Google Chat musi być z użytkownikiem pokoju.
  • Message do utworzenia zasobu. Aby określić treść wiadomości, możesz uwzględnić tekst sformatowany (text), co najmniej jeden interfejs karty (cardsV2), lub jedno i drugie.

Opcjonalnie możesz dodać takie elementy:

Ten kod pokazuje przykładowy sposób działania aplikacji Google Chat może wysłać wiadomość opublikowaną jako aplikacja Google Chat, która zawiera tekst, kartę i klikalny 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

czat/zaawansowane-usługa/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 w pomieszczeniu name. Aby go uzyskać, wywołaj metodę Metoda spaces.list() lub z adresu URL pokoju.

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

W pierwszym przykładzie kodu w tym przewodniku funkcja Wiadomość w aplikacji Google Chat z klikalnym przyciskiem czyli widżet akcesoriów. Widżety akcesoriów pojawiają się po tekście lub kartach w wiadomości. Możesz używać tych widżetów, aby otrzymywać prompty interakcji z przekazem reklamowym na wiele sposobów, między innymi:

  • Oceń dokładność lub satysfakcję wiadomości.
  • Zgłoś problem z wiadomością lub aplikacją Google Chat.
  • Otwórz link do powiązanych treści, np. dokumentacji.
  • Odrzucanie podobnych wiadomości w aplikacji Google Chat i odkładanie na później w wybranym okresie.

Aby dodać widżety akcesoriów, dołącz accessoryWidgets[] w treści żądania i określ co najmniej jeden widżet, który ma być .

Ten obraz przedstawia aplikację Google Chat, która dołącza do wiadomości wiadomość tekstowa z widżetami akcesoriów, aby użytkownicy mogli ocenić wrażenia użytkownika. w aplikacji Google Chat.

Widżet akcesoriów.
Rysunek 5. Wiadomość w aplikacji Google Chat z widżety tekstu i akcesoriów.

Poniżej widać treść żądania, które tworzy wiadomość tekstową z dwa przyciski. Gdy użytkownik kliknie przycisk, zostanie funkcja (np. doUpvote) przetwarza 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"
    }}
  }]}}]
}

Wyślij wiadomość prywatnie

Aplikacje do obsługi czatu mogą wysyłać wiadomości prywatnie, aby wiadomość jest widoczna tylko dla określonego użytkownika w pokoju. Gdy aplikacja Google Chat wysyła wiadomość prywatną, wyświetla etykietę informującą użytkownika, że wiadomość jest widoczna tylko dla niego.

Aby wysłać wiadomość prywatnie za pomocą interfejsu Chat API, określ privateMessageViewer w treści żądania. Aby określić użytkownika, ustaw wartość na zasobu User, reprezentuje użytkownika Google Chat. Możesz też użyć usługi name parametru User zgodnie z poniższym przykładem:

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

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

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

Wysyłanie SMS-a w imieniu użytkownika

W tej sekcji wyjaśniono, jak wysyłać wiadomości w imieniu użytkownika za pomocą usługi uwierzytelnianie użytkownika. Gdy funkcja uwierzytelniania użytkownika jest włączona, treść wiadomości może zawierać tylko tekst i pomijać funkcje przesyłania wiadomości, które są dostępne tylko komunikatory, w tym interfejsy kart i interaktywne widżety;

Wiadomość wysłana z uwierzytelnianiem użytkownika
Rysunek 3. Aplikacja do obsługi czatu wysyła SMS-a na użytkownika.

Aby wywołać messages.create() za pomocą uwierzytelniania użytkownika, musisz podać następujące pola w żądaniu:

  • zakres autoryzacji. który obsługuje uwierzytelnianie użytkowników w przypadku tej metody. W tym przykładzie użyto zakres chat.messages.create.
  • Zasób Space, w którym w którym chcesz opublikować wiadomość. Uwierzytelniony użytkownik musi być członkiem kosmosu.
  • Message do utworzenia zasobu. Aby zdefiniować treść wiadomości, należy umieścić parametr text .

Opcjonalnie możesz dodać takie elementy:

Ten kod pokazuje przykładowy sposób działania aplikacji Google Chat może wysłać SMS-a 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

czat/zaawansowane-usługa/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 w pomieszczeniu name. . Aby go uzyskać, wywołaj metodę Metoda spaces.list() lub z adresu URL pokoju.

Rozpoczynanie wątku lub odpowiadanie w nim

W przypadku pokoi z wątkami: możesz określić, czy nowa wiadomość ma rozpoczynać wątek, czy odpowiadać do istniejącego wątku.

Domyślnie wiadomości utworzone za pomocą interfejsu Chat API rozpoczynają nowy w wątku. Aby łatwiej zidentyfikować wątek i odpowiedzieć na niego później, możesz podać klucz wątku w żądaniu:

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

  • W treści żądania umieść pole thread. Jeśli zasada jest skonfigurowana, określ threadKey utworzonej przez siebie. W przeciwnym razie musisz użyć parametru name w wątku.
  • Określ parametr zapytania messageReplyOption.

Ten kod pokazuje przykładowy sposób działania aplikacji Google Chat może wysłać SMS-a rozpoczynającego się od wątku określonego przez 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

czat/zaawansowane-usługa/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 to:

  • THREAD_KEY: istniejący klucz wątku w pokoju, aby utworzyć nowy wątek, mającą unikalną nazwę.
  • SPACE_NAME: identyfikator pokoju name. . Aby go uzyskać, wywołaj metodę Metoda spaces.list() lub z adresu URL pokoju.

Nazywanie wiadomości

Aby pobierać lub określać wiadomość w przyszłych wywołaniach interfejsu API, możesz nazwać wiadomość ustawiając pole messageId w żądaniu messages.create(). Nazwa wiadomości pozwala ją określić bez konieczności przechowywania przypisany przez system identyfikator z nazwy zasobu wiadomości (reprezentowany w tagu name ).

Aby na przykład pobrać wiadomość przy użyciu metody get(), należy użyć funkcji nazwę zasobu określającą, którą wiadomość ma zostać pobrana. Nazwa zasobu to w formacie spaces/{space}/messages/{message}, gdzie {message} odpowiada identyfikator przypisany przez system lub niestandardową nazwę ustawioną podczas tworzenia .

Aby nazwać wiadomość, określ identyfikator niestandardowy w messageId podczas tworzenia wiadomości. Pole messageId ustawia wartość parametru clientAssignedMessageId. zasobu Message.

Możesz nazwać wiadomość tylko podczas jej tworzenia. Nie można nazwać zmienić niestandardowy identyfikator istniejących wiadomości. Niestandardowy identyfikator musi spełniać te wymagania: wymagania:

  • Zaczyna się od client-. np. client-custom-name to prawidłowy atrybut niestandardowy Identyfikator, ale custom-name już nie.
  • Może zawierać do 63 znaków i tylko małe litery, cyfry oraz łączników.
  • Jest unikalna w obrębie pokoju. Aplikacja do obsługi czatu nie może używać ten sam niestandardowy identyfikator dla różnych wiadomości.

Ten kod pokazuje przykładowy sposób działania aplikacji Google Chat może wysłać SMS-a z identyfikatorem do danego pokoju w imieniu uwierzytelniony użytkownik:

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

czat/zaawansowane-usługa/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 to:

  • SPACE_NAME: identyfikator pokoju name. . Aby go uzyskać, wywołaj metodę Metoda spaces.list() lub z adresu URL pokoju.
  • MESSAGE-ID: nazwa rozpoczynającej się wiadomości. dzięki custom-. Nie może się powtarzać wśród innych nazw wiadomości utworzonych przez Aplikacja do obsługi czatu w wybranym pokoju.

Rozwiązywanie problemów

Gdy aplikacja Google Chat lub card zwraca błąd, Interfejs czatu wyświetla komunikat „Coś poszło nie tak”. lub „Nie można przetworzyć żądania”. Czasami interfejs Google Chat nie wyświetla się żaden komunikat o błędzie, ale aplikacja Google Chat lub zwraca nieoczekiwany wynik; na przykład wiadomość w formie karty .

Komunikat o błędzie może nie wyświetlać się w interfejsie Google Chat, opisowe komunikaty o błędach i dane dziennika, które pomogą Ci w naprawianiu błędów gdy logowanie błędów aplikacji Google Chat jest włączone. Aby uzyskać pomoc w wyświetlaniu, debugowania i naprawiania błędów, zapoznaj się z artykułem Rozwiązywanie problemów z błędami w Google Chat