Inviare un messaggio utilizzando l'API Google Chat

Questa guida spiega come chiamare l'API Google Chat messages.create() per eseguire una delle seguenti operazioni:

  • Inviare messaggi che contengono testo, schede e widget interattivi.
  • Inviare messaggi privati a uno specifico utente di Chat.
  • Avviare o rispondere a un thread di messaggi.
  • Assegna un nome a un messaggio per poterlo specificare in un'altra API Chat richieste.

La dimensione massima del messaggio (compreso testo o schede) è di 32.000 byte. Per inviare un messaggio che supera queste dimensioni, l'app Chat ma devono inviare più messaggi.

Oltre a chiamare il metodo messages.create(), le app di Chat possono creare e inviare messaggi per rispondere alle interazioni degli utenti, ad esempio la pubblicazione di un messaggio di benvenuto visualizzato dopo che un utente ha aggiunto l'app Chat a un spazio. Quando rispondono alle interazioni, le app di chat possono usare Tipi di funzionalità di messaggistica, incluse finestre di dialogo interattive e anteprima dei link interfacce. Per rispondere a un utente, l'app Chat restituisce il messaggio in modo sincrono, senza chiamare l'API Chat. Per ulteriori informazioni sull'invio di messaggi per rispondere alle interazioni, vedi Ricevere e rispondere alle interazioni con l'app Google Chat.

In che modo Chat mostra e attribuisce i messaggi creati con l'API Chat

Puoi chiamare il metodo messages.create() utilizzando autenticazione app e autenticazione dell'utente. Chat attribuisce il mittente del messaggio in modo diverso a seconda del tipo di autenticazione utilizzato.

Quando esegui l'autenticazione come app Chat, l'app Chat invia il messaggio.

Chiamata del metodo messages.create() con l'autenticazione dell'app.
Figura 1: con l'autenticazione app, l'app Chat invia il messaggio. Per indicare che il mittente non è una persona, in Chat viene visualizzato App accanto al nome.

Quando esegui l'autenticazione come utente, l'app Chat invia le per conto dell'utente. Chat attribuisce inoltre Chat al messaggio visualizzandone il nome.

Chiamata del metodo messages.create() con l'autenticazione utente.
Figura 2: con l'autenticazione utente, l'utente invia il messaggio e Chat visualizza Il nome dell'app di chat accanto al nome dell'utente.

Il tipo di autenticazione determina anche le funzionalità e le interfacce di messaggistica che puoi includere nel messaggio. Con l'autenticazione delle app, Le app di chat possono inviare messaggi in formato RTF, interfacce basate su schede e widget interattivi. Dato che gli utenti di Chat possono inviare solo testo nei loro messaggi, puoi Includere solo testo quando si creano messaggi utilizzando l'autenticazione utente. Per scoprire di più sui messaggi disponibili per l'API Chat, consulta le Panoramica dei messaggi di Google Chat.

Questa guida spiega come utilizzare entrambi i tipi di autenticazione per inviare un messaggio con l'API Chat.

Prerequisiti

Node.js

Python

Java

Apps Script

Inviare un messaggio come app Chat

Questa sezione spiega come inviare messaggi contenenti testo, schede e widget accessori interattivi utilizzando autenticazione delle app.

Messaggio inviato con autenticazione delle app
. Figura 4. Un'app di Chat invia un messaggio con testo, una carta e un pulsante accessorio.

Per chiamare messages.create() utilizzando l'autenticazione delle app, devi specificare il seguenti campi della richiesta:

  • L'ambito di autorizzazione chat.bot.
  • La risorsa Space in cui vuoi pubblicare il messaggio. L'app Chat deve essere membro dello spazio.
  • La Message risorsa da creare. Per definire i contenuti del messaggio, puoi includere RTF (text), una o più interfacce delle schede (cardsV2), o entrambe le cose.

Se vuoi, puoi includere quanto segue:

Il codice seguente mostra un esempio di come un'app di Chat può inviare un messaggio pubblicato come app Chat che contiene testo, una scheda e un pulsante cliccabile in fondo al messaggio:

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

