إرسال رسالة

يوضّح هذا الدليل الطرق المختلفة التي يمكن لتطبيقات Google Chat من خلالها إرسال الرسائل:

  • أرسل رسائل نصية ورسائل بطاقات في الوقت الفعلي عن طريق الرد على تفاعل المستخدم.
  • أرسِل الرسائل النصية ورسائل البطاقات بشكل غير متزامن من خلال استدعاء طريقة create على مورد Message.
  • بدء سلسلة رسائل أو الردّ عليها
  • إرسال رسالة وتسميتها

يمثّل المورد Message رسالة نصية أو بطاقة في Google Chat. يمكنك create أو get أو update أو delete رسالة في Google Chat API من خلال طلب الطرق المناسبة. لمزيد من المعلومات عن الرسائل النصية ورسائل البطاقات، راجِع نظرة عامة على رسائل Google Chat.

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

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

Node.js

لغة Python

  • الإصدار 3.6 أو إصدار أحدث من Python
  • تتيح أداة pip لإدارة الحزم
  • أحدث مكتبات برامج Google للغة بايثون. ولتثبيتها أو تحديثها، يمكنك تشغيل الأمر التالي في واجهة سطر الأوامر:

    pip3 install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib oauth2client
    
  • أحد تطبيقات Chat المنشورة. لإنشاء تطبيق Chat ونشره، يمكنك الاطّلاع على إنشاء تطبيق Google Chat.

  • تم ضبط التفويض لتطبيق Chat لإرسال رسائل غير متزامنة. لا يلزم إجراء تهيئة للتفويض لإرسال الرسائل في الوقت الفعلي.

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

إرسال رسائل نصية

يوضح هذا القسم كيفية إرسال رسائل نصية بالطريقتين التاليتين:

  • يمكنك إرسال رسالة نصية في الوقت الفعلي من خلال الرد على تفاعل المستخدم.
  • يمكنك إرسال رسالة نصية من خلال طلب Google Chat API بشكل غير متزامن.

إرسال رسالة نصية في الوقت الفعلي

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

لإرسال رسالة نصية عندما يضيف مستخدم تطبيق Chat إلى مساحة، يتجاوب تطبيق Chat مع ADDED_TO_SPACE حدث تفاعل. للردّ على أحداث تفاعل "ADDED_TO_SPACE" من خلال رسالة نصية، استخدِم الرمز التالي:

Node.js

/**
 * Sends an onboarding message when the Chat app is added to a space.
 *
 * @param {Object} event The event object from Chat API.
 * @return {Object} Response from the Chat app. An onboarding message that
 * introduces the app and helps people get started with it.
 */
exports.onMessage = function onMessage(req, res) {
  if (req.method === 'GET' || !req.body.message) {
    res.send(
      'Hello! This function is meant to be used in a Google Chat space.');
  }

  // Send an onboarding message when added to a Chat space
  if(req.body.type === 'ADDED_TO_SPACE') {
    res.json({
      'text': 'Hi, Cymbal at your service. I help you manage your calendar
      from Google Chat. Take a look at your schedule today by typing
      `/checkCalendar`, or schedule a meeting with `/scheduleMeeting`. To
      learn what else I can do, type `/help`.'
    });
  }
};

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

/**
 * Sends an onboarding message when the Chat app is added to a space.
 *
 * @param {Object} event The event object from Chat API.
 * @return {Object} Response from the Chat app. An onboarding message that
 * introduces the app and helps people get started with it.
 */
function onAddToSpace(event) {

  return {
    'text': 'Hi, Cymbal at your service. I help you manage your calendar
    from Google Chat. Take a look at your schedule today by typing
    `/checkCalendar`, or schedule a meeting with `/scheduleMeeting`. To learn
    what else I can do, type `/help`.'
  }
}

يعرض نموذج التعليمة البرمجية الرسالة النصية التالية:

مثال على رسالة الإعداد

إرسال رسالة نصية بشكل غير متزامن

يوضح القسم التالي كيفية إرسال رسالة نصية بشكل غير متزامن باستخدام مصادقة التطبيق ومصادقة المستخدم.

