发送消息

本指南介绍了 Google Chat 应用可通过哪些方式 消息:

  • 通过回复用户,实时发送短信和卡片消息 互动
  • 调用以下对象的 create 方法来异步发送文本和卡片消息: Message 资源。
  • 发起或回复消息串。
  • 发送和命名消息。

通过 Message 资源 代表 文本卡片 消息。您可以 在 Google Chat API 中通过调用 creategetupdatedelete 消息 相应的方法有关短信和卡片消息的详情,请参阅 Google Chat 消息概览

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

不要对 Message 资源调用 create 方法, 使用 Google Chat API 异步发送文本或卡片消息, Google Chat 应用还可以创建消息来响应用户在 实时更新。响应用户互动不需要身份验证, 支持其他类型的消息,包括互动式对话框和链接 预览。有关详情,请参阅 在 Google Chat 应用中接收和回复互动信息

前提条件

Node.js

Python

  • Google Workspace 有权访问 Google Chat
  • Python 3.6 或更高版本
  • pip 软件包管理工具
  • 适用于 Python 的最新 Google 客户端库。若要安装或更新这些应用 在命令行界面中运行以下命令:

    pip3 install --upgrade google-api-python-client google-auth
    
  • 一个已启用并配置了 Google Chat API 的 Google Cloud 项目。有关具体步骤,请参阅 构建 Google Chat 应用
  • 为 Chat 应用配置发送授权 异步消息无需授权配置即可发送 实时推送消息

Apps 脚本

发送短信

本节介绍如何通过以下两种方式发送短信:

  • 通过响应用户互动来实时发送短信。
  • 通过异步调用 Google Chat API 来发送短信。

实时发送短信

在此示例中,您的 Chat 应用会创建并发送 消息。如需了解 新手入门用户,请参阅 通过实用的新手入门流程开始使用人员和聊天室

在用户添加您的 Chat 应用时发送短信 聊天室,您的 Chat 应用 响应 ADDED_TO_SPACE 互动事件。回复 ADDED_TO_SPACE 互动事件,请使用以下代码:

Node.js

/**
 * Sends an onboarding message when the Chat app is added to a space.
 *
 * @param {Object} event The event object from Chat API.
 * @return {Object} Response from the Chat app. An onboarding message that
 * introduces the app and helps people get started with it.
 */
exports.onMessage = function onMessage(req, res) {
  if (req.method === 'GET' || !req.body.message) {
    res.send(
      'Hello! This function is meant to be used in a Google Chat space.');
  }

  // Send an onboarding message when added to a Chat space
  if (req.body.type === 'ADDED_TO_SPACE') {
    res.json({
      'text': 'Hi, Cymbal at your service. I help you manage your calendar
      from Google Chat. Take a look at your schedule today by typing
      `/checkCalendar`, or schedule a meeting with `/scheduleMeeting`. To
      learn what else I can do, type `/help`.'
    });
  }
};

Apps 脚本

/**
 * Sends an onboarding message when the Chat app is added to a space.
 *
 * @param {Object} event The event object from Chat API.
 * @return {Object} Response from the Chat app. An onboarding message that
 * introduces the app and helps people get started with it.
 */
function onAddToSpace(event) {

  return {
    'text': 'Hi, Cymbal at your service. I help you manage your calendar
    from Google Chat. Take a look at your schedule today by typing
    `/checkCalendar`, or schedule a meeting with `/scheduleMeeting`. To learn
    what else I can do, type `/help`.'
  }
}

该代码示例会返回以下文本消息:

新手入门消息示例。

异步发送短信

以下部分介绍了如何使用 应用身份验证和用户身份验证。

如需发送短信,请在请求中传递以下内容:

  • 使用应用身份验证时,请指定 chat.bot 授权范围。包含 用户身份验证时,请指定 chat.messages.create 授权范围。
  • 调用 create 方法Message 资源

通过应用身份验证发送短信

下面展示了如何发送短信 应用身份验证

