使用 Google Chat API 发送消息

本指南介绍如何调用 Google Chat API 的 messages.create() 方法执行以下任何操作:

  • 发送包含文本、卡片和互动微件的消息。
  • 向特定 Chat 用户私下发送消息。
  • 发起或回复消息串。
  • 为消息命名,以便在其他 Chat API 中指定 请求。

<ph type="x-smartling-placeholder">

邮件(包括任何文字或卡片)的大小上限为 32,000 字节。 如要发送超出此大小的消息,您的 Chat 扩展应用 必须改为发送多条消息。

除了调用 messages.create() 方法之外,Chat 扩展应用 可以创建和发送消息来回复用户互动,如发布 用户在将 Chat 应用添加到 空间。在响应互动时,Chat 扩展应用可以使用 消息功能的类型,包括互动对话框和链接预览 界面。为了回复用户,Chat 应用会返回 无需调用 Chat API 即可同步处理消息。学习内容 有关如何发送消息来响应互动的信息,请参阅 在 Google Chat 应用中接收和回复互动信息

Chat 如何显示和归因使用 Chat API 创建的消息

您可以使用以下代码调用 messages.create() 方法: 应用身份验证用户身份验证。 Chat 对消息发送者的界定有所不同 具体取决于您使用的身份验证类型。

以 Chat 应用的身份进行身份验证时, Chat 应用发送消息。

<ph type="x-smartling-placeholder">
</ph> 使用应用身份验证调用 messages.create() 方法。
图 1:通过应用身份验证,Chat 应用 消息内容。为表明发送者不是真人,Chat 会在其名称旁边显示 App

您作为用户进行身份验证后,Chat 应用会将 。Chat 还会将 Chat 应用通过显示消息名称来发送消息。

<ph type="x-smartling-placeholder">
</ph> 使用用户身份验证调用 messages.create() 方法。
图 2:通过用户身份验证,用户发送消息,Chat 会显示 聊天应用名称。

身份验证类型还决定了哪些消息传递功能和界面 您可以包含在消息中的名称借助应用身份验证 聊天应用可以发送包含富文本、 基于卡片的界面和交互式小部件。 由于 Chat 用户只能在消息中发送短信,因此您可以 使用用户身份验证创建邮件时仅包含文本。 详细了解消息功能 功能的详细信息,请参阅 Google Chat 消息概览

本指南介绍了如何使用这两种身份验证类型来发送邮件 使用 Chat API。

前提条件

Node.js

Python

Java

Apps 脚本

以 Chat 应用的身份发送消息

本部分介绍如何发送包含文本、卡片和 交互式配件微件 应用身份验证

通过应用身份验证发送消息
图 4. Chat 应用会向以下应用发送消息: 卡片和一个配件按钮

若要使用应用身份验证调用 messages.create(),您必须指定 以下字段:

  • chat.bot 授权范围
  • Space资源 。Chat 应用必须 聊天室成员。
  • Message 要创建的资源。要定义消息的内容,您可以在 富文本 (text), 一个或多个卡片接口 (cardsV2), 或者两者兼有

您还可以选择添加以下内容:

以下代码展示了 Chat 应用如何 可以发送通过 Chat 应用发布的消息,消息中包含以下内容: 文本、卡片以及消息底部的可点击按钮:

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 脚本

聊天/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);
}

如需运行此示例,请将 SPACE_NAME 替换为 空间的 name 字段。 可通过调用 spaces.list() 方法 或者通过聊天室网址添加

在邮件底部添加互动微件

在本指南的第一个代码示例中, Chat 应用消息在 称为配件微件。配件微件 。您可以使用这些微件 用户可通过多种方式与您的消息互动,包括:

  • 对消息的准确性或满意度进行评分。
  • 报告消息或 Chat 应用存在的问题。
  • 打开指向相关内容(例如文档)的链接。
  • 在 Chat 应用中关闭或延后类似消息 特定时间段内的效果

如需添加配件微件,请添加 accessoryWidgets[] 字段,然后指定所需的一个或多个微件 。

下图显示了将 包含配件微件的短信,以便用户对自己的体验进行评分 使用 Chat 应用。

<ph type="x-smartling-placeholder">
</ph> 配件微件。
图 5:带有 文本和配件微件。

下面显示了使用 两个配件按钮。当用户点击某个按钮时, 函数(例如 doUpvote)处理交互:

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

私下发送消息

聊天应用可以私下发送消息 消息仅对聊天室中的特定用户可见。当 聊天应用会发送一条私信 会显示一个标签,通知用户相应邮件仅对他们可见。

