إرسال رسالة باستخدام Google Chat API

يوضّح هذا الدليل كيفية استخدام طريقة create() في مورد Message ضمن Google Chat API لتنفيذ أيّ مما يلي:

  • إرسال رسائل تحتوي على نصوص وبطاقات وتطبيقات مصغّرة تفاعلية
  • إرسال رسائل بشكل خاص إلى مستخدم محدّد في Chat
  • بدء سلسلة رسائل أو الردّ عليها
  • تسمية رسالة لتتمكّن من تحديدها في طلبات أخرى لواجهة برمجة تطبيقات Chat

يبلغ الحد الأقصى لحجم الرسالة (بما في ذلك أي نصوص أو بطاقات) 32,000 بايت. لإرسال رسالة تتجاوز هذا الحجم، يجب أن يرسل تطبيق Chat عدة رسائل بدلاً من ذلك.

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

طريقة عرض الرسائل التي تم إنشاؤها باستخدام Chat API وتحديد مصدرها

يمكنك استدعاء طريقة create() باستخدام مصادقة التطبيق ومصادقة المستخدم. يحدّد Chat مرسل الرسالة بشكل مختلف استنادًا إلى نوع المصادقة الذي تستخدمه.

عند المصادقة على تطبيق Chat، يرسل تطبيق Chat الرسالة.

استدعاء طريقة create() باستخدام مصادقة التطبيق
الشكل 1: عند استخدام مصادقة التطبيق، يرسل تطبيق Chat الرسالة. للإشارة إلى أنّ المُرسِل ليس شخصًا، يعرض Chat الرمز App بجانب اسمه.

عند المصادقة كمستخدم، يرسل تطبيق Chat الرسالة نيابةً عن المستخدم. يُشير Chat أيضًا إلى تطبيق Chat في الرسالة من خلال عرض اسمه.

استدعاء طريقة create() مع مصادقة المستخدم
الشكل 2: عند مصادقة المستخدم، يرسل المستخدم الرسالة، ويعرض Chat اسم تطبيق Chat بجانب اسم المستخدم.

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

يوضّح هذا الدليل كيفية استخدام أيّ من نوعَي المصادقة لإرسال رسالة باستخدام Chat API.

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

Node.js

Python

Java

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

إرسال رسالة كتطبيق Chat

يوضّح هذا القسم كيفية إرسال رسائل تحتوي على نصوص وبطاقات وأدوات تفاعلية خاصة بالملحقات باستخدام مصادقة التطبيق.

تم إرسال الرسالة بعد مصادقة التطبيق
الشكل 4. يرسل تطبيق Chat رسالة تتضمّن نصًا وبطاقة وزر ملحق.

لاستدعاء طريقة CreateMessage() باستخدام مصادقة التطبيق، يجب تحديد الحقول التالية في الطلب:

  • chat.bot نطاق التفويض
  • تمثّل هذه السمة Space المورد الذي تريد نشر الرسالة فيه. يجب أن يكون تطبيق Chat عضوًا في المساحة.
  • تمثّل هذه السمة مورد Message الذي سيتم إنشاؤه. لتحديد محتوى الرسالة، يمكنك تضمين نص منسّق (text) أو واجهة بطاقة واحدة أو أكثر (cardsV2) أو كليهما.

يمكنك اختياريًا تضمين ما يلي:

يعرض الرمز التالي مثالاً على كيفية إرسال تطبيق Chat رسالة منشورة كتطبيق Chat تتضمّن نصًا وبطاقة وزرًا قابلاً للنقر في أسفل الرسالة:

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

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

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

لتشغيل هذا النموذج، استبدِل SPACE_NAME برقم التعريف من حقل name في المساحة. يمكنك الحصول على المعرّف من خلال استدعاء الطريقة ListSpaces() أو من عنوان URL الخاص بالمساحة.

إضافة تطبيقات مصغّرة تفاعلية في أسفل الرسالة