Python

  1. 在您的工作目录中,创建一个名为 chat_create_text_message_app.py
  2. chat_create_text_message_app.py 中添加以下代码:

    from apiclient.discovery import build
    from google.oauth2 import service_account
    
    # Specify required scopes.
    SCOPES = ['https://www.googleapis.com/auth/chat.bot']
    
    # Specify service account details.
    CREDENTIALS = service_account.Credentials.from_service_account_file(
        'credentials.json', scopes=SCOPES)
    
    # Build the URI and authenticate with the service account.
    chat = build('chat', 'v1', credentials=CREDENTIALS)
    
    # Create a Chat message.
    result = chat.spaces().messages().create(
    
        # The space to create the message in.
        #
        # Replace SPACE with a space name.
        # Obtain the space name from the spaces resource of Chat API,
        # or from a space's URL.
        parent='spaces/SPACE',
    
        # The message to create.
        body={'text': 'Hello, world!'}
    
    ).execute()
    
    print(result)
    
  3. 在代码中,将 SPACE 替换为聊天室名称, 您可以从 spaces.list() 方法 或通过聊天室网址发送。

  4. 在您的工作目录中,构建并运行该示例:

    python3 chat_create_text_message_app.py
    

Chat API 会返回 Message 用于详细说明所发送的邮件

通过用户身份验证发送短信

下面展示了如何发送短信 用户身份验证

