با استفاده از Google Chat API پیام ارسال کنید

این راهنما نحوه فراخوانی messages.create() API Google Chat را برای انجام یکی از موارد زیر توضیح می‌دهد:

  • پیام هایی را ارسال کنید که حاوی متن، کارت و ویجت های تعاملی است.
  • پیام ها را به صورت خصوصی برای یک کاربر خاص چت ارسال کنید.
  • یک رشته پیام را شروع کنید یا به آن پاسخ دهید.
  • یک پیام را نام گذاری کنید تا بتوانید آن را در سایر درخواست های Chat API مشخص کنید.

حداکثر اندازه پیام (شامل هر متن یا کارت) 32000 بایت است. برای ارسال پیامی بیشتر از این اندازه، برنامه چت شما باید چند پیام ارسال کند.

علاوه بر فراخوانی متد messages.create() ، برنامه‌های چت می‌توانند پیام‌هایی را برای پاسخ به تعاملات کاربر ایجاد و ارسال کنند، مانند ارسال پیام خوشامدگویی پس از افزودن برنامه چت توسط کاربر به یک فضا. هنگام پاسخگویی به تعاملات، برنامه‌های چت می‌توانند از انواع دیگر ویژگی‌های پیام‌رسانی از جمله گفتگوهای تعاملی و رابط‌های پیش‌نمایش پیوند استفاده کنند. برای پاسخ به یک کاربر، برنامه Chat پیام را به صورت همزمان، بدون تماس با Chat API برمی‌گرداند. برای آشنایی با ارسال پیام برای پاسخ به تعاملات، به دریافت و پاسخ به تعاملات با برنامه گپ Google خود مراجعه کنید.

چگونه Chat پیام‌های ایجاد شده با Chat API را نمایش می‌دهد و ویژگی‌ها را نشان می‌دهد

می توانید با استفاده از احراز هویت برنامه و احراز هویت کاربر ، متد messages.create() را فراخوانی کنید. بسته به نوع احراز هویتی که استفاده می‌کنید، Chat به فرستنده پیام متفاوت است.

وقتی به عنوان برنامه Chat احراز هویت می کنید، برنامه Chat پیام را ارسال می کند.

فراخوانی متد messages.create() با احراز هویت برنامه.
شکل 1 : با احراز هویت برنامه، برنامه چت پیام را ارسال می کند. برای توجه به اینکه فرستنده یک شخص نیست، Chat App در کنار نام آن نمایش می دهد.

وقتی به عنوان کاربر احراز هویت می‌کنید، برنامه چت پیام را از طرف کاربر ارسال می‌کند. Chat همچنین برنامه Chat را با نمایش نام پیام به آن نسبت می دهد.

فراخوانی متد messages.create() با احراز هویت کاربر.
شکل 2 : با احراز هویت کاربر، کاربر پیام را ارسال می کند و Chat نام برنامه Chat را در کنار نام کاربر نمایش می دهد.

نوع احراز هویت همچنین تعیین می‌کند که کدام ویژگی‌ها و رابط‌های پیام‌رسانی را می‌توانید در پیام قرار دهید. با احراز هویت برنامه، برنامه‌های چت می‌توانند پیام‌هایی حاوی متن غنی، رابط‌های مبتنی بر کارت و ویجت‌های تعاملی ارسال کنند. از آنجایی که کاربران گپ فقط می‌توانند در پیام‌های خود متن ارسال کنند، هنگام ایجاد پیام با استفاده از احراز هویت کاربر، فقط می‌توانید متن را وارد کنید. برای اطلاعات بیشتر درباره ویژگی‌های پیام‌رسانی موجود برای Chat API، به نمای کلی پیام‌های گپ Google مراجعه کنید.

این راهنما نحوه استفاده از هر نوع احراز هویت برای ارسال پیام با Chat API را توضیح می دهد.

پیش نیازها

Node.js

پایتون

جاوا

اسکریپت برنامه ها

به عنوان برنامه چت پیام ارسال کنید

این بخش نحوه ارسال پیام های حاوی متن، کارت و ابزارک های جانبی تعاملی را با استفاده از احراز هویت برنامه توضیح می دهد.

پیام با احراز هویت برنامه ارسال شد
شکل 4. یک برنامه چت پیامی با متن، کارت و دکمه لوازم جانبی ارسال می کند.

