ส่งข้อความโดยใช้ Google Chat API

คู่มือนี้จะอธิบายวิธีเรียก API ของ Google Chat messages.create() ในการดำเนินการอย่างใดอย่างหนึ่งต่อไปนี้

  • ส่งข้อความที่มีข้อความ การ์ด และวิดเจ็ตแบบอินเทอร์แอกทีฟ
  • ส่งข้อความแบบส่วนตัวไปยังผู้ใช้ Chat ที่ระบุ
  • เริ่มหรือตอบกลับชุดข้อความ
  • ตั้งชื่อข้อความเพื่อให้คุณระบุใน Chat API อื่นๆ ได้ คำขอ

ขนาดสูงสุดของข้อความ (รวมถึงข้อความหรือการ์ดทั้งหมด) คือ 32,000 ไบต์ หากต้องการส่งข้อความที่มีขนาดใหญ่กว่านี้ แอป Chat ของคุณ ต้องส่งข้อความหลายรายการแทน

นอกจากการเรียกใช้เมธอด messages.create() แล้ว แอป Chat สามารถสร้างและส่งข้อความเพื่อตอบกลับการโต้ตอบของผู้ใช้ เช่น การโพสต์ ข้อความต้อนรับหลังจากที่ผู้ใช้เพิ่มแอป Chat ลงใน พื้นที่ทำงาน เมื่อตอบกลับการโต้ตอบ แอป Chat จะใช้ ประเภทของฟีเจอร์การรับส่งข้อความ รวมถึงกล่องโต้ตอบแบบอินเทอร์แอกทีฟและการแสดงตัวอย่างลิงก์ อินเทอร์เฟซ หากต้องการตอบกลับผู้ใช้ แอป Chat จะกลับมา ข้อความพร้อมกันโดยไม่ต้องเรียกใช้ Chat API เพื่อเรียนรู้ เกี่ยวกับการส่งข้อความเพื่อตอบกลับการโต้ตอบ โปรดดูที่ รับและตอบกลับการโต้ตอบกับแอป Google Chat

วิธีที่ Chat แสดงและระบุแหล่งที่มาของข้อความที่สร้างด้วย Chat API

คุณสามารถเรียกเมธอด messages.create() โดยใช้ การตรวจสอบสิทธิ์แอป และการตรวจสอบสิทธิ์ผู้ใช้ Chat ระบุแหล่งที่มาของผู้ส่งข้อความแตกต่างกัน โดยขึ้นอยู่กับประเภทการตรวจสอบสิทธิ์ที่คุณใช้

เมื่อคุณตรวจสอบสิทธิ์ว่าเป็นแอป Chat แอป Chat จะส่งข้อความนั้น

วันที่ การเรียกเมธอด messages.create() ที่มีการตรวจสอบสิทธิ์แอป
รูปที่ 1: เมื่อใช้การตรวจสอบสิทธิ์แอป แอป Chat จะส่ง ข้อความนั้น โปรดทราบว่าหากผู้ส่งไม่ใช่บุคคล Chat จะแสดง App ข้างชื่อผู้ส่ง

เมื่อคุณตรวจสอบสิทธิ์ในฐานะผู้ใช้ แอป Chat จะส่ง ข้อความในนามของผู้ใช้ Chat ยังระบุแหล่งที่มา แชทกับแอปโดยการแสดงชื่อ

วันที่ การเรียกเมธอด messages.create() ที่มีการตรวจสอบสิทธิ์ผู้ใช้
รูปที่ 2: เมื่อใช้การตรวจสอบสิทธิ์ผู้ใช้ ผู้ใช้จะส่งข้อความ และ Chat จะแสดง ชื่อแอป Chat ข้างชื่อของผู้ใช้

ประเภทการตรวจสอบสิทธิ์จะกำหนดฟีเจอร์และอินเทอร์เฟซการรับส่งข้อความด้วย ที่คุณสามารถใส่ไว้ในข้อความ การตรวจสอบสิทธิ์แอป แอปแชทสามารถส่งข้อความที่มี Rich Text ได้ อินเทอร์เฟซแบบการ์ด และวิดเจ็ตแบบอินเทอร์แอกทีฟ เนื่องจากผู้ใช้ Chat จะส่งได้เฉพาะข้อความตัวอักษรเท่านั้น คุณจึงดำเนินการต่อไปนี้ได้ รวมเฉพาะข้อความเมื่อสร้างข้อความโดยใช้การตรวจสอบสิทธิ์ผู้ใช้ หากต้องการดูข้อมูลเพิ่มเติมเกี่ยวกับการรับส่งข้อความ ฟีเจอร์ที่ใช้ได้กับ Chat API โปรดดู ภาพรวมข้อความ Google Chat

