Gửi tin nhắn bằng API Google Chat

Hướng dẫn này giải thích cách sử dụng phương thức create() trên tài nguyên Message của Google Chat API để thực hiện một trong những thao tác sau:

  • Gửi tin nhắn có chứa văn bản, thẻ và tiện ích tương tác.
  • Gửi tin nhắn riêng tư cho một người dùng Chat cụ thể.
  • Bắt đầu hoặc trả lời một chuỗi tin nhắn.
  • Đặt tên cho một tin nhắn để bạn có thể chỉ định tin nhắn đó trong các yêu cầu khác của Chat API.

Kích thước tối đa của thông báo (bao gồm cả văn bản hoặc thẻ) là 32.000 byte. Để gửi một thư vượt quá kích thước này, ứng dụng Chat phải gửi nhiều thư thay vì một thư.

Ngoài việc gọi API Chat để tạo tin nhắn, các ứng dụng Chat có thể tạo và gửi tin nhắn để trả lời các hoạt động tương tác của người dùng, chẳng hạn như đăng tin nhắn chào mừng sau khi người dùng thêm ứng dụng Chat vào một không gian. Khi phản hồi các lượt tương tác, ứng dụng trò chuyện có thể sử dụng các loại tính năng nhắn tin khác, bao gồm cả hộp thoại tương tác và giao diện xem trước đường liên kết. Để trả lời người dùng, ứng dụng Chat sẽ trả về tin nhắn một cách đồng bộ mà không cần gọi Chat API. Để tìm hiểu về cách gửi tin nhắn để phản hồi các lượt tương tác, hãy xem bài viết Nhận và phản hồi các lượt tương tác bằng ứng dụng Google Chat.

Cách Chat hiển thị và ghi nhận tin nhắn được tạo bằng API Chat

Bạn có thể gọi phương thức create() bằng cách sử dụng xác thực ứng dụngxác thực người dùng. Chat sẽ gán thuộc tính cho người gửi tin nhắn theo cách khác nhau, tuỳ thuộc vào loại phương thức xác thực mà bạn sử dụng.

Khi bạn xác thực dưới dạng ứng dụng Chat, ứng dụng Chat sẽ gửi thông báo.

Gọi phương thức create() bằng tính năng xác thực ứng dụng.
Hình 1: Khi xác thực ứng dụng, ứng dụng Chat sẽ gửi thông báo. Để cho biết người gửi không phải là người, Chat sẽ hiển thị biểu tượng App bên cạnh tên của người gửi.

Khi bạn xác thực với tư cách là người dùng, ứng dụng Chat sẽ gửi thông báo thay cho người dùng. Chat cũng ghi nhận ứng dụng Chat là nguồn của tin nhắn bằng cách hiển thị tên của ứng dụng.

Gọi phương thức create() bằng thông tin xác thực người dùng.
Hình 2: Khi xác thực người dùng, người dùng sẽ gửi tin nhắn và Chat sẽ hiển thị tên ứng dụng Chat bên cạnh tên người dùng.

Loại xác thực cũng xác định những tính năng và giao diện nhắn tin mà bạn có thể đưa vào thông báo. Với tính năng xác thực ứng dụng, các ứng dụng Chat có thể gửi tin nhắn chứa văn bản đa dạng thức, giao diện dựa trên thẻ và các tiện ích tương tác. Vì người dùng Chat chỉ có thể gửi văn bản trong tin nhắn, nên bạn chỉ có thể thêm văn bản khi tạo tin nhắn bằng cách sử dụng tính năng xác thực người dùng. Để tìm hiểu thêm về các tính năng nhắn tin có trong API Chat, hãy xem Tổng quan về tin nhắn trên Google Chat.

Hướng dẫn này giải thích cách sử dụng một trong hai loại xác thực để gửi tin nhắn bằng API Chat.

Điều kiện tiên quyết

Node.js

Python

Java

Apps Script

Gửi tin nhắn dưới dạng ứng dụng Chat