برای فراخوانی messages.create() با استفاده از احراز هویت برنامه، باید فیلدهای زیر را در درخواست مشخص کنید:

  • محدوده مجوز chat.bot .
  • منبع Space که می خواهید پیام را در آن پست کنید. برنامه چت باید عضوی از فضا باشد.
  • منبع Message برای ایجاد. برای تعریف محتوای پیام، می‌توانید متن غنی ( text )، یک یا چند رابط کارت ( cardsV2 ) یا هر دو را شامل کنید.

به صورت اختیاری، می توانید موارد زیر را اضافه کنید:

کد زیر نمونه‌ای از نحوه ارسال یک برنامه چت را نشان می‌دهد که چگونه می‌تواند پیام ارسال شده به عنوان برنامه چت را ارسال کند که حاوی متن، یک کارت و یک دکمه قابل کلیک در پایین پیام است:

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

پایتون

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()

جاوا

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 یک دکمه قابل کلیک را در پایین پیام نمایش می دهد که به عنوان ابزارک لوازم جانبی شناخته می شود. ویجت های لوازم جانبی بعد از هر متن یا کارتی در پیام ظاهر می شوند. شما می توانید از این ویجت ها برای ترغیب کاربران به تعامل با پیام شما به طرق مختلف استفاده کنید، از جمله موارد زیر:

  • دقت یا رضایت یک پیام را ارزیابی کنید.
  • مشکل پیام یا برنامه چت را گزارش کنید.
  • پیوندی به محتوای مرتبط، مانند اسناد، باز کنید.
  • رد یا به تعویق انداختن پیام‌های مشابه از برنامه چت برای یک دوره زمانی خاص.

برای افزودن ویجت‌های جانبی، فیلد accessoryWidgets[] را در متن درخواست خود وارد کنید و یک یا چند ویجت را که می‌خواهید اضافه کنید، مشخص کنید.

تصویر زیر یک برنامه چت را نشان می دهد که یک پیام متنی را با ویجت های جانبی اضافه می کند تا کاربران بتوانند تجربه خود را با برنامه چت رتبه بندی کنند.

ویجت لوازم جانبی
شکل 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 API، قسمت privateMessageViewer را در متن درخواست خود مشخص کنید. برای تعیین کاربر، مقدار را به منبع User که نشان دهنده کاربر چت است تنظیم می کنید. همانطور که در مثال زیر نشان داده شده است، می توانید از قسمت name منبع User نیز استفاده کنید:

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

برای استفاده از این نمونه، USER_ID با یک شناسه منحصر به فرد برای کاربر، مانند 12345678987654321 یا [email protected] جایگزین کنید. برای اطلاعات بیشتر درباره تعیین کاربران، به شناسایی و تعیین کاربران گپ Google مراجعه کنید.

برای ارسال پیام خصوصی، باید موارد زیر را در درخواست خود حذف کنید:

از طرف یک کاربر پیامک ارسال کنید

این بخش نحوه ارسال پیام از طرف یک کاربر با استفاده از احراز هویت کاربر را توضیح می دهد. با احراز هویت کاربر، محتوای پیام فقط می‌تواند حاوی متن باشد و باید ویژگی‌های پیام‌رسانی را که فقط برای برنامه‌های گپ در دسترس هستند، از جمله رابط‌های کارت و ویجت‌های تعاملی حذف کند.

پیام با احراز هویت کاربر ارسال شد
شکل 3. یک برنامه چت یک پیام متنی از طرف یک کاربر ارسال می کند.

برای فراخوانی messages.create() با استفاده از احراز هویت کاربر، باید فیلدهای زیر را در درخواست مشخص کنید:

  • یک محدوده مجوز که از احراز هویت کاربر برای این روش پشتیبانی می کند. نمونه زیر از محدوده chat.messages.create استفاده می کند.
  • منبع Space که می خواهید پیام را در آن پست کنید. کاربر احراز هویت شده باید عضوی از فضا باشد.
  • منبع Message برای ایجاد. برای تعریف محتوای پیام، باید فیلد text را وارد کنید.

به صورت اختیاری، می توانید موارد زیر را اضافه کنید:

کد زیر نمونه ای از نحوه ارسال یک برنامه چت را در یک فضای مشخص از طرف یک کاربر احراز هویت شده نشان می دهد:

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