คำแนะนำนี้จะอธิบายวิธีใช้การตรวจสอบสิทธิ์ประเภทใดประเภทหนึ่งในการส่งข้อความ ด้วย Chat API

ข้อกำหนดเบื้องต้น

Node.js

  • ธุรกิจหรือองค์กร บัญชี Google Workspace ที่มีสิทธิ์เข้าถึง Google Chat

Python

  • ธุรกิจหรือองค์กร บัญชี Google Workspace ที่มีสิทธิ์เข้าถึง Google Chat

Java

  • ธุรกิจหรือองค์กร บัญชี Google Workspace ที่มีสิทธิ์เข้าถึง Google Chat

Apps Script

  • ธุรกิจหรือองค์กร บัญชี Google Workspace ที่มีสิทธิ์เข้าถึง Google Chat

ส่งข้อความเป็นแอป Chat

ส่วนนี้อธิบายวิธีส่งข้อความที่มีข้อความ การ์ด และ วิดเจ็ตอุปกรณ์เสริมแบบอินเทอร์แอกทีฟโดยใช้ การตรวจสอบสิทธิ์แอป

วันที่ ข้อความที่ส่งพร้อมการตรวจสอบสิทธิ์แอป
รูปที่ 4 แอปใน Chat จะส่งข้อความด้วย ข้อความ การ์ด และปุ่มอุปกรณ์เสริม

หากต้องการเรียก messages.create() โดยใช้การตรวจสอบสิทธิ์แอป คุณต้องระบุ ฟิลด์ต่อไปนี้ในคำขอ

  • ขอบเขตการให้สิทธิ์ chat.bot
  • ทรัพยากร Space ที่ ที่คุณต้องการโพสต์ข้อความ แอป Chat ต้องมีคุณสมบัติต่อไปนี้ สมาชิกของพื้นที่ทำงาน
  • Message ทรัพยากรในการสร้าง หากต้องการกำหนดเนื้อหาของข้อความ คุณสามารถใส่ Rich Text (text), อินเทอร์เฟซของการ์ดอย่างน้อย 1 รายการ (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));
    }
  }
}

Apps Script

แชท/บริการขั้นสูง/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 ด้วยรหัสจาก ของ Space name คุณสามารถรับรหัสโดยโทรไปที่ spaces.list() วิธี หรือจาก URL ของพื้นที่ทำงาน

เพิ่มวิดเจ็ตแบบอินเทอร์แอกทีฟที่ด้านล่างของข้อความ

ในตัวอย่างโค้ดแรกของคู่มือนี้ ข้อความแอปใน Chat จะแสดงปุ่มที่คลิกได้ที่ ที่ด้านล่างของข้อความ ซึ่งเรียกว่าวิดเจ็ตอุปกรณ์เสริม วิดเจ็ตอุปกรณ์เสริม ปรากฏหลังข้อความหรือการ์ดในข้อความ คุณสามารถใช้วิดเจ็ตเหล่านี้เพื่อเรียกข้อความแจ้ง โต้ตอบกับข้อความของคุณได้หลายวิธี เช่น

  • ให้คะแนนความถูกต้องหรือความพึงพอใจของข้อความ
  • รายงานปัญหาเกี่ยวกับข้อความหรือแอป Chat
  • เปิดลิงก์ไปยังเนื้อหาที่เกี่ยวข้อง เช่น เอกสารประกอบ
  • ปิดหรือเลื่อนการแจ้งเตือนข้อความที่คล้ายกันจากแอป Chat สำหรับระยะเวลาที่กำหนด

หากต้องการเพิ่มวิดเจ็ตอุปกรณ์เสริม ให้ใส่ accessoryWidgets[] ในส่วนเนื้อหาของคำขอ และระบุวิดเจ็ตที่คุณต้องการ ที่จะรวม

รูปภาพต่อไปนี้แสดงแอปใน Chat ที่ต่อท้าย ข้อความที่มีวิดเจ็ตอุปกรณ์เสริมเพื่อให้ผู้ใช้ให้คะแนนประสบการณ์การใช้งาน ด้วยแอป Chat

วันที่ วิดเจ็ตอุปกรณ์เสริม
ภาพที่ 5: ข้อความแอปใน Chat ที่มี วิดเจ็ตข้อความและอุปกรณ์เสริม