Phần này giải thích cách gửi tin nhắn chứa văn bản, thẻ và các tiện ích phụ kiện tương tác bằng cách sử dụng xác thực ứng dụng.

Thư được gửi bằng phương thức xác thực ứng dụng
Hình 4. Một ứng dụng Chat gửi tin nhắn có văn bản, thẻ và nút phụ kiện.

Để gọi phương thức CreateMessage() bằng cách sử dụng tính năng xác thực ứng dụng, bạn phải chỉ định các trường sau trong yêu cầu:

  • chat.bot Phạm vi uỷ quyền.
  • Tài nguyên Space mà bạn muốn đăng thông báo. Ứng dụng Chat phải là thành viên của không gian.
  • Tài nguyên Message cần tạo. Để xác định nội dung của thông báo, bạn có thể thêm văn bản đa dạng thức (text), một hoặc nhiều giao diện thẻ (cardsV2) hoặc cả hai.

Bạn có thể thêm các thông tin sau (không bắt buộc):

Đoạn mã sau đây minh hoạ ví dụ về cách một ứng dụng Chat có thể gửi một thông báo được đăng dưới dạng ứng dụng Chat có chứa văn bản, thẻ và một nút có thể nhấp vào ở cuối thông báo:

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));
    }
  }
}

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);
}

Để chạy mẫu này, hãy thay thế SPACE_NAME bằng mã nhận dạng trong trường name của không gian. Bạn có thể lấy mã nhận dạng bằng cách gọi phương thức ListSpaces() hoặc từ URL của không gian.

Thêm tiện ích mang tính tương tác ở cuối thư

Trong mẫu mã đầu tiên của hướng dẫn này, thông báo của ứng dụng trò chuyện sẽ hiển thị một nút có thể nhấp vào ở cuối thông báo, được gọi là tiện ích bổ sung. Các tiện ích phụ kiện sẽ xuất hiện sau mọi văn bản hoặc thẻ trong một tin nhắn. Bạn có thể sử dụng các tiện ích này để nhắc người dùng tương tác với thông báo của bạn theo nhiều cách, bao gồm cả những cách sau:

  • Đánh giá độ chính xác hoặc mức độ hài lòng của một tin nhắn.
  • Báo cáo vấn đề về ứng dụng Tin nhắn hoặc Chat.
  • Mở đường liên kết đến nội dung liên quan, chẳng hạn như tài liệu.
  • Bỏ qua hoặc tạm ẩn các tin nhắn tương tự trong ứng dụng Chat trong một khoảng thời gian cụ thể.

Để thêm tiện ích bổ sung, hãy thêm trường accessoryWidgets[] vào nội dung yêu cầu và chỉ định một hoặc nhiều tiện ích mà bạn muốn thêm.

Hình ảnh sau đây cho thấy một ứng dụng Chat có các tiện ích bổ sung vào tin nhắn văn bản để người dùng có thể đánh giá trải nghiệm của họ với ứng dụng Chat.

Tiện ích phụ kiện.
Hình 5: Tin nhắn của ứng dụng nhắn tin có văn bản và tiện ích phụ kiện.

Sau đây là nội dung của yêu cầu tạo một tin nhắn văn bản có 2 nút phụ kiện. Khi người dùng nhấp vào một nút, hàm tương ứng (chẳng hạn như doUpvote) sẽ xử lý hoạt động tương tác:

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

Gửi tin nhắn riêng tư

Các ứng dụng Chat có thể gửi tin nhắn riêng tư để chỉ một người dùng cụ thể trong không gian nhìn thấy tin nhắn. Khi ứng dụng Chat gửi tin nhắn riêng tư, tin nhắn sẽ có nhãn thông báo cho người dùng biết rằng chỉ họ mới thấy được tin nhắn đó.

