发送消息

本指南介绍了 Google Chat 应用发送消息的不同方式:

  • 通过响应用户互动实时发送文本和卡片消息。
  • 通过对 Message 资源调用 create 方法异步发送文本和卡片消息。
  • 发起或回复消息会话。
  • 发送并命名消息。

Message 资源表示 Google Chat 中的文本卡片消息。您可以通过调用相应的方法,在 Google Chat API 中对消息执行 creategetupdatedelete 操作。如需详细了解文本和卡片消息,请参阅 Google Chat 消息概览

Google Chat 应用也可以创建消息来实时响应用户互动,而不是对 Google Chat API 的 Message 资源调用 create 方法来异步发送短信或卡片消息。响应用户互动不需要进行身份验证,并且支持其他类型的消息,包括互动对话框和链接预览。有关详情,请参阅接收和回复用户与 Google Chat 应用的互动情况

前提条件

Node.js

Python

  • Python 3.6 或更高版本
  • pip 软件包管理工具
  • 适用于 Python 的最新 Google 客户端库。如需安装或更新这些软件包,请在命令行界面中运行以下命令:

    pip3 install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib oauth2client
    
  • 已发布的 Chat 应用。如需创建和发布 Chat 应用,请参阅构建 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 授权范围。
  • Message 资源调用 create 方法

通过短信进行应用身份验证

使用应用身份验证发送短信的方法如下:

Python

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

    from httplib2 import Http
    from oauth2client.service_account import ServiceAccountCredentials
    from apiclient.discovery import build
    
    # Specify required scopes.
    SCOPES = ['https://www.googleapis.com/auth/chat.bot']
    
    # Specify service account details.
    CREDENTIALS = ServiceAccountCredentials.from_json_keyfile_name(
        'credentials.json', SCOPES)
    
    # Build the URI and authenticate with the service account.
    chat = build('chat', 'v1', http=CREDENTIALS.authorize(Http()))
    
    # 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 替换为聊天室名称,您可以通过 Chat API 中的 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 membership.
        print(result)
    
    if __name__ == '__main__':
        main()
    
  3. 在代码中,将 SPACE 替换为聊天室名称,您可以通过 Chat API 中的 spaces.list() 方法或聊天室的网址获取该名称。

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

    python3 chat_create_text_message_user.py
    

Chat API 会返回 Message 的实例,该实例详细说明了发送的消息。

发送卡消息

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

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

实时发送卡片消息

聊天应用可以创建卡片消息来响应用户互动,例如当用户向 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 {
    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 = {
      "cardsV2": [
          {
              "cardId": "avatarCard",
              "card": {
                  "name": "Avatar Card",
                  "header": header,
                  "sections": [avatar_section],
              },
          }
      ]
  }

  return cards

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 {
    cardsV2: [{
      cardId: 'avatarCard',
      card: {
        name: 'Avatar Card',
        header: cardHeader,
        sections: [avatarSection],
      }
    }],
  };
}

异步发送卡片消息

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

  • 使用应用身份验证时,请指定 chat.bot 授权范围。您不能发送进行用户身份验证的卡消息。
  • Message 资源调用 create 方法

以下是卡片消息的示例:

通过 Chat API 发送的卡片消息。

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

Python

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

    from httplib2 import Http
    from oauth2client.service_account import ServiceAccountCredentials
    from apiclient.discovery import build
    
    # Specify required scopes.
    SCOPES = ['https://www.googleapis.com/auth/chat.bot']
    
    # Specify service account details.
    CREDENTIALS = ServiceAccountCredentials.from_json_keyfile_name(
        'credentials.json', SCOPES)
    
    # Build the URI and authenticate with the service account.
    chat = build('chat', 'v1', http=CREDENTIALS.authorize(Http()))
    
    # 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 替换为聊天室名称,您可以通过 Chat API 中的 spaces.list 方法或聊天室网址获取该名称。

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

    python3 chat_create_card_message.py
    

发起或回复消息会话

如需启动消息线程,请发送消息并将 thread.name 留空;Google Chat 会在创建此线程时进行填充。(可选)如需自定义线程名称,请指定 thread.threadKey 字段。

如需回复某个消息线程,请发送一条消息,指明该线程的 threadKeyname 字段。如果会话是由人或其他 Chat 应用创建的,您必须使用 thread.name 字段。

如果未找到匹配的会话,您可以通过设置 messageReplyOption 字段来指定消息是应启动新会话,还是发布失败。

以下是启动或回复 threadKey 字段定义为 nameOfThread 的线程的方法:

Python

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

    from httplib2 import Http
    from oauth2client.service_account import ServiceAccountCredentials
    from apiclient.discovery import build
    
    # Specify required scopes.
    SCOPES = ['https://www.googleapis.com/auth/chat.bot']
    
    # Specify service account details.
    CREDENTIALS = ServiceAccountCredentials.from_json_keyfile_name(
        'credentials.json', SCOPES)
    
    # Build the URI and authenticate with the service account.
    chat = build('chat', 'v1', http=CREDENTIALS.authorize(Http()))
    
    # 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 替换为聊天室名称,您可以通过 Chat API 中的 spaces.list 方法或聊天室网址获取该名称。

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

    python3 chat_create_message_thread.py
    

Chat API 会返回 Message 的实例,该实例详细说明了发送的消息。

发送消息和命名消息

本部分介绍如何使用自定义名称发送消息。您可以使用消息名称获取更新删除消息。分配自定义名称还可让 Chat 应用召回消息,而无需保存发送消息时返回的响应正文中的消息 name

分配自定义名称不会替换生成的 name 字段,而是消息的资源名称。相反,它会将自定义名称设置为 clientAssignedMessageId 字段,您可以在处理后续操作(例如更新或删除消息)时引用该字段。

自定义名称具有以下要求:

  • client- 开头。例如,client-custom-name 是有效的自定义名称,但 custom-name 无效。
  • 只能包含小写字母、数字和连字符。
  • 长度不超过 63 个字符。
  • 发送消息时指定所使用的自定义名称会返回错误,但其他方法(如 updatedelete)会按预期发挥作用。

以下是发送消息和命名消息的方法:

Python

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

    from httplib2 import Http
    from oauth2client.service_account import ServiceAccountCredentials
    from apiclient.discovery import build
    
    # Specify required scopes.
    SCOPES = ['https://www.googleapis.com/auth/chat.bot']
    
    # Specify service account details.
    CREDENTIALS = ServiceAccountCredentials.from_json_keyfile_name(
        'credentials.json', SCOPES)
    
    # Build the URI and authenticate with the service account.
    chat = build('chat', 'v1', http=CREDENTIALS.authorize(Http()))
    
    # 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-custom-name',
    
        # The message to create.
        body={'text': 'Hello, world!'}
    
    ).execute()
    
    print(result)
    
  3. 在代码中,将 SPACE 替换为聊天室名称,您可以通过 Chat API 中的 spaces.list 方法或聊天室网址获取该名称。

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

    python3 chat_create_named_message.py
    

Chat API 会返回 Message 的实例,该实例详细说明了发送的消息。

排查问题

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

为 Chat 应用启用错误日志记录功能后,虽然 Chat 界面中可能不会显示错误消息,但借助描述性错误消息和日志数据,您可以修复相关错误。如需获取查看、调试和修正错误方面的帮助,请参阅排查和修正 Google Chat 错误