في نموذج الرمز البرمجي الأول من هذا الدليل، تعرض رسالة تطبيق Chat زرًا قابلاً للنقر في أسفل الرسالة، يُعرف باسم التطبيق المصغّر الملحق. تظهر أدوات التطبيقات المصغّرة الخاصة بالأجهزة الملحقة بعد أي نص أو بطاقات في الرسالة. يمكنك استخدام هذه الأدوات المصغّرة لتشجيع المستخدمين على التفاعل مع رسالتك بطرق عديدة، بما في ذلك ما يلي:

  • تقييم دقة الرسالة أو مستوى الرضا عنها
  • الإبلاغ عن مشكلة في الرسالة أو تطبيق Chat
  • فتح رابط يؤدي إلى محتوى ذي صلة، مثل المستندات
  • يمكنك تجاهل الرسائل المشابهة من تطبيق Chat أو تأجيلها لفترة زمنية محدّدة.

لإضافة أدوات مصغّرة خاصة بالملحقات، أدرِج الحقل accessoryWidgets[] في نص الطلب وحدِّد أداة مصغّرة واحدة أو أكثر تريد تضمينها.

تعرض الصورة التالية تطبيقًا في Chat يضيف رسالة نصية مع أدوات ملحقة حتى يتمكّن المستخدمون من تقييم تجربتهم مع تطبيق Chat.

تطبيق مصغَّر خاص بالأجهزة الملحقة
الشكل 5: رسالة في تطبيق دردشة تتضمّن نصًا وأدوات ملحقة

يوضّح ما يلي نص الطلب الذي ينشئ رسالة نصية تتضمّن زرَّين إضافيَّين. عندما ينقر المستخدم على زر، تعالج الدالة المقابلة (مثل doUpvote) التفاعل:

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

إرسال رسالة بشكل خاص

يمكن لتطبيقات Chat إرسال رسائل بشكل خاص كي لا تظهر الرسالة إلا لمستخدم معيّن في المساحة. عندما يرسل تطبيق Chat رسالة خاصة، تعرض الرسالة تصنيفًا يُعلم المستخدم بأنّ الرسالة مرئية له فقط.

لإرسال رسالة بشكل خاص باستخدام Chat API، حدِّد الحقل privateMessageViewer في نص الطلب. لتحديد المستخدم، عليك ضبط القيمة على المورد User الذي يمثّل مستخدم Chat. يمكنك أيضًا استخدام حقل name في المورد User، كما هو موضّح في المثال التالي:

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

لاستخدام هذا النموذج، استبدِل USER_ID بمعرّف فريد للمستخدم، مثل 12345678987654321 أو hao@cymbalgroup.com. لمزيد من المعلومات حول تحديد المستخدمين، يُرجى الاطّلاع على تحديد مستخدمي Google Chat.

لإرسال رسالة بشكل خاص، يجب حذف ما يلي من طلبك:

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

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

الرسالة المُرسَلة مع مصادقة المستخدم
الشكل 3. يرسل تطبيق Chat رسالة نصية نيابةً عن مستخدم.

لاستدعاء طريقة CreateMessage() باستخدام مصادقة المستخدم، يجب تحديد الحقول التالية في الطلب:

  • نطاق تفويض يتيح مصادقة المستخدم لهذه الطريقة. يستخدم المثال التالي النطاق chat.messages.create.
  • تمثّل هذه السمة Space المورد الذي تريد نشر الرسالة فيه. يجب أن يكون المستخدم الذي تمت المصادقة عليه عضوًا في المساحة.
  • تمثّل هذه السمة مورد Message الذي سيتم إنشاؤه. لتحديد محتوى الرسالة، عليك تضمين الحقل text.

يمكنك اختياريًا تضمين ما يلي:

يوضّح الرمز التالي مثالاً على كيفية إرسال تطبيق Chat رسالة نصية في مساحة معيّنة نيابةً عن مستخدم تم التحقّق من هويته:

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

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

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

لتشغيل هذا النموذج، استبدِل SPACE_NAME برقم التعريف من حقل name في المساحة. يمكنك الحصول على المعرّف من خلال استدعاء الطريقة ListSpaces() أو من عنوان URL الخاص بالمساحة.

بدء سلسلة محادثات أو الردّ فيها

بالنسبة إلى المساحات التي تستخدم سلاسل المحادثات، يمكنك تحديد ما إذا كانت الرسالة الجديدة تبدأ سلسلة محادثات أو ترد على سلسلة محادثات حالية.

بشكل تلقائي، تؤدي الرسائل التي تنشئها باستخدام Chat API إلى بدء سلسلة محادثات جديدة. لمساعدتك في تحديد سلسلة المحادثات والردّ عليها لاحقًا، يمكنك تحديد مفتاح سلسلة المحادثات في طلبك:

  • في نص الطلب، حدِّد الحقل thread.threadKey.
  • حدِّد مَعلمة طلب البحث messageReplyOption لتحديد ما يحدث إذا كان المفتاح متوفّرًا.