Để gửi tin nhắn riêng tư bằng API Chat, hãy chỉ định trường privateMessageViewer trong nội dung yêu cầu của bạn. Để chỉ định người dùng, bạn đặt giá trị thành tài nguyên User đại diện cho người dùng Chat. Bạn cũng có thể sử dụng trường name của tài nguyên User, như trong ví dụ sau:

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

Để sử dụng mẫu này, hãy thay thế USER_ID bằng một mã nhận dạng duy nhất cho người dùng, chẳng hạn như 12345678987654321 hoặc hao@cymbalgroup.com. Để biết thêm thông tin về cách chỉ định người dùng, hãy xem phần Xác định và chỉ định người dùng Google Chat.

Để gửi tin nhắn riêng tư, bạn phải bỏ qua những thông tin sau trong yêu cầu của mình:

Thay mặt người dùng gửi tin nhắn văn bản

Phần này giải thích cách gửi thông báo thay mặt người dùng bằng cách sử dụng xác thực người dùng. Khi xác thực người dùng, nội dung của tin nhắn chỉ được chứa văn bản và phải bỏ qua các tính năng nhắn tin chỉ có trong ứng dụng Chat, bao gồm cả giao diện thẻ và các tiện ích tương tác.

Thư được gửi bằng thông tin xác thực người dùng
Hình 3. Một ứng dụng Chat gửi tin nhắn văn bản thay mặt cho người dùng.

Để gọi phương thức CreateMessage() bằng cách sử dụng quy trình xác thực người dùng, bạn phải chỉ định các trường sau trong yêu cầu:

  • Một phạm vi uỷ quyền hỗ trợ xác thực người dùng cho phương thức này. Mẫu sau đây sử dụng phạm vi chat.messages.create.
  • Tài nguyên Space mà bạn muốn đăng thông báo. Người dùng được xác thực phải là thành viên của không gian.
  • Tài nguyên Message cần tạo. Để xác định nội dung của thông báo, bạn phải thêm trường text.

Bạn có thể thêm các thông tin sau (không bắt buộc):

Đoạn mã sau đây cho thấy ví dụ về cách ứng dụng Chat có thể gửi tin nhắn văn bản trong một không gian nhất định thay cho người dùng đã xác thực:

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));
    }
  }
}

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);
}

Để chạy mẫu này, hãy thay thế SPACE_NAME bằng mã nhận dạng trong trường name của không gian. Bạn có thể lấy mã nhận dạng bằng cách gọi phương thức ListSpaces() hoặc từ URL của không gian.

Bắt đầu hoặc trả lời trong một chuỗi

Đối với những không gian sử dụng chuỗi tin nhắn, bạn có thể chỉ định xem một tin nhắn mới có bắt đầu một chuỗi tin nhắn hay không, hoặc có trả lời một chuỗi tin nhắn hiện có hay không.

Theo mặc định, những tin nhắn mà bạn tạo bằng API Chat sẽ bắt đầu một chuỗi tin nhắn mới. Để giúp bạn xác định chuỗi và trả lời sau, bạn có thể chỉ định khoá chuỗi trong yêu cầu:

  • Trong phần nội dung của yêu cầu, hãy chỉ định trường thread.threadKey.
  • Chỉ định tham số truy vấn messageReplyOption để xác định điều gì sẽ xảy ra nếu khoá đã tồn tại.

Cách tạo một tin nhắn trả lời một chuỗi tin nhắn hiện có:

  • Trong nội dung yêu cầu, hãy thêm trường thread. Nếu đã thiết lập, bạn có thể chỉ định threadKey mà bạn đã tạo. Nếu không, bạn phải sử dụng name của luồng.
  • Chỉ định tham số truy vấn messageReplyOption.

Đoạn mã sau đây cho thấy ví dụ về cách ứng dụng Chat có thể gửi tin nhắn văn bản bắt đầu hoặc trả lời một chuỗi tin nhắn nhất định được xác định bằng khoá của một không gian nhất định thay cho người dùng đã xác thực:

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));
    }
  }
}

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);
}