لإرسال رسالة نصية، مرر ما يلي في طلبك:

  • باستخدام مصادقة التطبيق، حدِّد نطاق التفويض chat.bot. مع مصادقة المستخدم، حدِّد نطاق التفويض chat.messages.create.
  • عليك استدعاء طريقة create في المورد Message.

إرسال رسالة نصية تتضمن مصادقة التطبيق

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

لغة Python

  1. في دليل العمل، أنشئ ملفًا باسم chat_create_text_message_app.py.
  2. أدرِج الرمز التالي في chat_create_text_message_app.py:

    from httplib2 import Http
    from oauth2client.service_account import ServiceAccountCredentials
    from apiclient.discovery import build
    
    # Specify required scopes.
    SCOPES = ['https://www.googleapis.com/auth/chat.bot']
    
    # Specify service account details.
    CREDENTIALS = ServiceAccountCredentials.from_json_keyfile_name(
        'credentials.json', SCOPES)
    
    # Build the URI and authenticate with the service account.
    chat = build('chat', 'v1', http=CREDENTIALS.authorize(Http()))
    
    # Create a Chat message.
    result = chat.spaces().messages().create(
    
        # The space to create the message in.
        #
        # Replace SPACE with a space name.
        # Obtain the space name from the spaces resource of Chat API,
        # or from a space's URL.
        parent='spaces/SPACE',
    
        # The message to create.
        body={'text': 'Hello, world!'}
    
    ).execute()
    
    print(result)
    
  3. في الرمز، استبدِل SPACE باسم مساحة، والذي يمكنك الحصول عليه من طريقة spaces.list() في Chat API أو من عنوان URL لمساحة.

  4. في دليل العمل، أنشئ النموذج وشغِّله:

    python3 chat_create_text_message_app.py
    

تعرض Chat API مثيل Message الذي يوضِّح الرسالة المُرسَلة.

إرسال رسالة نصية تتضمن مصادقة المستخدم

إليك كيفية إرسال رسالة نصية باستخدام مصادقة المستخدم:

لغة Python

  1. في دليل العمل، أنشئ ملفًا باسم chat_create_text_message_user.py.
  2. أدرِج الرمز التالي في chat_create_text_message_user.py:

    import os.path
    
    from google.auth.transport.requests import Request
    from google.oauth2.credentials import Credentials
    from google_auth_oauthlib.flow import InstalledAppFlow
    from googleapiclient.discovery import build
    from googleapiclient.errors import HttpError
    
    # Define your app's authorization scopes.
    # When modifying these scopes, delete the file token.json, if it exists.
    SCOPES = ["https://www.googleapis.com/auth/chat.messages.create"]
    
    def main():
        '''
        Authenticates with Chat API via user credentials,
        then creates a text message in a Chat space.
        '''
    
        # Start with no credentials.
        creds = None
    
        # Authenticate with Google Workspace
        # and get user authorization.
        flow = InstalledAppFlow.from_client_secrets_file(
                        'client_secrets.json', SCOPES)
        creds = flow.run_local_server()
    
        # Build a service endpoint for Chat API.
        chat = build('chat', 'v1', credentials=creds)
    
        # Use the service endpoint to call Chat API.
        result = chat.spaces().messages().create(
    
            # The space to create the message in.
            #
            # Replace SPACE with a space name.
            # Obtain the space name from the spaces resource of Chat API,
            # or from a space's URL.
            parent='spaces/SPACE',
    
            # The message to create.
            body={'text': 'Hello, world!'}
    
        ).execute()
    
        # Prints details about the created membership.
        print(result)
    
    if __name__ == '__main__':
        main()
    
  3. في الرمز، استبدِل SPACE باسم مساحة، والذي يمكنك الحصول عليه من طريقة spaces.list() في Chat API أو من عنوان URL لمساحة.

  4. في دليل العمل، أنشئ النموذج وشغِّله:

    python3 chat_create_text_message_user.py
    

تعرض Chat API مثيل Message الذي يوضِّح الرسالة المُرسَلة.

إرسال رسائل البطاقات