รายการต่อไปนี้จะแสดงเนื้อหาของคำขอที่สร้างข้อความตัวอักษรด้วย ปุ่มเสริม 2 ปุ่ม เมื่อผู้ใช้คลิกปุ่ม โฆษณาที่สอดคล้องกัน (เช่น 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 ที่ แสดงถึงผู้ใช้ Chat คุณยังสามารถใช้ ฟิลด์ name ของฟิลด์ ทรัพยากร User ดังที่แสดงในตัวอย่างต่อไปนี้

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

หากต้องการใช้ตัวอย่างนี้ ให้แทนที่ USER_ID ที่มีรหัสที่ไม่ซ้ำกันสำหรับผู้ใช้ เช่น 12345678987654321 หรือ hao@cymbalgroup.com สำหรับข้อมูลเพิ่มเติมเกี่ยวกับการระบุผู้ใช้ โปรดดู ระบุและระบุผู้ใช้ Google Chat

หากต้องการส่งข้อความแบบส่วนตัว คุณต้องละเว้นข้อมูลต่อไปนี้ในคำขอ

ส่งข้อความในนามของผู้ใช้

ส่วนนี้จะอธิบายวิธีส่งข้อความในนามของผู้ใช้โดยใช้ การตรวจสอบสิทธิ์ผู้ใช้ เมื่อใช้การตรวจสอบสิทธิ์ผู้ใช้ เนื้อหาของข้อความจะมีได้เฉพาะข้อความเท่านั้น และต้องละเว้นฟีเจอร์การรับส่งข้อความที่ใช้ได้เฉพาะ แอปแชท รวมถึงอินเทอร์เฟซการ์ดและวิดเจ็ตแบบอินเทอร์แอกทีฟ

วันที่ ข้อความที่ส่งพร้อมการตรวจสอบสิทธิ์ผู้ใช้
รูปที่ 3 แอปใน Chat จะส่ง SMS ผ่าน แทนผู้ใช้

หากต้องการเรียก messages.create() โดยใช้การตรวจสอบสิทธิ์ผู้ใช้ คุณต้องระบุ ฟิลด์ต่อไปนี้ในคำขอ

  • ขอบเขตการให้สิทธิ์ ที่สนับสนุนการตรวจสอบสิทธิ์ผู้ใช้สำหรับวิธีนี้ ตัวอย่างต่อไปนี้ใช้ ขอบเขต chat.messages.create
  • ทรัพยากร Space ที่ ที่คุณต้องการโพสต์ข้อความ ผู้ใช้ที่ตรวจสอบสิทธิ์แล้วต้องเป็นสมาชิกของ พื้นที่ทำงาน
  • Message ทรัพยากรในการสร้าง หากต้องการกำหนดเนื้อหาของข้อความ คุณต้องใส่ text ด้วย

คุณสามารถรวมสิ่งต่อไปนี้ได้ (ไม่บังคับ)

โค้ดต่อไปนี้แสดงตัวอย่างวิธีที่แอป Chat สามารถส่ง SMS ในพื้นที่ทำงานที่ระบุในนามของผู้ใช้ที่ตรวจสอบสิทธิ์แล้ว ดังนี้

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

Apps Script

แชท/บริการขั้นสูง/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 ด้วยรหัสจาก ของ Space 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));
    }
  }
}

Apps Script

แชท/บริการขั้นสูง/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: คีย์ Thread ที่มีอยู่ในพื้นที่ทำงาน หรือ เพื่อสร้างชุดข้อความใหม่ ซึ่งจะมีชื่อที่ไม่ซ้ำกันสำหรับชุดข้อความนั้น
  • 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 ตัว และมีเฉพาะตัวพิมพ์เล็ก ตัวเลข และ ขีดกลาง
  • ไม่ซ้ำกันภายในพื้นที่ทำงาน แอป Chat ไม่สามารถใช้ รหัสที่กำหนดเองเดียวกันสำหรับข้อความที่แตกต่างกัน

โค้ดต่อไปนี้แสดงตัวอย่างวิธีที่แอป Chat สามารถส่ง SMS ที่มีบัตรประจำตัวไปยังพื้นที่ทำงานที่ระบุในนามของ ผู้ใช้ที่ตรวจสอบสิทธิ์แล้ว:

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

Apps Script

แชท/บริการขั้นสูง/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 แสดงข้อความว่า "เกิดข้อผิดพลาด" หรือ "ไม่สามารถดำเนินการตามคำขอของคุณ" บางครั้ง UI ของ Chat ไม่แสดงข้อความแสดงข้อผิดพลาดใดๆ แต่แอป Chat หรือ ทำให้เกิดผลลัพธ์ที่ไม่คาดคิด เช่น ข้อความในการ์ดอาจ ปรากฏขึ้น

แม้ว่าข้อความแสดงข้อผิดพลาดอาจไม่แสดงใน UI ของแชท มีข้อความแสดงข้อผิดพลาดและข้อมูลบันทึกที่สื่อความหมายเพื่อช่วยคุณแก้ไขข้อผิดพลาด เมื่อมีการเปิดข้อผิดพลาดในการบันทึกสำหรับแอป Chat หากต้องการความช่วยเหลือในการดู การแก้ไขข้อบกพร่องและการแก้ไขข้อผิดพลาด โปรดดู แก้ปัญหาข้อผิดพลาดของ Google Chat