لإنشاء رسالة تردّ على سلسلة محادثات حالية، اتّبِع الخطوات التالية:

  • في نص طلبك، أدرِج الحقل thread. في حال ضبطها، يمكنك تحديد threadKey الذي أنشأته. بخلاف ذلك، يجب استخدام name في سلسلة المحادثات.
  • حدِّد مَعلمة طلب البحث messageReplyOption.

يوضّح الرمز التالي مثالاً على كيفية إرسال تطبيق Chat رسالة نصية تبدأ سلسلة محادثات معيّنة أو تردّ عليها، ويتم تحديدها من خلال مفتاح لمساحة معيّنة نيابةً عن مستخدم تمّت المصادقة عليه:

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

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

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

لتشغيل هذا النموذج، استبدِل ما يلي:

  • THREAD_KEY: مفتاح سلسلة محادثات حالية في المساحة، أو اسم فريد لسلسلة المحادثات لإنشاء سلسلة محادثات جديدة
  • SPACE_NAME: رقم التعريف من حقل name المساحة يمكنك الحصول على المعرّف من خلال استدعاء الطريقة ListSpaces() أو من عنوان URL الخاص بالمساحة.

تسمية رسالة

لاسترداد رسالة أو تحديدها في طلبات مستقبلية من واجهة برمجة التطبيقات، يمكنك تسمية رسالة من خلال ضبط الحقل messageId في طلبك. يتيح لك تسمية رسالتك تحديد الرسالة بدون الحاجة إلى تخزين المعرّف الذي يحدّده النظام من اسم المورد الخاص بالرسالة (الممثّل في الحقل name).

على سبيل المثال، لاسترداد رسالة باستخدام طريقة get()، عليك استخدام اسم المورد لتحديد الرسالة التي تريد استردادها. يتم تنسيق اسم المورد على النحو التالي: spaces/{space}/messages/{message}، حيث يمثّل {message} المعرّف الذي يحدّده النظام أو الاسم المخصّص الذي تحدّده عند إنشاء الرسالة.

لتسمية رسالة، حدِّد معرّفًا مخصّصًا في الحقل messageId عند إنشاء الرسالة. يضبط الحقل messageId قيمة الحقل clientAssignedMessageId للمورد Message.

يمكنك تسمية رسالة فقط عند إنشائها. لا يمكنك تسمية أو تعديل معرّف مخصّص للرسائل الحالية. يجب أن يستوفي المعرّف المخصّص المتطلبات التالية:

  • يبدأ بـ "client-". على سبيل المثال، client-custom-name هو معرّف مخصّص صالح، ولكن custom-name ليس كذلك.
  • يحتوي على ما يصل إلى 63 حرفًا وأحرف صغيرة وأرقامًا وواصلات فقط.
  • أن يكون فريدًا ضمن مساحة لا يمكن لتطبيق Chat استخدام المعرّف المخصّص نفسه لرسائل مختلفة.

يعرض الرمز التالي مثالاً على كيفية إرسال تطبيق Chat رسالة نصية تتضمّن رقم تعريف إلى مساحة معيّنة نيابةً عن مستخدم تم إثبات هويته:

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

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

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

لتشغيل هذا النموذج، استبدِل ما يلي:

  • SPACE_NAME: رقم التعريف من حقل name المساحة يمكنك الحصول على المعرّف من خلال استدعاء الطريقة ListSpaces() أو من عنوان URL الخاص بالمساحة.
  • MESSAGE-ID: اسم للرسالة يبدأ بـ custom-. يجب أن يكون الاسم فريدًا عن أي أسماء رسائل أخرى أنشأها تطبيق Chat في المساحة المحدّدة.

تحديد المشاكل وحلّها

عندما يعرض تطبيق أو بطاقة في Google Chat خطأً، تعرض واجهة Chat رسالة تفيد بأنّه "حدث خطأ". أو "لم نتمكّن من معالجة طلبك". في بعض الأحيان، لا تعرض واجهة مستخدم Chat أي رسالة خطأ، ولكن ينتج تطبيق Chat أو البطاقة نتيجة غير متوقّعة، مثلاً، قد لا تظهر رسالة البطاقة.

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