يصف هذا القسم كيفية إرسال رسائل البطاقات بالطريقتين التاليتين:

  • يمكنك إرسال رسالة بطاقة في الوقت الفعلي من خلال الردّ على تفاعل المستخدم.
  • يمكنك إرسال رسالة بطاقة من خلال طلب Google Chat API بشكل غير متزامن.

إرسال رسالة بطاقة في الوقت الفعلي

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

في هذا المثال، يرسل المستخدم رسالة إلى تطبيق Chat ويستجيب تطبيق Chat من خلال إرسال رسالة بطاقة تعرض اسم المستخدم وصورته الرمزية:

تطبيق Chat يستجيب ببطاقة تعرض الاسم المعروض للمُرسِل وصورته
الشخصية.

Node.js

العقدة/avatar-app/index.js
/**
 * Google Cloud Function that responds to messages sent from a
 * Google Chat room.
 *
 * @param {Object} req Request sent from Google Chat room
 * @param {Object} res Response to send back
 */
exports.helloChat = function helloChat(req, res) {
  if (req.method === 'GET' || !req.body.message) {
    res.send('Hello! This function is meant to be used in a Google Chat ' +
      'Room.');
  }

  const sender = req.body.message.sender.displayName;
  const image = req.body.message.sender.avatarUrl;

  const data = createMessage(sender, image);

  res.send(data);
};

/**
 * Creates a card with two widgets.
 * @param {string} displayName the sender's display name
 * @param {string} imageUrl the URL for the sender's avatar
 * @return {Object} a card with the user's avatar.
 */
function createMessage(displayName, imageUrl) {
  const cardHeader = {
    title: `Hello ${displayName}!`,
  };

  const avatarWidget = {
    textParagraph: {text: 'Your avatar picture: '},
  };

  const avatarImageWidget = {
    image: {imageUrl},
  };

  const avatarSection = {
    widgets: [
      avatarWidget,
      avatarImageWidget,
    ],
  };

  return {
    text: 'Here\'s your avatar',
    cardsV2: [{
      cardId: 'avatarCard',
      card: {
        name: 'Avatar Card',
        header: cardHeader,
        sections: [avatarSection],
      }
    }],
  };
}

لغة Python

python/avatar-app/main.py
from typing import Any, Mapping

import flask
import functions_framework


# Google Cloud Function that responds to messages sent in
# Google Chat.
#
# @param {Object} req Request sent from Google Chat.
# @param {Object} res Response to send back.
@functions_framework.http
def hello_chat(req: flask.Request) -> Mapping[str, Any]:
  if req.method == "GET":
    return "Hello! This function must be called from Google Chat."

  request_json = req.get_json(silent=True)

  display_name = request_json["message"]["sender"]["displayName"]
  avatar = request_json["message"]["sender"]["avatarUrl"]

  response = create_message(name=display_name, image_url=avatar)

  return response


# Creates a card with two widgets.
# @param {string} name the sender's display name.
# @param {string} image_url the URL for the sender's avatar.
# @return {Object} a card with the user's avatar.
def create_message(name: str, image_url: str) -> Mapping[str, Any]:
  avatar_image_widget = {"image": {"imageUrl": image_url}}
  avatar_text_widget = {"textParagraph": {"text": "Your avatar picture:"}}
  avatar_section = {"widgets": [avatar_text_widget, avatar_image_widget]}

  header = {"title": f"Hello {name}!"}

  cards = {
      "text": "Here's your avatar",
      "cardsV2": [
          {
              "cardId": "avatarCard",
              "card": {
                  "name": "Avatar Card",
                  "header": header,
                  "sections": [avatar_section],
              },
          }
      ]
  }

  return cards

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

apps-script/avatar-app/hello-chat.gs
/**
 * Responds to a MESSAGE event in Google Chat.
 *
 * @param {Object} event the event object from Google Chat
 */
function onMessage(event) {
  const displayName = event.message.sender.displayName;
  const avatarUrl = event.message.sender.avatarUrl;

  return createMessage(displayName, avatarUrl);
}

/**
 * Creates a card with two widgets.
 * @param {string} displayName the sender's display name
 * @param {string} avatarUrl the URL for the sender's avatar
 * @return {Object} a card with the sender's avatar.
 */
