تعديل رسالة

يشرح هذا الدليل كيفية استخدام طريقة update في المورد Message من Google Chat API لتعديل رسالة نصية أو رسالة بطاقة في مساحة. يمكنك تعديل رسالة لتغيير سماتها، مثل محتواها أو محتوى بطاقة. يمكنك أيضًا إضافة رسالة نصية قبل رسالة البطاقة، أو إلحاق بطاقة برسالة نصية.

في Chat API، يتم تمثيل رسالة محادثة من خلال مورد Message. في حين أنّ مستخدمي Chat يمكنهم فقط إرسال رسائل تحتوي على نص، يمكن لتطبيقات Chat استخدام العديد من ميزات المراسلة الأخرى، بما في ذلك عرض واجهات مستخدم ثابتة أو تفاعلية، وجمع المعلومات من المستخدمين، وإرسال الرسائل بشكل خاص. لمزيد من المعلومات عن ميزات المراسلة المتاحة في Chat API، يُرجى الاطّلاع على نظرة عامة على رسائل Google Chat.

المتطلبات الأساسية

Node.js

Python

جافا

برمجة التطبيقات

تعديل رسالة نيابةً عن مستخدم

باستخدام مصادقة المستخدم، يمكن تعديل نص الرسالة فقط.

لتعديل رسالة باستخدام مصادقة المستخدم، عليك تمرير ما يلي في طلبك:

  • حدِّد نطاق تفويض 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));
    }
  }
}

برمجة التطبيقات

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 أو من عنوان URL الخاص بالمساحة.
  • ‫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));
    }
  }
}

برمجة التطبيقات

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 أو من عنوان URL الخاص بالمساحة.
  • ‫MESSAGE_NAME: المعرّف من السمة name للرسالة. يمكنك الحصول على المعرّف من نص الردّ الذي يتم عرضه بعد إنشاء رسالة بشكل غير متزامن باستخدام Chat API، أو باستخدام الاسم المخصّص الذي تم تعيينه للرسالة عند إنشائها.

تعرض واجهة Chat API مثيلاً من Message يوضّح تفاصيل الرسالة التي تم تعديلها.

تعديل البطاقات بشكل غير متزامن

يمكنك تعديل البطاقات في رسالة بشكل غير متزامن باستخدام الطريقة replaceCards. ويُعدّ ذلك مفيدًا لتعديل محتوى بطاقة بدون تفاعل المستخدم، مثل إعادة تحميل معاينة رابط أو تعديل حالة مهمة. تعمل هذه الطريقة مع الرسائل التي أنشأها التطبيق، بما في ذلك الرسائل التي تم إنشاؤها نيابةً عن مستخدم.

لمعرفة التفاصيل، يُرجى الاطّلاع على مقالة إنشاء البطاقات التفاعلية وتعديلها.