Inviare un messaggio utilizzando l'API Google Chat

Questa guida spiega come utilizzare il metodo create() nella risorsa Message dell'API Google Chat per eseguire una delle seguenti operazioni:

  • Inviare messaggi contenenti testo, schede e widget interattivi.
  • Inviare messaggi privati a un utente di Chat specifico.
  • Avviare o rispondere a un thread di messaggi.
  • Assegna un nome a un messaggio in modo da poterlo specificare in altre richieste dell'API Chat.

La dimensione massima del messaggio (incluso qualsiasi testo o scheda) è di 32.000 byte. Per inviare un messaggio che supera questa dimensione, l'app Chat deve inviare più messaggi.

Oltre a chiamare l'API Chat per creare messaggi, le app di Chat possono creare e inviare messaggi per rispondere alle interazioni degli utenti, ad esempio pubblicare un messaggio di benvenuto dopo che un utente aggiunge l'app di Chat a uno spazio. Quando rispondono alle interazioni, le app di chat possono utilizzare altri tipi di funzionalità di messaggistica, tra cui dialoghi interattivi e interfacce di anteprima dei link. Per rispondere a un utente, l'app Chat restituisce il messaggio in modo sincrono, senza chiamare l'API Chat. Per informazioni sull'invio di messaggi per rispondere alle interazioni, vedi Ricevere e rispondere alle interazioni con l'app Google Chat.

Come Chat visualizza e attribuisce i messaggi creati con l'API Chat

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

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

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

Quando ti autentichi come utente, l'app Chat invia il messaggio per conto dell'utente. Chat attribuisce anche l'app Chat al messaggio visualizzandone il nome.

Chiamata al metodo create() con l'autenticazione utente.
Figura 2: con l'autenticazione utente, l'utente invia il messaggio e Chat mostra il nome dell'app 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 che contengono testo RTF, interfacce basate su schede e widget interattivi. Poiché gli utenti di Chat possono inviare solo testo nei loro messaggi, puoi includere solo testo quando crei messaggi utilizzando l'autenticazione utente. Per scoprire di più sulle funzionalità di messaggistica disponibili per l'API Chat, consulta la Panoramica dei messaggi di Google Chat.

Questa guida spiega come utilizzare uno dei due 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 interattivi per accessori utilizzando l'autenticazione dell'app.

Messaggio inviato con l'autenticazione dell'app
Figura 4. Un'app di chat invia un messaggio con testo, una scheda e un pulsante accessorio.

Per chiamare il metodo CreateMessage() utilizzando l'autenticazione dell'app, devi specificare i seguenti campi nella richiesta:

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

In via facoltativa, puoi includere quanto segue:

Il seguente codice mostra un esempio di come un'app di chat può inviare un messaggio pubblicato come app di chat che contiene testo, una scheda e un pulsante su cui è possibile fare clic nella parte inferiore del 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 del campo name dello spazio. Puoi ottenere l'ID chiamando il metodo ListSpaces() o dall'URL dello spazio.

Aggiungere widget interattivi in fondo a un messaggio

Nel primo esempio di codice di questa guida, il messaggio dell'app di chat mostra un pulsante su cui è possibile fare clic nella parte inferiore del messaggio, noto come widget accessorio. I widget degli accessori vengono visualizzati dopo il testo o le schede di un messaggio. Puoi utilizzare questi widget per invitare gli utenti a interagire con il tuo messaggio in molti modi, tra cui:

  • Valuta l'accuratezza o la soddisfazione di un messaggio.
  • Segnala un problema relativo all'app Messaggi o Chat.
  • Aprire un link a contenuti correlati, ad esempio la documentazione.
  • Ignora o posticipa messaggi simili dall'app Chat per un periodo di tempo specifico.

Per aggiungere widget di accessori, includi il campo accessoryWidgets[] nel corpo della richiesta e specifica uno o più widget da includere.

L'immagine seguente mostra un'app Chat che aggiunge un messaggio di testo con widget accessori in modo che gli utenti possano valutare la loro esperienza con l'app Chat.