function createMessage(displayName, avatarUrl) {
  const cardHeader = {
    title: `Hello ${displayName}!`
  };

  const avatarWidget = {
    textParagraph: {text: 'Your avatar picture: '}
  };

  const avatarImageWidget = {
    image: {imageUrl: avatarUrl}
  };

  const avatarSection = {
    widgets: [
      avatarWidget,
      avatarImageWidget
    ],
  };

  return {
    text: 'Here\'s your avatar',
    cardsV2: [{
      cardId: 'avatarCard',
      card: {
        name: 'Avatar Card',
        header: cardHeader,
        sections: [avatarSection],
      }
    }],
  };
}

إرسال رسالة بطاقة بشكل غير متزامن

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

  • باستخدام مصادقة التطبيق، حدِّد نطاق التفويض chat.bot. لا يمكنك إرسال رسالة بطاقة مع مصادقة المستخدم.
  • عليك استدعاء طريقة create في المورد Message.

في ما يلي مثال على رسالة بطاقة:

رسالة بطاقة تم إرسالها باستخدام Chat API

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

لغة Python

  1. في دليل العمل، أنشئ ملفًا باسم chat_create_card_message.py.
  2. أدرِج الرمز التالي في chat_create_card_message.py:

    from httplib2 import Http
    from oauth2client.service_account import ServiceAccountCredentials
    from apiclient.discovery import build
    
    # Specify required scopes.
    SCOPES = ['https://www.googleapis.com/auth/chat.bot']
    
    # Specify service account details.
    CREDENTIALS = ServiceAccountCredentials.from_json_keyfile_name(
        'credentials.json', SCOPES)
    
    # Build the URI and authenticate with the service account.
    chat = build('chat', 'v1', http=CREDENTIALS.authorize(Http()))
    
    # Create a Chat message.
    result = chat.spaces().messages().create(
    
        # The space to create the message in.
        #
        # Replace SPACE with a space name.
        # Obtain the space name from the spaces resource of Chat API,
        # or from a space's URL.
        parent='spaces/SPACE',
    
        # The message to create.
        body=
        {
          'cardsV2': [{
            'cardId': 'createCardMessage',
            'card': {
              'header': {
                'title': 'A card message!',
                'subtitle': 'Created with the Chat API',
                'imageUrl': 'https://developers.google.com/chat/images/chat-product-icon.png',
                'imageType': 'CIRCLE'
              },
              'sections': [
                {
                  'widgets': [
                    {
                      'buttonList': {
                        'buttons': [
                          {
                            'text': 'Read the docs!',
                            'onClick': {
                              'openLink': {
                                'url': 'https://developers.google.com/chat'
                              }
                            }
                          }
                        ]
                      }
                    }
                  ]
                }
              ]
            }
          }]
        }
    
    ).execute()
    
    print(result)
    
  3. في الرمز، استبدِل SPACE باسم مساحة، والذي يمكنك الحصول عليه من طريقة spaces.list في Chat API أو من عنوان URL لمساحة.

  4. في دليل العمل، أنشئ النموذج وشغِّله:

    python3 chat_create_card_message.py
    

بدء سلسلة رسائل أو الردّ عليها

لبدء سلسلة رسائل، أرسِل رسالة واترك حقل thread.name فارغًا، حيث يعمل Google Chat على تعبئته عند إنشاء سلسلة المحادثات. بشكل اختياري، لتخصيص اسم سلسلة المحادثات، حدِّد الحقل thread.threadKey.

للرد على سلسلة رسائل، أرسِل رسالة تحدد الحقل threadKey أو حقل name الخاص بسلسلة المحادثات. إذا تم إنشاء سلسلة المحادثات من قِبل مستخدم أو تطبيق Chat آخر، يجب استخدام الحقل thread.name.

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

في ما يلي طريقة بدء سلسلة محادثات أو الرد عليها باستخدام الحقل threadKey المحدد على أنه nameOfThread:

