به‌روز کردن پیام

این راهنما توضیح می‌دهد که چگونه از روش update در منبع Message در Google Chat API برای به‌روزرسانی پیام نوشتاری یا کارتی در فضا استفاده کنید. پیامی را به‌روز کنید تا مشخصه‌های پیام، مثل آنچه می‌گوید یا محتوای کارت، تغییر کند. همچنین می‌توانید پیام نوشتاری را به ابتدای پیام کارتی اضافه کنید، یا کارت را به انتهای پیام نوشتاری اضافه کنید.

در Chat API، پیام Chat با منبع Message نشان داده می‌شود. درحالی‌که کاربران Chat فقط می‌توانند پیام‌های حاوی نوشتار ارسال کنند، برنامه‌های Chat می‌توانند از بسیاری از ویژگی‌های پیام‌رسانی دیگر استفاده کنند، ازجمله نمایش میاناهای کاربر تعاملی یا ایستا، جمع‌آوری اطلاعات از کاربران، و ارسال خصوصی پیام‌ها. برای کسب اطلاعات بیشتر درباره ویژگی‌های پیام‌رسانی موجود برای Chat API، به نمای کلی پیام‌های Google Chat مراجعه کنید.

پیش‌نیازها

Node.js

Python

جاوا

Apps Script

به‌روزرسانی پیام ازطرف کاربر

با اصالت‌سنجی کاربر، فقط نوشتار پیام را می‌توان به‌روز کرد.

برای به‌روزرسانی پیام با اصالت‌سنجی کاربر، موارد زیر را در درخواستتان ارسال کنید:

  • محدوده مجوز chat.messages را مشخص کنید.
  • روش UpdateMessage را فراخوانی کنید.
  • message را به‌عنوان نمونه‌ای از Message با موارد زیر ارسال کنید:
    • فیلد name روی پیامی که باید به‌روز شود تنظیم شده است، که شامل شناسه فضا و شناسه پیام است.
    • فیلد text با نوشتار جدید تنظیم شد.
  • updateMask را با مقدار text ارسال کنید.

اگر پیام به‌روزشده پیام کارتی باشد، نوشتار به کارت‌ها (که همچنان نمایش داده می‌شوند) اضافه می‌شود.

در اینجا نحوه به‌روزرسانی پیام یا پیش‌افزودن پیامک به پیام کارت با اصالت‌سنجی کاربر آورده شده است:

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()

جاوا

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 Script

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

برای اجرای این نمونه، موارد زیر را جایگزین کنید:

  • ‫SPACE_NAME: شناسه از name فضا. می‌توانید شناسه را با فراخوانی روش ListSpaces یا از نشانی وب فضا دریافت کنید.
  • MESSAGE_NAME: شناسه از name پیام. می‌توانید شناسه را از بدنه پاسخ برگردانده‌شده پس‌از ایجاد پیام به‌صورت ناهمگام با Chat API، یا با نام سفارشی اختصاص‌داده‌شده به پیام در زمان ایجاد دریافت کنید.

‫Chat API نمونه‌ای از Message را برمی‌گرداند که جزئیات پیام به‌روزشده را نشان می‌دهد.

به‌روزرسانی پیام به‌عنوان برنامه Chat

با اصالت‌سنجی برنامه، هم نوشتار و هم کارت‌های پیام را می‌توان به‌روز کرد.

برای به‌روزرسانی پیام با اصالت‌سنجی برنامه، موارد زیر را در درخواستتان ارسال کنید:

  • محدوده مجوز chat.bot را مشخص کنید.
  • روش UpdateMessage را فراخوانی کنید.
  • message را به‌عنوان نمونه‌ای از Message با موارد زیر ارسال کنید:
    • فیلد name روی پیامی که باید به‌روز شود تنظیم شده است، که شامل شناسه فضا و شناسه پیام است.
    • اگر فیلد text نیاز به به‌روزرسانی داشته باشد، با نوشتار جدید تنظیم می‌شود.
    • اگر کارت‌های جدید نیاز به به‌روزرسانی داشته باشند، فیلد cardsV2 با آن‌ها تنظیم می‌شود.
  • ‫updateMask را با فهرست فیلدها برای به‌روزرسانی‌هایی مثل text و cardsV2 ارسال کنید.

اگر پیام به‌روزشده پیام کارتی باشد و نوشتار به‌روز شده باشد، نوشتار به‌روزشده به کارت‌ها (که همچنان نمایش داده می‌شوند) اضافه می‌شود. اگر پیام به‌روزشده پیام نوشتاری باشد و کارت‌ها به‌روز شوند، کارت‌های به‌روزشده به نوشتار (که همچنان نمایش داده می‌شود) اضافه می‌شوند.

در اینجا نحوه به‌روزرسانی نوشتار و کارت‌های پیام با اصالت‌سنجی برنامه آورده شده است:

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()

جاوا

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 Script

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

برای اجرای این نمونه، موارد زیر را جایگزین کنید:

  • ‫SPACE_NAME: شناسه از name فضا. می‌توانید شناسه را با فراخوانی روش ListSpaces یا از نشانی وب فضا دریافت کنید.
  • MESSAGE_NAME: شناسه از name پیام. می‌توانید شناسه را از بدنه پاسخ برگردانده‌شده پس‌از ایجاد پیام به‌صورت ناهمگام با Chat API، یا با نام سفارشی اختصاص‌داده‌شده به پیام در زمان ایجاد دریافت کنید.

‫Chat API نمونه‌ای از Message را برمی‌گرداند که جزئیات پیام به‌روزشده را نشان می‌دهد.

به‌روزرسانی کارت‌ها به‌صورت ناهمگام

می‌توانید کارت‌های موجود در پیام را بااستفاده از روش replaceCards به‌صورت ناهمگام به‌روز کنید. این برای به‌روزرسانی محتوای کارت بدون تعامل کاربر مفید است، مانند بازآوری پیش‌نمایش پیوند یا به‌روزرسانی وضعیت تکلیف. این روش برای پیام‌های ایجادشده توسط برنامه، ازجمله پیام‌های ایجادشده ازطرف کاربر، کار می‌کند.

برای جزئیات، ایجاد و به‌روزرسانی کارت‌های تعاملی را ببینید.