Mesaj güncelleme

Bu kılavuzda, bir alandaki metin veya kart mesajını güncellemek için Google Chat API'nin Message kaynağında update yönteminin nasıl kullanılacağı açıklanmaktadır. Mesaj özelliklerini (ör. mesajın içeriği veya kartın içeriği) değiştirmek için mesajı güncelleyin. Ayrıca, kart mesajının başına kısa mesaj ekleyebilir veya kısa mesajın sonuna kart ekleyebilirsiniz.

Chat API'de, sohbet mesajları Message kaynağı ile temsil edilir. Chat kullanıcıları yalnızca metin içeren mesajlar gönderebilirken Chat uygulamaları, statik veya etkileşimli kullanıcı arayüzleri gösterme, kullanıcılardan bilgi toplama ve mesajları gizli olarak gönderme gibi diğer birçok mesajlaşma özelliğini kullanabilir. Chat API'de kullanılabilen mesajlaşma özellikleri hakkında daha fazla bilgi edinmek için Google Chat mesajlarına genel bakış başlıklı makaleyi inceleyin.

Ön koşullar

Node.js

Python

Java

Apps Komut Dosyası

Kullanıcı adına mesaj güncelleme

Kullanıcı kimlik doğrulaması ile yalnızca mesajın metni güncellenebilir.

Kullanıcı kimlik doğrulamasıyla bir mesajı güncellemek için isteğinizde aşağıdakileri iletin:

  • chat.messages yetkilendirme kapsamını belirtin.
  • UpdateMessage yöntemini çağırın.
  • message değerini, aşağıdaki kodla Message örneği olarak iletin:
    • name alanı, güncellenecek mesaja ayarlanır. Bu alan, bir alan kimliği ve mesaj kimliği içerir.
    • text alanı yeni metinle ayarlandı.
  • updateMask parametresini text değeriyle iletin.

Güncellenen mesaj bir kart mesajıysa metin, kartların (gösterilmeye devam eden) başına eklenir.

Kullanıcı kimlik doğrulaması ile bir mesajı nasıl güncelleyeceğiniz veya kart mesajının başına nasıl kısa mesaj ekleyeceğiniz aşağıda açıklanmıştır:

Node.js

chat/client-libraries/cloud/update-message-user-cred.js
import {createClientWithUserCredentials} from './authentication-utils.js';

const USER_AUTH_OAUTH_SCOPES = [
  'https://www.googleapis.com/auth/chat.messages',
];

// This sample shows how to update a message with user credential
async function main() {
  // Create a client
  const chatClient = await createClientWithUserCredentials(
    USER_AUTH_OAUTH_SCOPES,
  );

  // Initialize request argument(s)
  const request = {
    message: {
      // Replace SPACE_NAME and MESSAGE_NAME here
      name: 'spaces/SPACE_NAME/messages/MESSAGE_NAME',
      text: 'Updated with user credential!',
    },
    // The field paths to update. Separate multiple values with commas or use `*`
    // to update all field paths.
    updateMask: {
      // The field paths to update.
      paths: ['text'],
    },
  };

  // Make the request
  const response = await chatClient.updateMessage(request);

  // Handle the response
  console.log(response);
}

await main();

Python

chat/client-libraries/cloud/update_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"]

# This sample shows how to update a message with user credential
def update_message_with_user_cred():
    # Create a client
    client = create_client_with_user_credentials(SCOPES)

    # Initialize request argument(s)
    request = google_chat.UpdateMessageRequest(
        message = {
            # Replace SPACE_NAME and MESSAGE_NAME here
            "name": "spaces/SPACE_NAME/messages/MESSAGE_NAME",
            "text": "Updated with user credential!"
        },
        # The field paths to update. Separate multiple values with commas or use
        # `*` to update all field paths.
        update_mask = "text"
    )

    # Make the request
    response = client.update_message(request)

    # Handle the response
    print(response)

update_message_with_user_cred()

Java

chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/UpdateMessageUserCred.java
import com.google.chat.v1.ChatServiceClient;
import com.google.chat.v1.UpdateMessageRequest;
import com.google.chat.v1.Message;
import com.google.protobuf.FieldMask;

// This sample shows how to update message with user credential.
public class UpdateMessageUserCred {

  private static final String SCOPE =
    "https://www.googleapis.com/auth/chat.messages";

