Cómo crear un mensaje de tarjeta

En esta página, se explica cómo crear y enviar mensajes basados en tarjetas como una app de Google Chat. Las tarjetas admiten un diseño definido, elementos interactivos de la IU (como botones) y rich media (como imágenes). Para obtener más información sobre las formas de usar las tarjetas, consulta Cómo diseñar IU dinámicas, interactivas y coherentes con tarjetas. Para obtener más información sobre los mensajes, consulta la descripción general de los mensajes de Google Chat.

Requisitos previos

Node.js

Nota: Las muestras de código de Node.js en esta guía están escritas para ejecutarse como una Google Cloud Function.

Python

Nota: Las muestras de código de Python en esta guía están escritas para ejecutarse como una función de Google Cloud Functions mediante Python 3.9.

Apps Script

Cómo crear mensajes de tarjetas

En esta sección, se describe cómo crear mensajes de tarjeta de dos maneras: respondiendo a una interacción del usuario y llamando a la API de Google Chat de forma asíncrona.

Responde a un usuario

Las apps de chat pueden crear mensajes de tarjeta para responder a una interacción del usuario, como cuando un usuario envía un mensaje a la app de Chat o agrega la app de Chat a un espacio. Si quieres obtener más información para responder a las interacciones del usuario, consulta Recibe y responde eventos de interacción de la app de Chat.

En este ejemplo, un usuario envía un mensaje a una app de Chat, y la app de Chat responde mediante un mensaje de tarjeta que muestra el nombre del usuario y la imagen de avatar del usuario:

Una app de Chat que responde con una tarjeta que muestra el nombre visible y la imagen de avatar del remitente.

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 Script

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],
      }
    }],
  };
}

Llama a la API de Google Chat

A continuación, se explica cómo crear un mensaje de tarjeta llamando de forma asíncrona a la API de Google Chat.

Llamar a la API de Chat de forma asíncrona requiere autenticación. Dado que solo las apps de Chat pueden crear mensajes de tarjeta, una app de Chat debe usar la autenticación de la app para crear y enviar mensajes de tarjeta (las apps de chat no pueden usar la autenticación de usuarios para enviar mensajes de tarjetas en nombre de los usuarios). Para obtener más información, consulta la descripción general de la autenticación de Google Chat.

En este ejemplo, se crea el siguiente mensaje de tarjeta mediante la autenticación de la app:

Un mensaje de tarjeta creado con la API de Google Chat
Figura 1: Un mensaje de tarjeta creado con la API de Chat.

Para configurar la autenticación y obtener información sobre cómo crear mensajes de forma asíncrona, consulta la guía de la API de Chat.

Python

  1. En el directorio de trabajo, crea un archivo llamado chat_create_card_message.py.
  2. Incluye el siguiente código en 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 Chat REST 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. En el código, reemplaza SPACE por el nombre de un espacio, que puedes obtener del método spaces.list() en la API de Chat, o bien desde la URL de un espacio.

  4. En el directorio de trabajo, compila y ejecuta la muestra:

    python3 chat_create_card_message.py
    

Si quieres obtener más información para trabajar con mensajes en la API de Chat, consulta los siguientes vínculos:

Solución de problemas

Cuando una app de Google Chat o una tarjeta muestran un error, la interfaz de Chat muestra un mensaje que dice “Se produjo un error” o “No se pudo procesar la solicitud”. A veces, la IU de Chat no muestra ningún mensaje de error, pero la app o tarjeta de Chat producen un resultado inesperado; por ejemplo, es posible que no aparezca un mensaje de tarjeta.

Aunque es posible que no se muestre un mensaje de error en la IU de Chat, hay mensajes de error descriptivos y datos de registro disponibles para ayudarte a corregir errores cuando se activa el registro de errores para apps de chat. Si necesitas ayuda para ver, depurar y corregir errores, consulta Cómo solucionar problemas de Google Chat.