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

يشرح هذا الدليل طريقة استدعاء واجهة برمجة تطبيقات Google Chat messages.create() لإجراء أي مما يلي:

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

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

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

كيفية عرض Chat وسمات الرسائل التي تم إنشاؤها باستخدام Chat API

يمكنك استدعاء الطريقة messages.create() باستخدام مصادقة التطبيقات ومصادقة المستخدم. تختلف سمات مُرسِل الرسالة في Chat بناءً على نوع المصادقة التي تستخدمها.

عند إجراء المصادقة داخل تطبيق Chat، يرسل تطبيق Chat الرسالة.

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

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

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

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

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

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

Node.js

Python

Java

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

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

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

تم إرسال الرسالة باستخدام مصادقة التطبيق.
الشكل 4. يُرسِل تطبيق في Chat رسالة باستخدام ونص وبطاقة وزر للملحقات.

لطلب "messages.create()" باستخدام مصادقة التطبيقات، يجب تحديد الحقول التالية في الطلب:

  • نطاق التفويض في 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. ويمكنك الحصول على المعرّف من خلال استدعاء طريقة spaces.list() أو من عنوان URL الخاص بالمساحة.

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

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

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

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

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

التطبيق المصغّر للملحق
الشكل 5: رسالة تطبيق Chat تحتوي على تطبيقات مصغّرة للنصوص والملحقات

يوضح ما يلي نص الطلب الذي يؤدي إلى إنشاء رسالة نصية تحتوي على زرين للملحقات. عندما ينقر المستخدم على زر ما، فإن (مثل 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 وتحديدهم

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

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

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

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

لطلب رقم messages.create() باستخدام مصادقة المستخدم، يجب تحديد الحقول التالية في الطلب:

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

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

  • الحقل messageId، الذي يتيح لك يمكنك تسمية الرسالة لاستخدامها في طلبات واجهة برمجة التطبيقات الأخرى.
  • الحقلان thread.threadKey وmessageReplyOption من أجل بدء سلسلة محادثات أو الرد عليها إذا لم تكن المساحة استخدام سلاسل المحادثات، يتم تجاهل هذا الحقل.

يوضّح الرمز التالي مثالاً على طريقة استخدام تطبيق 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 . ويمكنك الحصول على المعرّف من خلال استدعاء طريقة spaces.list() أو من عنوان 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 . ويمكنك الحصول على المعرّف من خلال استدعاء طريقة spaces.list() أو من عنوان URL الخاص بالمساحة.

تسمية رسالة

لاسترداد رسالة أو تحديدها في طلبات البيانات من واجهة برمجة التطبيقات المستقبلية، يمكنك تسمية رسالة. من خلال إعداد الحقل messageId في طلب messages.create(). تتيح لك تسمية رسالتك تحديد الرسالة بدون الحاجة إلى تخزين الذي يعيّنه النظام من اسم مورد الرسالة (يتم تمثيله في 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 . ويمكنك الحصول على المعرّف من خلال استدعاء طريقة spaces.list() أو من عنوان URL الخاص بالمساحة.
  • MESSAGE-ID: اسم للرسالة التي تبدأ مع custom-. يجب أن يكون فريدًا عن أي أسماء رسائل أخرى تم إنشاؤها بواسطة تطبيق Chat في المساحة المحدّدة

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

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

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