Per eseguire questo esempio, sostituisci SPACE_NAME con l'ID di dello spazio name. Puoi ottenere l'ID chiamando il metodo Metodo spaces.list() oppure dall'URL dello spazio.

Aggiungere widget interattivi nella parte inferiore di un messaggio

Nel primo esempio di codice di questa guida, Il messaggio dell'app di chat mostra un pulsante cliccabile nella parte inferiore del messaggio, noto come widget accessorio. Widget accessori vengono visualizzati dopo un testo o una scheda in un messaggio. Puoi usare questi widget per chiedere agli utenti di interagire con il tuo messaggio in vari modi, inclusi i seguenti:

  • Valuta l'accuratezza o la soddisfazione di un messaggio.
  • Segnala un problema relativo al messaggio o all'app Chat.
  • Apri un link ai contenuti correlati, ad esempio alla documentazione.
  • Ignorare o posticipare messaggi simili dall'app Chat per un determinato periodo di tempo.

Per aggiungere widget accessori, includi i accessoryWidgets[] nel corpo della richiesta e specificare uno o più widget che desideri da includere.

L'immagine seguente mostra un'app di Chat che aggiunge un SMS con widget accessori per consentire agli utenti di valutare la loro esperienza con l'app Chat.

Widget accessorio.
Figura 5: un messaggio dell'app Chat con widget di testo e accessori.

Di seguito è riportato il corpo della richiesta che crea un messaggio di testo con due pulsanti accessori. Quando un utente fa clic su un pulsante, viene restituito il codice (ad esempio doUpvote) elabora l'interazione:

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

Inviare un messaggio in privato

Le app di chat possono inviare messaggi privati in modo che è visibile solo a un utente specifico nello spazio. Quando L'app Chat invia un messaggio privato, il messaggio mostra un'etichetta che comunica all'utente che il messaggio è visibile solo a lui.

Per inviare un messaggio privatamente utilizzando l'API Chat, specifica la privateMessageViewer nel corpo della richiesta. Per specificare l'utente, imposta il valore su la risorsa User rappresenta l'utente di Chat. Puoi utilizzare anche name del Risorsa User, come mostrato nell'esempio seguente:

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

Per utilizzare questo esempio, sostituisci USER_ID con un ID univoco per l'utente, ad esempio 12345678987654321 o hao@cymbalgroup.com. Per ulteriori informazioni su come specificare gli utenti, consulta Identificare e specificare gli utenti di Google Chat.

Per inviare un messaggio privatamente, devi omettere quanto segue nella richiesta:

Invia un messaggio per conto di un utente

Questa sezione spiega come inviare messaggi per conto di un utente utilizzando autenticazione degli utenti. Con l'autenticazione utente, i contenuti del messaggio possono contenere solo testo e devono omettere le funzionalità di messaggistica disponibili solo App di chat, incluse interfacce delle schede e widget interattivi.

Messaggio inviato con autenticazione utente
. Figura 3. Un'app di Chat invia un messaggio su per conto di un utente.

Per chiamare messages.create() utilizzando l'autenticazione utente, devi specificare il seguenti campi della richiesta:

  • Un ambito di autorizzazione che supporta l'autenticazione utente per questo metodo. Il seguente esempio utilizza nell'ambito chat.messages.create.
  • La risorsa Space in cui vuoi pubblicare il messaggio. L'utente autenticato deve essere membro del spazio.
  • La Message risorsa da creare. Per definire i contenuti del messaggio, devi includere la sezione text .

Se vuoi, puoi includere quanto segue:

Il codice seguente mostra un esempio di come un'app di Chat possono inviare un messaggio in un determinato spazio per conto di un utente autenticato:

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

Per eseguire questo esempio, sostituisci SPACE_NAME con l'ID di dello spazio name . Puoi ottenere l'ID chiamando il metodo Metodo spaces.list() oppure dall'URL dello spazio.

Avviare o rispondere in un thread