Để chạy mẫu này, hãy thay thế các nội dung sau:

  • THREAD_KEY: khoá luồng hiện có trong không gian hoặc để tạo một luồng mới, một tên duy nhất cho luồng.
  • SPACE_NAME: mã nhận dạng trong trường name của không gian. Bạn có thể lấy mã nhận dạng bằng cách gọi phương thức ListSpaces() hoặc từ URL của không gian.

Đặt tên cho tin nhắn

Để truy xuất hoặc chỉ định một thông báo trong các lệnh gọi API sau này, bạn có thể đặt tên cho một thông báo bằng cách đặt trường messageId trong yêu cầu của mình. Việc đặt tên cho thông báo cho phép bạn chỉ định thông báo mà không cần lưu trữ mã nhận dạng do hệ thống chỉ định từ tên tài nguyên của thông báo (được biểu thị trong trường name).

Ví dụ: để truy xuất một thông báo bằng phương thức get(), bạn dùng tên tài nguyên để chỉ định thông báo cần truy xuất. Tên tài nguyên được định dạng là spaces/{space}/messages/{message}, trong đó {message} biểu thị mã do hệ thống chỉ định hoặc tên tuỳ chỉnh mà bạn đặt khi tạo thông báo.

Để đặt tên cho một thông báo, hãy chỉ định một mã nhận dạng tuỳ chỉnh trong trường messageId khi bạn tạo thông báo. Trường messageId đặt giá trị cho trường clientAssignedMessageId của tài nguyên Message.

Bạn chỉ có thể đặt tên cho thông báo khi tạo thông báo. Bạn không thể đặt tên hoặc sửa đổi mã nhận dạng tuỳ chỉnh cho các thông báo hiện có. Mã nhận dạng tuỳ chỉnh phải đáp ứng các yêu cầu sau:

  • Bắt đầu từ client-. Ví dụ: client-custom-name là một mã nhận dạng tuỳ chỉnh hợp lệ, nhưng custom-name thì không.
  • Chứa tối đa 63 ký tự và chỉ có chữ cái viết thường, số và dấu gạch ngang.
  • Là duy nhất trong một không gian. Ứng dụng Chat không thể dùng cùng một mã nhận dạng tuỳ chỉnh cho nhiều thông báo.

Đoạn mã sau đây cho thấy ví dụ về cách một ứng dụng Chat có thể gửi tin nhắn văn bản kèm theo mã nhận dạng đến một không gian nhất định thay mặt cho người dùng đã xác thực:

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));
    }
  }
}

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);
}

Để chạy mẫu này, hãy thay thế các nội dung sau:

  • SPACE_NAME: mã nhận dạng trong trường name của không gian. Bạn có thể lấy mã nhận dạng bằng cách gọi phương thức ListSpaces() hoặc từ URL của không gian.
  • MESSAGE-ID: tên của thông báo bắt đầu bằng custom-. Phải là tên duy nhất so với mọi tên thông báo khác do ứng dụng Chat tạo trong không gian đã chỉ định.

Khắc phục sự cố

Khi một ứng dụng Google Chat hoặc thẻ trả về lỗi, giao diện Chat sẽ hiển thị thông báo "Đã xảy ra lỗi". hoặc "Không thể xử lý yêu cầu của bạn". Đôi khi, giao diện người dùng Chat không hiển thị bất kỳ thông báo lỗi nào, nhưng ứng dụng hoặc thẻ Chat lại tạo ra kết quả không mong muốn; ví dụ: thông báo thẻ có thể không xuất hiện.

Mặc dù thông báo lỗi có thể không xuất hiện trong giao diện người dùng Chat, nhưng bạn có thể sử dụng thông báo lỗi mô tả và dữ liệu nhật ký để khắc phục lỗi khi bật tính năng ghi nhật ký lỗi cho ứng dụng Chat. Để được trợ giúp xem, gỡ lỗi và khắc phục lỗi, hãy xem bài viết Khắc phục lỗi trong Google Chat.