  public static void main(String[] args) throws Exception {
    try (ChatServiceClient chatServiceClient =
        AuthenticationUtils.createClientWithUserCredentials(
          ImmutableList.of(SCOPE))) {
      UpdateMessageRequest.Builder request = UpdateMessageRequest.newBuilder()
        .setMessage(Message.newBuilder()
          // replace SPACE_NAME and MESSAGE_NAME here
          .setName("spaces/SPACE_NAME/messages/MESSAGE_NAME")
          .setText("Updated with user credential!"))
        .setUpdateMask(FieldMask.newBuilder()
          // The field paths to update.
          .addPaths("text"));
      Message response = chatServiceClient.updateMessage(request.build());

      System.out.println(JsonFormat.printer().print(response));
    }
  }
}

Apps Komut Dosyası

chat/advanced-service/Main.gs
/**
 * This sample shows how to update a message with user credential
 *
 * It relies on the OAuth2 scope 'https://www.googleapis.com/auth/chat.messages'
 * referenced in the manifest file (appsscript.json).
 */
function updateMessageUserCred() {
  // Initialize request argument(s)
  // TODO(developer): Replace SPACE_NAME and MESSAGE_NAME here
  const name = "spaces/SPACE_NAME/messages/MESSAGE_NAME";
  const message = {
    text: "Updated with user credential!",
  };
  // The field paths to update. Separate multiple values with commas or use
  // `*` to update all field paths.
  const updateMask = "text";

  // Make the request
  const response = Chat.Spaces.Messages.patch(message, name, {
    updateMask: updateMask,
  });

  // Handle the response
  console.log(response);
}

Bu örneği çalıştırmak için aşağıdakileri değiştirin:

  • SPACE_NAME: Alanın name kimliği. Kimliği, ListSpaces yöntemini çağırarak veya alanın URL'sinden alabilirsiniz.
  • MESSAGE_NAME: Mesajın name alanındaki kimlik. Kimliği, Chat API ile eşzamansız olarak bir mesaj oluşturduktan sonra döndürülen yanıt gövdesinden veya oluşturma sırasında mesaja atanan özel ad ile alabilirsiniz.

Chat API, güncellenen mesajın ayrıntılarını içeren bir Message örneği döndürür.

Chat uygulaması olarak bir mesajı güncelleme

Uygulama kimlik doğrulaması ile mesajın hem metni hem de kartları güncellenebilir.

Uygulama kimlik doğrulamasıyla bir mesajı güncellemek için isteğinizde aşağıdakileri iletin:

  • chat.bot yetkilendirme kapsamını belirtin.
  • UpdateMessage yöntemini çağırın.
  • message değerini, aşağıdaki kodla Message örneği olarak iletin:
    • name alanı, güncellenecek mesaja ayarlanır. Bu alan, bir alan kimliği ve mesaj kimliği içerir.
    • Güncellenmesi gerekiyorsa text alanı yeni metinle ayarlanır.
    • Güncellenmesi gerekiyorsa yeni kartlarla ayarlanan cardsV2 alanı.
  • updateMask parametresini, güncellenecek alanların listesiyle (ör. text ve cardsV2) birlikte iletin.

Güncellenen mesaj bir kart mesajıysa ve metin güncellenirse güncellenen metin, kartların başına eklenir (kartlar gösterilmeye devam eder). Güncellenen mesaj bir kısa mesaj ise ve kartlar güncellenirse güncellenen kartlar metne eklenir (metin gösterilmeye devam eder).

Uygulama kimlik doğrulaması ile bir mesajın metnini ve kartlarını nasıl güncelleyeceğiniz aşağıda açıklanmıştır:

Node.js

chat/client-libraries/cloud/update-message-app-cred.js
import {createClientWithAppCredentials} from './authentication-utils.js';

// This sample shows how to update a message with app credential
async function main() {
  // Create a client
  const chatClient = createClientWithAppCredentials();

  // Initialize request argument(s)
  const request = {
    message: {
      // Replace SPACE_NAME and MESSAGE_NAME here
      name: 'spaces/SPACE_NAME/messages/MESSAGE_NAME',
      text: 'Text updated with app credential!',
      cardsV2: [
        {
          card: {
            header: {
              title: 'Card updated with app credential!',
              imageUrl:
                'https://fonts.gstatic.com/s/i/short-term/release/googlesymbols/info/default/24px.svg',
            },
          },
        },
      ],
    },
    // The field paths to update. Separate multiple values with commas or use `*`
    // to update all field paths.
    updateMask: {
      // The field paths to update.
      paths: ['text', 'cards_v2'],
    },
  };

  // Make the request
  const response = await chatClient.updateMessage(request);

  // Handle the response
  console.log(response);
}

await main();

Python