要使用 Chat API 以私密方式发送消息,请指定 privateMessageViewer 字段。要指定用户,请将值设置为 User 资源, 代表 Chat 用户。您还可以使用 name 字段的 User 资源,如以下示例所示:

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

如需使用此示例,请将 USER_ID 用户的唯一 ID,例如 12345678987654321hao@cymbalgroup.com。如需详细了解如何指定用户,请参阅 识别并指定 Google Chat 用户

要以私密方式发送消息,您必须在请求中省略以下内容:

代表用户发送短信

本部分介绍了如何使用 用户身份验证。 借助用户身份验证,邮件内容只能包含文本 并且必须省略仅适用于 聊天应用,包括卡片界面和交互式微件。

通过用户身份验证发送消息
图 3. Chat 应用可通过以下应用发送短信: 。

若要使用用户身份验证调用 messages.create(),您必须指定 以下字段:

  • 授权范围 此方法支持用户身份验证。以下示例使用 chat.messages.create 范围。
  • Space资源 。通过身份验证的用户必须是 空间。
  • Message 要创建的资源。要定义消息的内容,您必须在代码中添加 text 字段。

您还可以选择添加以下内容:

  • messageId 字段,可让您 为消息命名以便在其他 API 请求中使用。
  • thread.threadKeymessageReplyOption 字段 发起或回复讨论帖。如果聊天室没有 使用线程处理,系统会忽略此字段。

以下代码展示了 Chat 应用如何 可以代表经过身份验证的用户在指定空间中发送短信:

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 脚本

聊天/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);
}

如需运行此示例,请将 SPACE_NAME 替换为 空间的 name 字段。可通过调用 spaces.list() 方法 或者通过聊天室网址添加

在消息串中发起或回复消息

对于使用话题的聊天室: 您可以指定新消息是发起会话还是回复 现有线程

默认情况下,您使用 Chat API 创建的消息会发起新的 线程。为方便识别该会话并稍后回复,您可以指定一个 线程键:

如需创建回复现有会话的消息,请执行以下操作:

  • 在您的请求正文中,添加 thread 字段。如果已设置,您可以 指定 threadKey 创建的所有文件否则,您必须使用 name 线程。
  • 指定查询参数 messageReplyOption

以下代码展示了 Chat 应用如何 可以发送短信,而相应短信会发起或回复由 键:

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 脚本

聊天/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);
}

如需运行此示例,请替换以下内容:

  • THREAD_KEY:聊天室中的现有消息串键,或 来创建新线程,这是线程的唯一名称。
  • SPACE_NAME:聊天室的 ID name 字段。可通过调用 spaces.list() 方法 或者通过聊天室网址添加

为消息命名

如需在将来的 API 调用中检索或指定消息,您可以为消息命名 方法是在 messages.create() 请求中设置 messageId 字段。 通过为消息命名,您可以指定消息,而无需存储 消息的资源名称中系统分配的 ID(以 name 字段)。

例如,如需使用 get() 方法检索消息,您可以使用 资源名称指定要检索的消息。资源名称为 格式为 spaces/{space}/messages/{message},其中 {message} 表示 系统分配的 ID 或您在创建 消息。

要命名消息,请在 messageId 字段。messageId 字段用于设置 clientAssignedMessageId Message 资源的指定字段。

您只能在创建消息时为其命名。您不能命名或 修改现有消息的自定义 ID。自定义 ID 必须符合以下要求 要求:

  • client- 开头。例如,client-custom-name 是有效的自定义 但 custom-name 不是。
  • 最多包含 63 个字符,且只能包含小写字母、数字和 连字符。
  • 在聊天室中是唯一的。Chat 应用无法使用 为不同的消息使用相同的自定义 ID。

以下代码展示了 Chat 应用如何 可以代表 经过身份验证的用户:

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 脚本

聊天/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);
}

如需运行此示例,请替换以下内容:

  • SPACE_NAME:聊天室的 ID name 字段。可通过调用 spaces.list() 方法 或者通过聊天室网址添加
  • MESSAGE-ID:以消息开头的消息的名称 和custom-。该 ID 必须与 指定聊天室中的 Chat 应用。

问题排查

当 Google Chat 应用或 card 会返回错误, 聊天界面会显示一条内容为“出了点问题”的消息。 或“无法处理您的请求”。有时,Chat 界面 不会显示任何错误消息,但 Chat 应用或 卡片会产生意外结果;例如,卡片消息 。

虽然 Chat 界面中可能不会显示错误消息, 提供描述性错误消息和日志数据,以帮助您修正错误 启用 Chat 应用的错误日志记录时。如需观看方面的帮助, 请参阅 排查并修正 Google Chat 错误