Per gli spazi che utilizzano i thread, puoi specificare se un nuovo messaggio avvia un thread o se risponde un thread esistente.

Per impostazione predefinita, i messaggi che crei utilizzando l'API Chat avviano una nuova . Per aiutarti a identificare il thread e a rispondere in un secondo momento, puoi specificare una chiave thread nella tua richiesta:

Per creare un messaggio che risponda a un thread esistente:

  • Nel corpo della richiesta, includi il campo thread. Se impostato, puoi specificare threadKey che hai creato. In caso contrario, devi utilizzare name del thread.
  • Specifica il parametro di query messageReplyOption.

Il codice seguente mostra un esempio di come un'app di Chat possono inviare un SMS che inizia o risponde a un determinato thread identificato da chiave di un determinato spazio per conto di un utente autenticato:

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

Per eseguire questo esempio, sostituisci quanto segue:

  • THREAD_KEY: una chiave thread esistente nello spazio oppure per creare un nuovo thread, un nome univoco per il thread.
  • SPACE_NAME: l'ID del parametro name . Puoi ottenere l'ID chiamando il metodo Metodo spaces.list() oppure dall'URL dello spazio.

Assegna un nome a un messaggio

Per recuperare o specificare un messaggio nelle chiamate API future, puoi assegnare un nome al messaggio impostando il campo messageId nella richiesta messages.create(). Assegnando un nome al messaggio puoi specificarlo senza dover archiviare il assegnato dal sistema dal nome della risorsa del messaggio (rappresentato nel name ).

Ad esempio, per recuperare un messaggio con il metodo get(), devi utilizzare il il nome della risorsa per specificare quale messaggio recuperare. Il nome della risorsa è nel formato spaces/{space}/messages/{message}, dove {message} rappresenta l'ID assegnato dal sistema o il nome personalizzato che hai impostato quando hai creato .

Per assegnare un nome a un messaggio, specifica un ID personalizzato nel messageId campo quando crei il messaggio. Il campo messageId consente di impostare il valore del parametro clientAssignedMessageId della risorsa Message.

Puoi assegnare un nome a un messaggio solo quando lo crei. Non puoi assegnare un nome o modificare un ID personalizzato per i messaggi esistenti. L'ID personalizzato deve soddisfare i seguenti requisiti requisiti:

  • Inizia con client-. Ad esempio, client-custom-name è un'entità personalizzata ID, ma custom-name non lo è.
  • Contiene fino a 63 caratteri e solo lettere minuscole, numeri e e trattini.
  • Sia univoco all'interno di uno spazio. Un'app di Chat non può utilizzare stesso ID personalizzato per messaggi diversi.

Il codice seguente mostra un esempio di come un'app di Chat può inviare un messaggio con un ID in un determinato spazio per conto di un utente autenticato:

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

Per eseguire questo esempio, sostituisci quanto segue:

  • SPACE_NAME: l'ID della proprietà name . Puoi ottenere l'ID chiamando il metodo Metodo spaces.list() oppure dall'URL dello spazio.
  • MESSAGE-ID: un nome per il messaggio che inizia con custom-. Deve essere univoco rispetto a qualsiasi altro nome di messaggio creato dal App di Chat nello spazio specificato.

Risoluzione dei problemi

Quando un'app Google Chat o card restituisce un errore, L'interfaccia di Chat mostra il messaggio "Si è verificato un problema". o "Impossibile elaborare la richiesta". A volte, l'UI di Chat non mostra alcun messaggio di errore, ma l'app Chat o la scheda restituisce un risultato inaspettato; Ad esempio, il messaggio di una scheda potrebbe non vengono visualizzate.

Anche se un messaggio di errore potrebbe non essere visualizzato nella UI di Chat, messaggi di errore descrittivi e dati di log che ti aiuteranno a correggere gli errori quando il logging degli errori per le app di chat è attivo. Per assistenza con la visualizzazione, il debug e la correzione degli errori, consulta Risolvere i problemi e correggere gli errori di Google Chat.