لغة Python

  1. في دليل العمل، أنشئ ملفًا باسم chat_create_message_thread.py.
  2. أدرِج الرمز التالي في chat_create_message_thread.py:

    from httplib2 import Http
    from oauth2client.service_account import ServiceAccountCredentials
    from apiclient.discovery import build
    
    # Specify required scopes.
    SCOPES = ['https://www.googleapis.com/auth/chat.bot']
    
    # Specify service account details.
    CREDENTIALS = ServiceAccountCredentials.from_json_keyfile_name(
        'credentials.json', SCOPES)
    
    # Build the URI and authenticate with the service account.
    chat = build('chat', 'v1', http=CREDENTIALS.authorize(Http()))
    
    # Create a Chat message.
    result = chat.spaces().messages().create(
    
        # The space to create the message in.
        #
        # Replace SPACE with a space name.
        # Obtain the space name from the spaces resource of Chat API,
        # or from a space's URL.
        parent='spaces/SPACE',
    
        # Whether to start a thread or reply to an existing one.
        #
        # Required when threading is enabled in a space unless starting a
        # thread.  Ignored in other space types. Threading is enabled when
        # space.spaceThreadingState is THREADED_MESSAGES.
        #
        # REPLY_MESSAGE_FALLBACK_TO_NEW_THREAD replies to an existing thread
        # if one exists, otherwise it starts a new one.
        messageReplyOption='REPLY_MESSAGE_FALLBACK_TO_NEW_THREAD',
    
        # The message body.
        body={
    
            # The message to create.
            'text': 'Start or reply to another message in a thread!',
    
            # The thread to start or reply to.
            'thread': {
                'threadKey': 'nameOfThread'
            }
        }
    
    ).execute()
    
    print(result)
    
  3. في الرمز، استبدِل SPACE باسم مساحة، والذي يمكنك الحصول عليه من طريقة spaces.list في Chat API أو من عنوان URL لمساحة.

  4. في دليل العمل، أنشئ النموذج وشغِّله:

    python3 chat_create_message_thread.py
    

تعرض Chat API مثيل Message الذي يوضِّح الرسالة المُرسَلة.

إرسال رسالة وتسميتها

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

لا يحلّ تعيين اسم مخصّص محلّ حقل name الذي تم إنشاؤه، أي اسم مورد الرسالة. بدلاً من ذلك، يتم ضبط الاسم المخصّص كحقل clientAssignedMessageId الذي يمكنك الرجوع إليه أثناء معالجة العمليات اللاحقة، مثل تعديل الرسالة أو حذفها.

يجب استيفاء المتطلبات التالية للأسماء المخصّصة:

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

في ما يلي كيفية إرسال رسالة وتسميتها:

لغة Python

  1. في دليل العمل، أنشئ ملفًا باسم chat_create_named_message.py.
  2. أدرِج الرمز التالي في chat_create_named_message.py:

    from httplib2 import Http
    from oauth2client.service_account import ServiceAccountCredentials
    from apiclient.discovery import build
    
    # Specify required scopes.
    SCOPES = ['https://www.googleapis.com/auth/chat.bot']
    
    # Specify service account details.
    CREDENTIALS = ServiceAccountCredentials.from_json_keyfile_name(
        'credentials.json', SCOPES)
    
    # Build the URI and authenticate with the service account.
    chat = build('chat', 'v1', http=CREDENTIALS.authorize(Http()))
    
    # Create a Chat message with a custom name.
    result = chat.spaces().messages().create(
    
        # The space to create the message in.
        #
        # Replace SPACE with a space name.
        # Obtain the space name from the spaces resource of Chat API,
        # or from a space's URL.
        parent='spaces/SPACE',
    
        # Custom name for the message used to facilitate later operations.
        messageId='client-custom-name',
    
        # The message to create.
        body={'text': 'Hello, world!'}
    
    ).execute()
    
    print(result)
    
  3. في الرمز، استبدِل SPACE باسم مساحة، والذي يمكنك الحصول عليه من طريقة spaces.list في Chat API أو من عنوان URL لمساحة.

  4. في دليل العمل، أنشئ النموذج وشغِّله:

    python3 chat_create_named_message.py
    

تعرض Chat API مثيل Message الذي يوضِّح الرسالة المُرسَلة.

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

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

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