پایتون

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()

جاوا

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 را مشخص کنید.
  • پارامتر query messageReplyOption را مشخص کنید تا مشخص شود اگر کلید از قبل وجود داشته باشد چه اتفاقی می افتد.

برای ایجاد پیامی که به یک رشته موجود پاسخ می دهد:

  • در متن درخواست خود، فیلد thread را درج کنید. در صورت تنظیم، می توانید threadKey را که ایجاد کرده اید مشخص کنید. در غیر این صورت باید از name تاپیک استفاده کنید.
  • پارامتر query messageReplyOption را مشخص کنید.

کد زیر نمونه ای از نحوه ارسال یک برنامه چت را نشان می دهد که چگونه یک برنامه چت می تواند یک پیام متنی ارسال کند که از طرف یک کاربر احراز هویت شده با کلید یک فضای مشخص شده شروع می شود یا به رشته معینی پاسخ می دهد:

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

پایتون

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()

جاوا

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 فضا بدست آورید.

یک پیام را نام ببرید

برای بازیابی یا تعیین یک پیام در تماس‌های API آینده، می‌توانید با تنظیم فیلد messageId در درخواست messages.create() پیامی را نام‌گذاری کنید. نامگذاری پیام به شما امکان می دهد پیام را بدون نیاز به ذخیره شناسه اختصاص داده شده به سیستم از نام منبع پیام (که در قسمت name نشان داده شده است) مشخص کنید.

به عنوان مثال، برای بازیابی یک پیام با استفاده از متد get() ، از نام منبع استفاده می کنید تا مشخص کنید کدام پیام را بازیابی کنید. نام منبع به صورت spaces/{space}/messages/{message} قالب‌بندی می‌شود، جایی که {message} نشان‌دهنده شناسه اختصاص داده شده به سیستم یا نام سفارشی است که هنگام ایجاد پیام تنظیم کرده‌اید.

برای نامگذاری پیام، هنگام ایجاد پیام، یک شناسه سفارشی را در قسمت messageId تعیین کنید. فیلد messageId مقدار فیلد clientAssignedMessageId منبع Message را تعیین می کند.

زمانی که پیام را ایجاد می‌کنید، فقط می‌توانید پیامی را نام ببرید. نمی‌توانید یک شناسه سفارشی برای پیام‌های موجود نام‌گذاری یا تغییر دهید. شناسه سفارشی باید شرایط زیر را داشته باشد:

  • با client- شروع می شود- . برای مثال، client-custom-name یک شناسه سفارشی معتبر است، اما custom-name نیست.
  • دارای حداکثر 63 کاراکتر و فقط حروف کوچک، اعداد و خط فاصله است.
  • در یک فضا منحصر به فرد است. برنامه چت نمی‌تواند از یک شناسه سفارشی برای پیام‌های مختلف استفاده کند.

کد زیر نمونه‌ای از نحوه ارسال یک پیام متنی با یک شناسه به یک فضای معین از طرف یک کاربر تأیید شده را نشان می‌دهد:

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

پایتون

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()

جاوا

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- شروع می شود. باید از هر نام پیام دیگری که توسط برنامه چت در فضای مشخص شده ایجاد شده است منحصر به فرد باشد.

عیب یابی

وقتی یک برنامه یا کارت Google Chat خطایی را برمی‌گرداند، رابط Chat پیامی را نشان می‌دهد که می‌گوید «مشکلی پیش آمده است». یا "نمی توان به درخواست شما رسیدگی کرد." گاهی اوقات Chat UI هیچ پیام خطایی را نمایش نمی دهد، اما برنامه یا کارت Chat نتیجه غیرمنتظره ای ایجاد می کند. برای مثال، ممکن است پیام کارت ظاهر نشود.

اگرچه ممکن است پیام خطا در رابط کاربری گپ نمایش داده نشود، پیام‌های خطای توصیفی و داده‌های گزارش در دسترس هستند تا به شما کمک کنند هنگام فعال بودن ثبت خطا برای برنامه‌های گپ، خطاها را برطرف کنید. برای راهنمایی برای مشاهده، اشکال‌زدایی و رفع خطاها، به عیب‌یابی و رفع خطاهای Google Chat مراجعه کنید.