Python

  1. 在您的工作目录中,创建一个名为 chat_create_text_message_user.py
  2. chat_create_text_message_user.py 中添加以下代码:

    import os.path
    
    from google.auth.transport.requests import Request
    from google.oauth2.credentials import Credentials
    from google_auth_oauthlib.flow import InstalledAppFlow
    from googleapiclient.discovery import build
    from googleapiclient.errors import HttpError
    
    # Define your app's authorization scopes.
    # When modifying these scopes, delete the file token.json, if it exists.
    SCOPES = ["https://www.googleapis.com/auth/chat.messages.create"]
    
    def main():
        '''
        Authenticates with Chat API via user credentials,
        then creates a text message in a Chat space.
        '''
    
        # Start with no credentials.
        creds = None
    
        # Authenticate with Google Workspace
        # and get user authorization.
        flow = InstalledAppFlow.from_client_secrets_file(
                        'client_secrets.json', SCOPES)
        creds = flow.run_local_server()
    
        # Build a service endpoint for Chat API.
        chat = build('chat', 'v1', credentials=creds)
    
        # Use the service endpoint to call Chat API.
        result = chat.spaces().messages().create(
    
            # The space to create the message in.
            #
            # Replace SPACE with a space name.
            # Obtain the space name from the spaces resource of Chat API,
            # or from a space's URL.
            parent='spaces/SPACE',
    
            # The message to create.
            body={'text': 'Hello, world!'}
    
        ).execute()
    
        # Prints details about the created message.
        print(result)
    
    if __name__ == '__main__':
        main()
    
  3. 在代码中,将 SPACE 替换为聊天室名称, 您可以从 spaces.list() 方法(在 Chat API,或通过聊天室网址添加。

  4. 在您的工作目录中,构建并运行该示例:

    python3 chat_create_text_message_user.py
    

Chat API 会返回 Message 用于详细说明所发送的邮件

发送卡片消息

本部分介绍如何通过以下两种方式发送卡片消息:

  • 通过响应用户互动来实时发送卡片消息。
  • 通过异步调用 Google Chat API 发送卡片消息。

实时发送卡片消息

聊天应用可以创建卡片消息来回复用户 例如当用户向 Chat 应用发送 消息或将 Chat 应用添加到聊天室。了解详情 有关如何响应用户交互的信息,请参阅接收和响应 Chat 应用互动 事件

在此示例中,用户向 Chat 扩展应用发送消息 并且 Chat 应用通过发送卡片消息进行响应 (显示用户名称和头像图片):

一个 Chat 应用以一张卡片(包含发送者的显示名称和头像)进行回复
图片。

Node.js

node/avatar-app/index.js
/**
 * Google Cloud Function that responds to messages sent from a
 * Google Chat room.
 *
 * @param {Object} req Request sent from Google Chat room
 * @param {Object} res Response to send back
 */
exports.helloChat = function helloChat(req, res) {
  if (req.method === 'GET' || !req.body.message) {
    res.send('Hello! This function is meant to be used in a Google Chat ' +
      'Room.');
  }

  const sender = req.body.message.sender.displayName;
  const image = req.body.message.sender.avatarUrl;

  const data = createMessage(sender, image);

  res.send(data);
};

/**
 * Creates a card with two widgets.
 * @param {string} displayName the sender's display name
 * @param {string} imageUrl the URL for the sender's avatar
 * @return {Object} a card with the user's avatar.
 */
function createMessage(displayName, imageUrl) {
  const cardHeader = {
    title: `Hello ${displayName}!`,
  };

  const avatarWidget = {
    textParagraph: {text: 'Your avatar picture: '},
  };

  const avatarImageWidget = {
    image: {imageUrl},
  };

  const avatarSection = {
    widgets: [
      avatarWidget,
      avatarImageWidget,
    ],
  };

  return {
    text: 'Here\'s your avatar',
    cardsV2: [{
      cardId: 'avatarCard',
      card: {
        name: 'Avatar Card',
        header: cardHeader,
        sections: [avatarSection],
      }
    }],
  };
}

Python

python/avatar-app/main.py
from typing import Any, Mapping

import flask
import functions_framework


# Google Cloud Function that responds to messages sent in
# Google Chat.
#
# @param {Object} req Request sent from Google Chat.
# @param {Object} res Response to send back.
@functions_framework.http
def hello_chat(req: flask.Request) -> Mapping[str, Any]:
  if req.method == "GET":
    return "Hello! This function must be called from Google Chat."

  request_json = req.get_json(silent=True)

  display_name = request_json["message"]["sender"]["displayName"]
  avatar = request_json["message"]["sender"]["avatarUrl"]

  response = create_message(name=display_name, image_url=avatar)

  return response


# Creates a card with two widgets.
# @param {string} name the sender's display name.
# @param {string} image_url the URL for the sender's avatar.
# @return {Object} a card with the user's avatar.
def create_message(name: str, image_url: str) -> Mapping[str, Any]:
  avatar_image_widget = {"image": {"imageUrl": image_url}}
  avatar_text_widget = {"textParagraph": {"text": "Your avatar picture:"}}
  avatar_section = {"widgets": [avatar_text_widget, avatar_image_widget]}

  header = {"title": f"Hello {name}!"}

  cards = {
      "text": "Here's your avatar",
      "cardsV2": [
          {
              "cardId": "avatarCard",
              "card": {
                  "name": "Avatar Card",
                  "header": header,
                  "sections": [avatar_section],
              },
          }
      ]
  }

  return cards

Apps 脚本

此示例通过返回 卡片 JSON。 您还可以使用 Apps 脚本卡片服务

apps-script/avatar-app/hello-chat.gs
/**
 * Responds to a MESSAGE event in Google Chat.
 *
 * @param {Object} event the event object from Google Chat
 */
function onMessage(event) {
  const displayName = event.message.sender.displayName;
  const avatarUrl = event.message.sender.avatarUrl;

  return createMessage(displayName, avatarUrl);
}

/**
 * Creates a card with two widgets.
 * @param {string} displayName the sender's display name
 * @param {string} avatarUrl the URL for the sender's avatar
 * @return {Object} a card with the sender's avatar.
 */
function createMessage(displayName, avatarUrl) {
  const cardHeader = {
    title: `Hello ${displayName}!`
  };

  const avatarWidget = {
    textParagraph: {text: 'Your avatar picture: '}
  };

  const avatarImageWidget = {
    image: {imageUrl: avatarUrl}
  };

  const avatarSection = {
    widgets: [
      avatarWidget,
      avatarImageWidget
    ],
  };

  return {
    text: 'Here\'s your avatar',
    cardsV2: [{
      cardId: 'avatarCard',
      card: {
        name: 'Avatar Card',
        header: cardHeader,
        sections: [avatarSection],
      }
    }],
  };
}

异步发送卡片消息

要发送 卡片消息, 请在请求中传递以下内容:

  • 使用应用身份验证时,请指定 chat.bot 授权范围。禁止的行为 发送包含用户身份验证的卡片消息。
  • 调用 create 方法Message 资源

以下是卡片消息的示例:

使用 Chat API 发送的卡片消息。

以下是通过应用身份验证发送卡片消息的方法:

Python

  1. 在您的工作目录中,创建一个名为 chat_create_card_message.py
  2. chat_create_card_message.py 中添加以下代码:

    from apiclient.discovery import build
    from google.oauth2 import service_account
    
    # Specify required scopes.
    SCOPES = ['https://www.googleapis.com/auth/chat.bot']
    
    # Specify service account details.
    CREDENTIALS = service_account.Credentials.from_service_account_file(
        'credentials.json', scopes=SCOPES)
    
    # Build the URI and authenticate with the service account.
    chat = build('chat', 'v1', credentials=CREDENTIALS)
    
    # Create a Chat message.
    result = chat.spaces().messages().create(
    
        # The space to create the message in.
        #
        # Replace SPACE with a space name.
        # Obtain the space name from the spaces resource of Chat API,
        # or from a space's URL.
        parent='spaces/SPACE',
    
        # The message to create.
        body=
        {
          'cardsV2': [{
            'cardId': 'createCardMessage',
            'card': {
              'header': {
                'title': 'A card message!',
                'subtitle': 'Created with the Chat API',
                'imageUrl': 'https://developers.google.com/chat/images/chat-product-icon.png',
                'imageType': 'CIRCLE'
              },
              'sections': [
                {
                  'widgets': [
                    {
                      'buttonList': {
                        'buttons': [
                          {
                            'text': 'Read the docs!',
                            'onClick': {
                              'openLink': {
                                'url': 'https://developers.google.com/chat'
                              }
                            }
                          }
                        ]
                      }
                    }
                  ]
                }
              ]
            }
          }]
        }
    
    ).execute()
    
    print(result)
    
  3. 在代码中,将 SPACE 替换为聊天室名称, 您可以从 spaces.list 方法 或通过聊天室网址发送。

  4. 在您的工作目录中,构建并运行该示例:

    python3 chat_create_card_message.py
    

发起或回复消息串

如要发起消息串,请发送消息并离开 thread.name 为空;创建话题时,Google Chat 会填充该消息。(可选) 自定义线程的名称,指定 thread.threadKey 字段。

要回复某个消息串,请发送一条消息,指定该会话的 threadKeyname 字段。消息串是否由其他人创建 Chat 应用,必须使用 thread.name 字段。

如果未找到匹配的讨论帖,您可以指定 通过设置为 messageReplyOption 字段。

如果状态为 messageReplyOption 设置之后,您还必须设置 thread.namethread.threadKey

下面展示了如何使用定义为 threadKey 字段的会话发起或回复会话 nameOfThread

Python

  1. 在您的工作目录中,创建一个名为 chat_create_message_thread.py
  2. chat_create_message_thread.py 中添加以下代码:

    from apiclient.discovery import build
    from google.oauth2 import service_account
    
    # Specify required scopes.
    SCOPES = ['https://www.googleapis.com/auth/chat.bot']
    
    # Specify service account details.
    CREDENTIALS = service_account.Credentials.from_service_account_file(
        'credentials.json', scopes=SCOPES)
    
    # Build the URI and authenticate with the service account.
    chat = build('chat', 'v1', credentials=CREDENTIALS)
    
    # Create a Chat message.
    result = chat.spaces().messages().create(
    
        # The space to create the message in.
        #
        # Replace SPACE with a space name.
        # Obtain the space name from the spaces resource of Chat API,
        # or from a space's URL.
        parent='spaces/SPACE',
    
        # Whether to start a thread or reply to an existing one.
        #
        # Required when threading is enabled in a space unless starting a
        # thread.  Ignored in other space types. Threading is enabled when
        # space.spaceThreadingState is THREADED_MESSAGES.
        #
        # REPLY_MESSAGE_FALLBACK_TO_NEW_THREAD replies to an existing thread
        # if one exists, otherwise it starts a new one.
        messageReplyOption='REPLY_MESSAGE_FALLBACK_TO_NEW_THREAD',
    
        # The message body.
        body={
    
            # The message to create.
            'text': 'Start or reply to another message in a thread!',
    
            # The thread to start or reply to.
            'thread': {
                'threadKey': 'nameOfThread'
            }
        }
    
    ).execute()
    
    print(result)
    
  3. 在代码中,将 SPACE 替换为聊天室名称, 您可以从 spaces.list 方法 或通过聊天室网址发送。

  4. 在您的工作目录中,构建并运行该示例:

    python3 chat_create_message_thread.py
    

Chat API 会返回 Message 用于详细说明所发送的邮件

为消息命名

本部分介绍了如何通过为消息串设置自定义 ID 来命名消息 消息。您可以使用自定义 ID 获取、更新或删除邮件。自定义 ID 可让您指定邮件内容,而无需存储 消息的资源名称(在 name 字段中表示)。资源 生成名称的 响应正文

例如,如需使用 get() 方法检索消息,您可以使用 资源名称指定要检索的消息。资源名称为 格式为 spaces/{space}/messages/{message},其中 {message} 表示 系统分配的 ID如果您已为该消息命名,则可将 将 {message} 的值替换为自定义 ID。

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

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

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

以下是使用自定义 ID 发送消息的方法:

Python

  1. 在您的工作目录中,创建一个名为 chat_create_named_message.py
  2. chat_create_named_message.py 中添加以下代码:

    from apiclient.discovery import build
    from google.oauth2 import service_account
    
    # Specify required scopes.
    SCOPES = ['https://www.googleapis.com/auth/chat.bot']
    
    # Specify service account details.
    CREDENTIALS = service_account.Credentials.from_service_account_file(
        'credentials.json', scopes=SCOPES)
    
    # Build the URI and authenticate with the service account.
    chat = build('chat', 'v1', credentials=CREDENTIALS)
    
    # Create a Chat message with a custom name.
    result = chat.spaces().messages().create(
    
        # The space to create the message in.
        #
        # Replace SPACE with a space name.
        # Obtain the space name from the spaces resource of Chat API,
        # or from a space's URL.
        parent='spaces/SPACE',
    
        # Custom name for the message used to facilitate later operations.
        messageId='client-NAME',
    
        # The message to create.
        body={'text': 'Hello, world!'}
    
    ).execute()
    
    print(result)
    
  3. 在代码中进行以下替换:

    • SPACE:要执行此操作的聊天室的 ID 发布消息,您可以从 spaces.list 方法 或通过聊天室网址发送。
    • NAME:消息的自定义名称。
  4. 在您的工作目录中,构建并运行该示例:

    python3 chat_create_named_message.py
    

Chat API 会返回 Message

在邮件底部添加互动微件

您也可以选择为消息附加配件微件。 配件微件会显示在消息中的任何文本或卡片后面。您可以使用这些 微件以多种方式提示用户与您的消息互动,包括 以下:

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

如需添加配件微件,请添加 accessoryWidgets[] 对象,并指定一个或多个 AccessoryWidgets 添加的数据消息必须向聊天室中的所有人显示 (你无法将配件微件添加到私信中)。

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

配件 widget 示例

以下代码示例展示了此消息的 JSON。当用户点击 按钮之一,互动就会触发相应的功能(例如 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",
             }
           }
         }
       ]
     }
   }
 ]

以私密方式发送消息

聊天应用能够以私密方式发送短信和卡片消息, 消息仅对聊天室中的一位用户可见。要以私密方式发送消息,请执行以下操作: 您需要在消息中指定 privateMessageViewer 字段。仅限 聊天应用可以发送私信。发送私信 必须使用应用身份验证。

有关详情,请参阅向 Google Chat 发送私信 用户

问题排查

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

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