إرسال رسالة

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

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

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

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

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

Node.js

Python

  • Python 3.6 أو أحدث
  • تتيح لك أداة إدارة الحِزم 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 من خلال إرسال رسالة بطاقة تعرض اسم المستخدم وصورته الرمزية:

تطبيق 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 وحلّها.