Widget Accessori.
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 accessorio. Quando un utente fa clic su un pulsante, la funzione corrispondente (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 privato

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

Per inviare un messaggio in privato utilizzando l'API Chat, specifica il campo privateMessageViewer nel corpo della richiesta. Per specificare l'utente, imposta il valore sulla risorsa User che rappresenta l'utente di Chat. Puoi anche utilizzare il campo name della 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 saperne di più su come specificare gli utenti, vedi Identificare e specificare gli utenti di Google Chat.

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

Inviare un messaggio per conto di un utente

Questa sezione spiega come inviare messaggi per conto di un utente utilizzando l'autenticazione utente. Con l'autenticazione utente, il contenuto del messaggio può contenere solo testo e deve omettere le funzionalità di messaggistica disponibili solo per le app di chat, tra cui interfacce di schede e widget interattivi.

Messaggio inviato con l&#39;autenticazione utente
Figura 3. Un'app di chat invia un messaggio di testo per conto di un utente.

Per chiamare il metodo CreateMessage() utilizzando l'autenticazione utente, devi specificare i seguenti campi nella richiesta:

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

In via facoltativa, puoi includere quanto segue:

Il seguente codice mostra un esempio di come un'app Chat può 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 del campo name dello spazio. Puoi ottenere l'ID chiamando il metodo ListSpaces() o dall'URL dello spazio.

Avviare o rispondere a un thread

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

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

  • Nel corpo della richiesta, specifica il campo thread.threadKey.
  • Specifica il parametro di query messageReplyOption per determinare cosa succede se la chiave esiste già.

Per creare un messaggio che risponde a un thread esistente:

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

Il seguente codice mostra un esempio di come un'app Chat può inviare un messaggio di testo che avvia o risponde a un determinato thread identificato dalla 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 di thread esistente nello spazio oppure, per creare un nuovo thread, un nome univoco per il thread.
  • SPACE_NAME: l'ID del campo name dello spazio. Puoi ottenere l'ID chiamando il metodo ListSpaces() o dall'URL dello spazio.

Assegnare un nome a un messaggio

Per recuperare o specificare un messaggio nelle chiamate API future, puoi assegnare un nome a un messaggio impostando il campo messageId nella richiesta. Assegnare un nome al messaggio ti consente di specificarlo senza dover memorizzare l'ID assegnato dal sistema dal nome della risorsa del messaggio (rappresentato nel campo name).

Ad esempio, per recuperare un messaggio utilizzando il metodo get(), utilizzi il nome della risorsa per specificare quale messaggio recuperare. Il nome della risorsa è formattato come spaces/{space}/messages/{message}, dove {message} rappresenta l'ID assegnato dal sistema o il nome personalizzato che hai impostato durante la creazione del messaggio.

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

Puoi assegnare un nome a un messaggio solo al momento della creazione. Non puoi assegnare un nome o modificare un ID personalizzato per i messaggi esistenti. L'ID personalizzato deve soddisfare i seguenti requisiti:

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

Il seguente codice mostra un esempio di come un'app di chat può inviare un messaggio con un ID a 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 del campo name dello spazio. Puoi ottenere l'ID chiamando il metodo ListSpaces() o 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 dall'app Chat nello spazio specificato.

Risoluzione dei problemi

Quando un'app Google Chat o una scheda restituisce un errore, l'interfaccia di Chat mostra il messaggio "Si è verificato un problema". o "Impossibile elaborare la tua richiesta". A volte l'interfaccia utente di Chat non mostra alcun messaggio di errore, ma l'app o la scheda Chat produce un risultato imprevisto; ad esempio, un messaggio della scheda potrebbe non essere visualizzato.

Anche se nell'interfaccia utente di Chat potrebbe non essere visualizzato un messaggio di errore, sono disponibili messaggi di errore descrittivi e dati di log per aiutarti a correggere gli errori quando la registrazione degli errori per le app di chat è attivata. Per assistenza nella visualizzazione, nel debug e nella correzione degli errori, consulta Risolvere i problemi e correggere gli errori di Google Chat.