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

คู่มือนี้อธิบายวิธีใช้เมธอด create() ในทรัพยากร Message ของ Google Chat API เพื่อทำสิ่งต่อไปนี้

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

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

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

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

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

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

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

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

เรียกใช้เมธอด create() ด้วยการตรวจสอบสิทธิ์ผู้ใช้
รูปที่ 2: เมื่อมีการตรวจสอบสิทธิ์ผู้ใช้ ผู้ใช้จะส่งข้อความ และ Chat จะแสดง ชื่อแอป 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 จะส่งข้อความที่มีข้อความ การ์ด และปุ่มอุปกรณ์เสริม

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

  • chat.bot ขอบเขตการให้สิทธิ์
  • Space แหล่งข้อมูลที่คุณต้องการโพสต์ข้อความ แอป Chat ต้องเป็นสมาชิกของพื้นที่ทำงาน
  • แหล่งข้อมูล Message ที่จะสร้าง หากต้องการกำหนดเนื้อหาของข้อความ คุณสามารถใส่ ข้อความที่จัดรูปแบบ (text) อินเทอร์เฟซการ์ดอย่างน้อย 1 รายการ (cardsV2) หรือทั้ง 2 อย่าง

คุณเลือกที่จะรวมข้อมูลต่อไปนี้หรือไม่ก็ได้

โค้ดต่อไปนี้แสดงตัวอย่างวิธีที่แอป 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

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 ของพื้นที่ทำงาน คุณรับรหัสได้โดยการเรียกใช้เมธอด ListSpaces() หรือจาก URL ของพื้นที่ทำงาน

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

คุณเลือกที่จะรวมข้อมูลต่อไปนี้หรือไม่ก็ได้

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

Node.js

chat/client-libraries/cloud/create-message-user-cred.js
import {createClientWithUserCredentials} from './authentication-utils.js';

const USER_AUTH_OAUTH_SCOPES = ['https://www.googleapis.com/auth/chat.messages.create'];

// This sample shows how to create message with user credential
async function main() {
  // Create a client
  const chatClient = await createClientWithUserCredentials(USER_AUTH_OAUTH_SCOPES);

  // Initialize request argument(s)
  const request = {
    // Replace SPACE_NAME here.
    parent: 'spaces/SPACE_NAME',
    message: {
      text: '👋🌎 Hello world!' +
            'Text messages can contain things like:\n\n' +
            '* Hyperlinks 🔗\n' +
            '* Emojis 😄🎉\n' +
            '* Mentions of other Chat users `@` \n\n' +
            'For details, see the ' +
            '<https://developers.google.com/workspace/chat/format-messages' +
            '|Chat API developer documentation>.'
    }
  };

  // Make the request
  const response = await chatClient.createMessage(request);

  // Handle the response
  console.log(response);
}

main().catch(console.error);

Python

chat/client-libraries/cloud/create_message_user_cred.py
from authentication_utils import create_client_with_user_credentials
from google.apps import chat_v1 as google_chat

SCOPES = ["https://www.googleapis.com/auth/chat.messages.create"]

def create_message_with_user_cred():
    # Create a client
    client = create_client_with_user_credentials(SCOPES)

    # Initialize request argument(s)
    request = google_chat.CreateMessageRequest(
        # Replace SPACE_NAME here.
        parent = "spaces/SPACE_NAME",
        message = {
            "text": '👋🌎 Hello world!' +
                    'Text messages can contain things like:\n\n' +
                    '* Hyperlinks 🔗\n' +
                    '* Emojis 😄🎉\n' +
                    '* Mentions of other Chat users `@` \n\n' +
                    'For details, see the ' +
                    '<https://developers.google.com/workspace/chat/format-messages' +
                    '|Chat API developer documentation>.'
        }
    )

    # Make the request
    response = client.create_message(request)

    # Handle the response
    print(response)

create_message_with_user_cred()

Java

chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMessageUserCred.java
import com.google.chat.v1.ChatServiceClient;
import com.google.chat.v1.CreateMessageRequest;
import com.google.chat.v1.Message;

// This sample shows how to create message with user credential.
public class CreateMessageUserCred {

  private static final String SCOPE =
    "https://www.googleapis.com/auth/chat.messages.create";

  public static void main(String[] args) throws Exception {
    try (ChatServiceClient chatServiceClient =
        AuthenticationUtils.createClientWithUserCredentials(
          ImmutableList.of(SCOPE))) {
      CreateMessageRequest.Builder request = CreateMessageRequest.newBuilder()
        // Replace SPACE_NAME here.
        .setParent("spaces/SPACE_NAME")
        .setMessage(Message.newBuilder()
          .setText( "👋🌎 Hello world!" +
                    "Text messages can contain things like:\n\n" +
                    "* Hyperlinks 🔗\n" +
                    "* Emojis 😄🎉\n" +
                    "* Mentions of other Chat users `@` \n\n" +
                    "For details, see the " +
                    "<https://developers.google.com/workspace/chat/format-messages" +
                    "|Chat API developer documentation>."));
      Message response = chatServiceClient.createMessage(request.build());

      System.out.println(JsonFormat.printer().print(response));
    }
  }
}

Apps Script

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 ของพื้นที่ทำงาน คุณรับรหัสได้โดยการเรียกใช้เมธอด ListSpaces() หรือจาก 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

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 ของพื้นที่ทำงาน คุณรับรหัสได้โดยการเรียกใช้เมธอด ListSpaces() หรือจาก URL ของพื้นที่ทำงาน

ตั้งชื่อข้อความ

หากต้องการดึงหรือระบุข้อความในการเรียก API ในอนาคต คุณสามารถตั้งชื่อข้อความได้ โดยการตั้งค่าฟิลด์ messageId ในคำขอ การตั้งชื่อข้อความช่วยให้คุณระบุข้อความได้โดยไม่ต้องจัดเก็บ รหัสที่ระบบกำหนดจากชื่อทรัพยากรของข้อความ (แสดงในฟิลด์ name )

เช่น หากต้องการเรียกข้อมูลข้อความโดยใช้เมธอด get() คุณจะต้องใช้ชื่อทรัพยากรเพื่อระบุข้อความที่จะเรียก ชื่อทรัพยากรมีรูปแบบเป็น spaces/{space}/messages/{message} โดย {message} แสดงถึงรหัสที่ระบบกำหนดหรือชื่อที่กำหนดเองที่คุณตั้งค่าเมื่อสร้างข้อความ

หากต้องการตั้งชื่อข้อความ ให้ระบุรหัสที่กำหนดเองในฟิลด์ messageId เมื่อสร้างข้อความ ฟิลด์ messageId จะตั้งค่าสำหรับฟิลด์ clientAssignedMessageId ของทรัพยากร Message

คุณตั้งชื่อข้อความได้เมื่อสร้างข้อความเท่านั้น คุณตั้งชื่อหรือ แก้ไขรหัสที่กำหนดเองสำหรับข้อความที่มีอยู่ไม่ได้ รหัสที่กำหนดเองต้องเป็นไปตามข้อกำหนดต่อไปนี้

  • เริ่มต้นด้วย client- เช่น client-custom-name เป็นรหัสที่กำหนดเองที่ถูกต้อง แต่ custom-name ไม่ถูกต้อง
  • มีความยาวไม่เกิน 63 อักขระ และมีเฉพาะตัวอักษรพิมพ์เล็ก ตัวเลข และขีดกลาง
  • ไม่ซ้ำกันภายในพื้นที่ทำงาน แอป Chat จะใช้รหัสที่กำหนดเองเดียวกันสำหรับข้อความต่างๆ ไม่ได้

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

Node.js

chat/client-libraries/cloud/create-message-user-cred-message-id.js
import {createClientWithUserCredentials} from './authentication-utils.js';