chat/client-libraries/cloud/update_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 update a message with app credential
def update_message_with_app_cred():
    # Create a client
    client = create_client_with_app_credentials()

    # Initialize request argument(s)
    request = google_chat.UpdateMessageRequest(
        message = {
            # Replace SPACE_NAME and MESSAGE_NAME here
            "name": "spaces/SPACE_NAME/messages/MESSAGE_NAME",
            "text": "Text updated with app credential!",
            "cards_v2" : [{ "card": { "header": {
                "title": 'Card updated with app credential!',
                "image_url": 'https://fonts.gstatic.com/s/i/short-term/release/googlesymbols/info/default/24px.svg'
            }}}]
        },
        # The field paths to update. Separate multiple values with commas or use
        # `*` to update all field paths.
        update_mask = "text,cardsV2"
    )

    # Make the request
    response = client.update_message(request)

    # Handle the response
    print(response)

update_message_with_app_cred()

Java

chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/UpdateMessageAppCred.java
import com.google.apps.card.v1.Card;
import com.google.apps.card.v1.Card.CardHeader;
import com.google.chat.v1.CardWithId;
import com.google.chat.v1.ChatServiceClient;
import com.google.chat.v1.UpdateMessageRequest;
import com.google.chat.v1.Message;
import com.google.protobuf.FieldMask;

// This sample shows how to update message with app credential.
public class UpdateMessageAppCred {

  public static void main(String[] args) throws Exception {
    try (ChatServiceClient chatServiceClient =
        AuthenticationUtils.createClientWithAppCredentials()) {
      UpdateMessageRequest.Builder request = UpdateMessageRequest.newBuilder()
        .setMessage(Message.newBuilder()
          // replace SPACE_NAME and MESSAGE_NAME here
          .setName("spaces/SPACE_NAME/messages/MESSAGE_NAME")
          .setText("Text updated with app credential!")
          .addCardsV2(CardWithId.newBuilder().setCard(Card.newBuilder()
            .setHeader(CardHeader.newBuilder()
              .setTitle("Card updated with app credential!")
              .setImageUrl("https://fonts.gstatic.com/s/i/short-term/release/googlesymbols/info/default/24px.svg")))))
        .setUpdateMask(FieldMask.newBuilder()
          // The field paths to update.
          .addAllPaths(List.of("text", "cards_v2")));
      Message response = chatServiceClient.updateMessage(request.build());

      System.out.println(JsonFormat.printer().print(response));
    }
  }
}

Apps Komut Dosyası

chat/advanced-service/Main.gs
/**
 * This sample shows how to update a message with app credential
 *
 * It relies on the OAuth2 scope 'https://www.googleapis.com/auth/chat.bot'
 * used by service accounts.
 */
function updateMessageAppCred() {
  // Initialize request argument(s)
  // TODO(developer): Replace SPACE_NAME and MESSAGE_NAME here
  const name = "spaces/SPACE_NAME/messages/MESSAGE_NAME";
  const message = {
    text: "Text updated with app credential!",
    cardsV2: [
      {
        card: {
          header: {
            title: "Card updated with app credential!",
            imageUrl:
              "https://fonts.gstatic.com/s/i/short-term/release/googlesymbols/info/default/24px.svg",
          },
        },
      },
    ],
  };
  // The field paths to update. Separate multiple values with commas or use
  // `*` to update all field paths.
  const updateMask = "text,cardsV2";

  // Make the request
  const response = Chat.Spaces.Messages.patch(
    message,
    name,
    {
      updateMask: updateMask,
    },
    getHeaderWithAppCredentials(),
  );

  // Handle the response
  console.log(response);
}

Bu örneği çalıştırmak için aşağıdakileri değiştirin:

  • SPACE_NAME: Alanın name kimliği. Kimliği, ListSpaces yöntemini çağırarak veya alanın URL'sinden alabilirsiniz.
  • MESSAGE_NAME: Mesajın name alanındaki kimlik. Kimliği, Chat API ile eşzamansız olarak bir mesaj oluşturduktan sonra döndürülen yanıt gövdesinden veya oluşturma sırasında mesaja atanan özel ad ile alabilirsiniz.

Chat API, güncellenen mesajın ayrıntılarını içeren bir Message örneği döndürür.

Kartları eşzamansız olarak güncelleme

replaceCards yöntemini kullanarak bir mesajdaki kartları eşzamansız olarak güncelleyebilirsiniz. Bu, kullanıcı etkileşimi olmadan bir kartın içeriğini güncellemek (ör. bağlantı önizlemesini yenilemek veya bir görevin durumunu güncellemek) için kullanışlıdır. Bu yöntem, bir kullanıcı adına oluşturulanlar da dahil olmak üzere uygulama tarafından oluşturulan mesajlar için geçerlidir.

Ayrıntılar için Etkileşimli kartlar oluşturma ve güncelleme başlıklı makaleyi inceleyin.