const USER_AUTH_OAUTH_SCOPES = ['https://www.googleapis.com/auth/chat.messages.create'];

// This sample shows how to create message with user credential with message id
async function main() {
  // Create a client
  const chatClient = await createClientWithUserCredentials(USER_AUTH_OAUTH_SCOPES);

  // Initialize request argument(s)
  const request = {
    // Replace SPACE_NAME here.
    parent: 'spaces/SPACE_NAME',
    // Message id lets chat apps get, update or delete a message without needing
    // to store the system assigned ID in the message's resource name
    messageId: 'client-MESSAGE-ID',
    message: { text: 'Hello with user credential!' }
  };

  // Make the request
  const response = await chatClient.createMessage(request);

  // Handle the response
  console.log(response);
}

main().catch(console.error);

Python

chat/client-libraries/cloud/create_message_user_cred_message_id.py
from authentication_utils import create_client_with_user_credentials
from google.apps import chat_v1 as google_chat

SCOPES = ["https://www.googleapis.com/auth/chat.messages.create"]

# This sample shows how to create message with user credential with message id
def create_message_with_user_cred_message_id():
    # Create a client
    client = create_client_with_user_credentials(SCOPES)

    # Initialize request argument(s)
    request = google_chat.CreateMessageRequest(
        # Replace SPACE_NAME here
        parent = "spaces/SPACE_NAME",
        # Message id let chat apps get, update or delete a message without needing
        # to store the system assigned ID in the message's resource name.
        message_id = "client-MESSAGE-ID",
        message = {
            "text": "Hello with user credential!"
        }
    )

    # Make the request
    response = client.create_message(request)

    # Handle the response
    print(response)

create_message_with_user_cred_message_id()

Java

chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMessageUserCredMessageId.java
import com.google.chat.v1.ChatServiceClient;
import com.google.chat.v1.CreateMessageRequest;
import com.google.chat.v1.Message;

// This sample shows how to create message with message id specified with user
// credential.
public class CreateMessageUserCredMessageId {

  private static final String SCOPE =
    "https://www.googleapis.com/auth/chat.messages.create";

  public static void main(String[] args) throws Exception {
    try (ChatServiceClient chatServiceClient =
        AuthenticationUtils.createClientWithUserCredentials(
          ImmutableList.of(SCOPE))) {
      CreateMessageRequest.Builder request = CreateMessageRequest.newBuilder()
        // Replace SPACE_NAME here.
        .setParent("spaces/SPACE_NAME")
        .setMessage(Message.newBuilder()
          .setText("Hello with user credentials!"))
        // Message ID lets chat apps get, update or delete a message without
        // needing to store the system assigned ID in the message's resource
        // name.
        .setMessageId("client-MESSAGE-ID");
      Message response = chatServiceClient.createMessage(request.build());

      System.out.println(JsonFormat.printer().print(response));
    }
  }
}

Apps Script

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 ของพื้นที่ทำงาน คุณรับรหัสได้โดยการเรียกใช้เมธอด ListSpaces() หรือจาก URL ของพื้นที่ทำงาน
  • MESSAGE-ID: ชื่อของข้อความที่ขึ้นต้นด้วย custom- ต้องไม่ซ้ำกับชื่อข้อความอื่นๆ ที่แอป Chat สร้างขึ้นในพื้นที่ที่ระบุ

แก้ปัญหา

เมื่อแอป Google Chat หรือการ์ดแสดงข้อผิดพลาด อินเทอร์เฟซของ Chat จะแสดงข้อความว่า "เกิดข้อผิดพลาด" หรือ "ดำเนินการตามคำขอของคุณไม่ได้" บางครั้ง UI ของ Chat อาจไม่แสดงข้อความแสดงข้อผิดพลาดใดๆ แต่แอปหรือการ์ด Chat อาจให้ผลลัพธ์ที่ไม่คาดคิด เช่น ข้อความในการ์ดอาจไม่ปรากฏ

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