ตอบสนองต่อคําสั่งของแอป Google Chat

หน้านี้อธิบายวิธีตั้งค่าและตอบกลับคำสั่งในฐานะ แอป Google Chat

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

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

ประเภทของคำสั่งแอป Chat

คุณสร้างคำสั่งของแอป Chat เป็นคำสั่งเครื่องหมายทับ คำสั่งด่วน หรือการดำเนินการกับข้อความได้ หากต้องการใช้คำสั่งแต่ละประเภท ผู้ใช้สามารถทำดังนี้
  1. คำสั่งเครื่องหมายทับ: ผู้ใช้สามารถเลือกคำสั่งเครื่องหมายทับจากเมนูหรือพิมพ์เครื่องหมายทับ (/) แล้วตามด้วยข้อความที่กำหนดไว้ล่วงหน้า เช่น /about โดยปกติแล้วแอปแชทจะกำหนดให้ต้องมีข้อความอาร์กิวเมนต์สำหรับคำสั่งเครื่องหมายทับ

    สร้างคำสั่งเครื่องหมายทับ หากแอป Chat ของคุณต้องใช้ข้อมูลเพิ่มเติม จากผู้ใช้ เช่น คุณสามารถสร้างคำสั่งเครื่องหมายทับ ที่ชื่อ /search ซึ่งจะทำงานหลังจากที่ผู้ใช้ป้อนวลีที่จะ ค้นหา เช่น /search receipts

  2. คำสั่งด่วน: ผู้ใช้จะใช้คำสั่งได้โดยเปิดเมนูจากส่วนตอบกลับ ของข้อความแชท หากต้องการใช้คำสั่ง ผู้ใช้จะคลิกเพิ่ม และ เลือกคำสั่งจากเมนู

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

  3. การดำเนินการกับข้อความ: ผู้ใช้จะใช้การดำเนินการกับข้อความได้โดยวางเมาส์เหนือข้อความและ คลิกเมนู 3 จุด หากต้องการใช้คำสั่ง ผู้ใช้จะเปิดเมนู 3 จุดและเลือก คำสั่งจากเมนู

    สร้างการดำเนินการที่แนะนำหากแอป Chat สามารถดำเนินการตามบริบทของข้อความได้

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

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

HTTP

แอป Google Chat ที่รับและตอบสนองต่อการโต้ตอบของผู้ใช้ หากต้องการสร้าง ให้ทำตามการเริ่มต้นใช้งาน HTTP

Apps Script

แอป Google Chat ที่รับและตอบสนองต่อการโต้ตอบของผู้ใช้ หากต้องการสร้าง ให้ทำตามการเริ่มต้นใช้งาน Apps Script อย่างรวดเร็ว

ตั้งค่าคำสั่ง

ส่วนนี้จะอธิบายวิธีทําตามขั้นตอนต่อไปนี้เพื่อตั้งค่า คําสั่ง

  1. สร้างชื่อและคำอธิบายสำหรับคำสั่ง
  2. กำหนดค่าคำสั่งในคอนโซล Google Cloud
  3. ไม่บังคับ: แมปคำสั่งกับพรอมต์เริ่มต้น

ตั้งชื่อและอธิบายคำสั่ง

ชื่อของคำสั่งคือสิ่งที่ผู้ใช้พิมพ์หรือเลือกเพื่อเรียกใช้แอป Chat นอกจากนี้ คำอธิบายสั้นๆ จะปรากฏใต้ชื่อเพื่อแจ้งให้ผู้ใช้ทราบเพิ่มเติมเกี่ยวกับวิธีใช้คำสั่ง

ชื่อและคำอธิบายของคำสั่งเครื่องหมายทับ
ชื่อและคำอธิบายสำหรับคำสั่งเครื่องหมายทับ

เมื่อเลือกชื่อและคำอธิบายสำหรับคำสั่ง ให้พิจารณาคำแนะนำต่อไปนี้

วิธีตั้งชื่อคำสั่ง

  • ใช้คำหรือวลีที่สั้น สื่อความหมาย และกระตุ้นให้ดำเนินการได้ เพื่อให้คำสั่งชัดเจนสำหรับผู้ใช้ เช่น แทนที่จะใช้ชื่อ Create a reminder ให้ใช้ Remind me
  • ลองใช้ชื่อที่ไม่ซ้ำกันหรือชื่อทั่วไปสำหรับคำสั่ง หากคำสั่งอธิบายการโต้ตอบหรือฟีเจอร์ทั่วไป คุณสามารถใช้ชื่อที่ผู้ใช้รู้จักและคาดหวัง เช่น Settings หรือ Feedback ไม่เช่นนั้น ให้ลองใช้ชื่อคำสั่งที่ไม่ซ้ำกัน เนื่องจากหากชื่อคำสั่งของคุณเหมือนกับแอป Chat อื่นๆ ผู้ใช้จะต้องกรองคำสั่งที่คล้ายกันเพื่อค้นหาและใช้คำสั่งของคุณ

วิธีอธิบายคำสั่ง

  • เขียนคำอธิบายให้สั้นและชัดเจนเพื่อให้ผู้ใช้ทราบว่าจะเกิดอะไรขึ้นเมื่อใช้คำสั่ง
  • แจ้งให้ผู้ใช้ทราบหากมีข้อกำหนดในการจัดรูปแบบคำสั่ง ตัวอย่างเช่น หากคุณ สร้างคำสั่งเครื่องหมายทับ ที่ต้องใช้ข้อความอาร์กิวเมนต์ ให้ตั้งค่าคำอธิบายเป็นข้อความต่อไปนี้ Remind me to do [something] at [time]
  • แจ้งให้ผู้ใช้ทราบว่าแอป Chat ตอบกลับทุกคนในพื้นที่ทำงานหรือ ตอบกลับแบบส่วนตัวไปยังผู้ใช้ที่เรียกใช้คำสั่ง เช่น สำหรับคำสั่งด่วน About คุณอาจอธิบายได้ว่า Learn about this app (Only visible to you)

กำหนดค่าคำสั่งในคอนโซล Google Cloud

หากต้องการสร้างคำสั่งเครื่องหมายทับ คำสั่งด่วน หรือการดำเนินการที่แนะนำ คุณต้องระบุข้อมูลเกี่ยวกับคำสั่งหรือการดำเนินการในการกำหนดค่าของแอป Chat สำหรับ Google Chat API

หากต้องการกำหนดค่าคำสั่งใน Google Chat API ให้ทำตามขั้นตอนต่อไปนี้

  1. ในคอนโซล Google Cloud ให้คลิกเมนู > API และบริการ > API และบริการที่เปิดใช้ > Google Chat API

    ไปที่หน้า Google Chat API

  2. คลิกการกำหนดค่า

  3. ในส่วนการตั้งค่าการเชื่อมต่อ ให้ไปที่ทริกเกอร์และระบุรายละเอียดของ ปลายทาง คุณต้องใช้ทริกเกอร์นี้ในส่วนต่อไปนี้เพื่อตอบสนองต่อคำสั่ง

    1. URL ปลายทาง HTTP: คุณระบุ URL ปลายทาง HTTP ทั่วไปได้ 1 รายการที่นี่ หรือหากต้องการใช้ปลายทาง HTTP อื่นสำหรับทริกเกอร์ต่างๆ ให้ระบุปลายทางในช่องคำสั่งแอปโดยตรง
    2. Apps Script: ป้อนรหัสการติดตั้งใช้งาน Apps Script โดยค่าเริ่มต้น ระบบจะเรียกใช้ฟังก์ชัน onAppCommand หากต้องการใช้ฟังก์ชัน Apps Script อื่น ให้ระบุชื่อฟังก์ชันที่กำหนดเองในช่องคำสั่งแอป
  4. ในส่วนคำสั่ง ให้คลิกเพิ่มคำสั่ง

  5. ป้อนข้อมูลต่อไปนี้เกี่ยวกับคำสั่ง

    1. รหัสคำสั่ง: ตัวเลขตั้งแต่ 1 ถึง 1000 ที่แอป Chat ใช้เพื่อจดจำคำสั่ง และส่งคืนการตอบกลับ
    2. คำอธิบาย: ข้อความที่อธิบายวิธีใช้และจัดรูปแบบ คำสั่ง คำอธิบายมีความยาวได้ไม่เกิน 50 อักขระ
    3. ประเภทคำสั่ง: เลือกคำสั่งด่วน คำสั่งเครื่องหมายทับ หรือ การดำเนินการกับข้อความ
    4. ระบุชื่อสำหรับคำสั่ง
      • ชื่อคำสั่งด่วน: ชื่อที่แสดงซึ่งผู้ใช้เลือกจากเมนู เพื่อเรียกใช้คำสั่ง มีความยาวได้สูงสุด 50 อักขระและมี อักขระพิเศษได้ เช่น Remind me
      • ชื่อคำสั่งเครื่องหมายทับ: ข้อความที่ผู้ใช้พิมพ์เพื่อเรียกใช้คำสั่งในข้อความ ต้องขึ้นต้นด้วยเครื่องหมายทับ มีเฉพาะข้อความ และ มีความยาวได้สูงสุด 50 อักขระ เช่น /remindMe
      • ชื่อการดำเนินการที่แนะนำของข้อความ: ชื่อที่แสดงซึ่งผู้ใช้เลือกจากเมนู เพื่อเรียกใช้การดำเนินการที่แนะนำของข้อความ มีความยาวได้สูงสุด 50 อักขระและ มีอักขระพิเศษได้ เช่น Remind me
  6. ไม่บังคับ: ข้อความแจ้งเตือนการโหลด: ข้อความแจ้งเตือนแบบป๊อปอัปที่จะแสดงต่อผู้ใช้ขณะที่ระบบกำลังดำเนินการตามข้อความ ใช้ได้เฉพาะ กับการดำเนินการกับข้อความที่ไม่ได้เปิดกล่องโต้ตอบ

  7. ไม่บังคับ: หากต้องการให้แอป Chat ตอบกลับคำสั่งด้วยกล่องโต้ตอบ ให้เลือกช่องทําเครื่องหมายเปิดกล่องโต้ตอบ

  8. คลิกบันทึก

ตอนนี้คำสั่งได้รับการกำหนดค่าสำหรับแอป Chat แล้ว

จับคู่คำสั่งในแผนที่กับพรอมต์เริ่มต้น

คุณสามารถแสดงคำสั่งเป็นพรอมต์เริ่มต้นเพื่อให้ผู้ใช้เห็นคำสั่งเป็น ชิปแบบอินเทอร์แอกทีฟเมื่อเริ่มส่งข้อความส่วนตัวแบบ 1:1 ที่ว่างเปล่ากับแอป แชทของคุณ

วิธีเชื่อมโยงคำสั่งกับพรอมต์เริ่มต้น

  1. ตรวจสอบว่าคำสั่งของคุณไม่จำเป็นต้องใช้อาร์กิวเมนต์ที่กำหนดเองเพิ่มเติม (ระบบรองรับเฉพาะคำสั่งที่ไม่มีอาร์กิวเมนต์หรืออาร์กิวเมนต์พื้นฐานเป็นพรอมต์เริ่มต้น)
  2. ในคอนโซล Google Cloud ให้ไปที่หน้าการกำหนดค่าของ Chat API
  3. ในส่วนฟีเจอร์แบบอินเทอร์แอกทีฟ > พรอมต์เริ่มต้น ให้คลิกเพิ่มพรอมต์
  4. กำหนดอันดับ (1-3) สำหรับลำดับการแสดงผล
  5. ในส่วนการเลือกประเภท ให้เลือกพรอมต์คำสั่ง แล้วเลือกคำสั่งจากเมนูแบบเลื่อนลง
  6. คลิกเสร็จสิ้น แล้วคลิกบันทึก

ตอบสนองต่อคำสั่ง

เมื่อผู้ใช้ใช้คำสั่ง แอป Chat จะได้รับออบเจ็กต์เหตุการณ์ เพย์โหลดเหตุการณ์ (event.chat.appCommandPayload) มีออบเจ็กต์ appCommandPayload พร้อมรายละเอียดเกี่ยวกับคำสั่งที่เรียกใช้ (รวมถึงรหัสคำสั่งและประเภทคำสั่ง) เพื่อให้คุณส่งคืนการตอบกลับที่เหมาะสมได้ ระบบจะส่งออบเจ็กต์เหตุการณ์ไปยังฟังก์ชัน HTTP ปลายทางหรือ Apps Script ที่คุณระบุเมื่อกำหนดค่าทริกเกอร์คำสั่งแอป

ข้อความส่วนตัวสำหรับแอปแชทของ Cymbal Labs โดยข้อความระบุว่าแอปแชทสร้างโดย Cymbal Labs และแชร์ลิงก์ไปยังเอกสารประกอบและลิงก์สำหรับติดต่อทีมสนับสนุน
แอปใน Chat จะตอบกลับคำสั่งเครื่องหมายทับ slash /help แบบส่วนตัวเพื่ออธิบายวิธีรับการสนับสนุน

ตอบกลับคำสั่งเครื่องหมายทับหรือคำสั่งด่วน

โค้ดต่อไปนี้แสดงตัวอย่างแอป Chat ที่ตอบกลับคำสั่งเครื่องหมายทับ /about ด้วยข้อความ หากต้องการตอบกลับ คำสั่งเครื่องหมายทับหรือคำสั่งด่วน แอป Chat จะจัดการ ออบเจ็กต์เหตุการณ์ (event.chat.appCommandPayload) จากทริกเกอร์คำสั่งแอป เมื่อเพย์โหลดของออบเจ็กต์เหตุการณ์มีรหัสคำสั่งที่ตรงกัน แอป Chat จะแสดงผลการดำเนินการ DataActions พร้อมด้วยออบเจ็กต์ createMessageAction (hostAppDataAction.chatDataAction.createMessageAction)

Node.js

node/chat/avatar-app/index.js
// The ID of the slash command "/about".
// You must use the same ID in the Google Chat API configuration.
const ABOUT_COMMAND_ID = 1;

/**
 * Handle requests from Google Workspace add on
 *
 * @param {Object} req Request sent by Google Chat
 * @param {Object} res Response to be sent back to Google Chat
 */
http('avatarApp', (req, res) => {
  const chatEvent = req.body.chat;
  let message;
  if (chatEvent.appCommandPayload) {
    message = handleAppCommand(chatEvent);
  } else {
    message = handleMessage(chatEvent);
  }
  res.send({ hostAppDataAction: { chatDataAction: { createMessageAction: {
    message: message
  }}}});
});

/**
 * Responds to an APP_COMMAND event in Google Chat.
 *
 * @param {Object} event the event object from Google Chat
 * @return the response message object.
 */
function handleAppCommand(event) {
  switch (event.appCommandPayload.appCommandMetadata.appCommandId) {
    case ABOUT_COMMAND_ID:
      return {
        text: 'The Avatar app replies to Google Chat messages.'
      };
  }
}

Python

python/chat/avatar-app/main.py
# The ID of the slash command "/about".
# You must use the same ID in the Google Chat API configuration.
ABOUT_COMMAND_ID = 1

@functions_framework.http
def avatar_app(req: flask.Request) -> Mapping[str, Any]:
  """Handle requests from Google Workspace add on

  Args:
    flask.Request req: the request sent by Google Chat

  Returns:
    Mapping[str, Any]: the response to be sent back to Google Chat
  """
  chat_event = req.get_json(silent=True)["chat"]
  if chat_event and "appCommandPayload" in chat_event:
    message = handle_app_command(chat_event)
  else:
    message = handle_message(chat_event)
  return { "hostAppDataAction": { "chatDataAction": { "createMessageAction": {
      "message": message
  }}}}

def handle_app_command(event: Mapping[str, Any]) -> Mapping[str, Any]:
  """Responds to an APP_COMMAND event in Google Chat.

  Args:
    Mapping[str, Any] event: the event object from Google Chat

  Returns:
    Mapping[str, Any]: the response message object.
  """
  if event["appCommandPayload"]["appCommandMetadata"]["appCommandId"] == ABOUT_COMMAND_ID:
    return {
      "text": "The Avatar app replies to Google Chat messages.",
    }
  return {}

Java

java/chat/avatar-app/src/main/java/com/google/chat/avatar/App.java
// The ID of the slash command "/about".
// You must use the same ID in the Google Chat API configuration.
private static final int ABOUT_COMMAND_ID = 1;

private static final Gson gson = new Gson();

/**
 * Handle requests from Google Workspace add on
 * 
 * @param request the request sent by Google Chat
 * @param response the response to be sent back to Google Chat
 */
@Override
public void service(HttpRequest request, HttpResponse response) throws Exception {
  JsonObject event = gson.fromJson(request.getReader(), JsonObject.class);
  JsonObject chatEvent = event.getAsJsonObject("chat");
  Message message;
  if (chatEvent.has("appCommandPayload")) {
    message = handleAppCommand(chatEvent);
  } else {
    message = handleMessage(chatEvent);
  }
  JsonObject createMessageAction = new JsonObject();
  createMessageAction.add("message", gson.fromJson(gson.toJson(message), JsonObject.class));
  JsonObject chatDataAction = new JsonObject();
  chatDataAction.add("createMessageAction", createMessageAction);
  JsonObject hostAppDataAction = new JsonObject();
  hostAppDataAction.add("chatDataAction", chatDataAction);
  JsonObject dataActions = new JsonObject();
  dataActions.add("hostAppDataAction", hostAppDataAction);
  response.getWriter().write(gson.toJson(dataActions));
}

/**
 * Handles an APP_COMMAND event in Google Chat.
 *
 * @param event the event object from Google Chat
 * @return the response message object.
 */
private Message handleAppCommand(JsonObject event) throws Exception {
  switch (event.getAsJsonObject("appCommandPayload")
    .getAsJsonObject("appCommandMetadata").get("appCommandId").getAsInt()) {
    case ABOUT_COMMAND_ID:
      return new Message()
        .setText("The Avatar app replies to Google Chat messages.");
    default:
      return null;
  }
}

Apps Script

apps-script/chat/avatar-app/Code.gs
// The ID of the slash command "/about".
// You must use the same ID in the Google Chat API configuration.
const ABOUT_COMMAND_ID = 1;

/**
 * Responds to an APP_COMMAND event in Google Chat.
 *
 * @param {Object} event the event object from Google Chat
 */
function onAppCommand(event) {
  // Executes the app command logic based on ID.
  switch (event.chat.appCommandPayload.appCommandMetadata.appCommandId) {
    case ABOUT_COMMAND_ID:
      return { hostAppDataAction: { chatDataAction: { createMessageAction: { message: {
        text: 'The Avatar app replies to Google Chat messages.'
      }}}}};
  }
}

หากต้องการใช้ตัวอย่างโค้ดนี้ ให้แทนที่ ABOUT_COMMAND_ID ด้วย รหัสคำสั่งที่คุณระบุเมื่อ กำหนดค่าคำสั่งใน Chat API

ตอบกลับการดำเนินการที่แนะนำ

โค้ดต่อไปนี้แสดงตัวอย่างแอป Chat ที่ตอบกลับการดำเนินการที่แนะนำ เตือนฉัน ด้วยข้อความ หากต้องการตอบกลับการดำเนินการกับข้อความ แอป Chat จะจัดการออบเจ็กต์เหตุการณ์ จากทริกเกอร์คำสั่งแอป เมื่อเพย์โหลดของออบเจ็กต์เหตุการณ์มีรหัสคำสั่งการดำเนินการของข้อความ แอป Chat จะแสดงการดำเนินการ DataActions พร้อมออบเจ็กต์ createMessageAction ดังนี้

Node.js

/**
 * Responds to an APP_COMMAND interaction event from Google Chat.
 *
 * @param {Object} event The interaction event from Google Chat.
 * @param {Object} res The HTTP response object.
 * @return {Object} The JSON response message with a confirmation.
 */
function onAppCommand(event, res) {
  // Collect the command ID and type from the event metadata.
  const {appCommandId, appCommandType} =
    event.chat.appCommandPayload.appCommandMetadata;

  if (appCommandType === 'MESSAGE_ACTION' &&
      appCommandId === REMIND_ME_COMMAND_ID) {

    // Message actions can access the context of the message they were
    // invoked on, such as the text or sender of that message.
    const messageText = event.chat.appCommandPayload.message.text;

    // Return a response that includes details from the original message.
    return res.json({
      "hostAppDataAction": {
        "chatDataAction": {
          "createMessageAction": {
            "message": {
              "text": `Setting a reminder for message: "${messageText}"`
            }
          }
        }
      }
    });
  }
}

Python

def on_app_command(event):
    """Responds to an APP_COMMAND interaction event from Google Chat.

    Args:
        event (dict): The interaction event from Google Chat.

    Returns:
        dict: The JSON response message with a confirmation.
    """
    # Collect the command ID and type from the event metadata.
    payload = event.get('chat', {}).get('appCommandPayload', {})
    metadata = payload.get('appCommandMetadata', {})
    if metadata.get('appCommandType') == 'MESSAGE_ACTION' and \
       metadata.get('appCommandId') == REMIND_ME_COMMAND_ID:

        # Message actions can access the context of the message they were
        # invoked on, such as the text or sender of that message.
        message_text = payload.get('message', {}).get('text')

        # Return a response that includes details from the original message.
        return {
            "hostAppDataAction": {
                "chatDataAction": {
                    "createMessageAction": {
                        "message": {
                            "text": f'Setting a reminder for message: "{message_text}"'
                        }
                    }
                }
            }
        }

Java

/**
 * Responds to an APP_COMMAND interaction event from Google Chat.
 *
 * @param event The interaction event from Google Chat.
 * @param response The HTTP response object.
 */
void onAppCommand(JsonObject event, HttpResponse response) throws Exception {
  // Collect the command ID and type from the event metadata.
  JsonObject payload = event.getAsJsonObject("chat").getAsJsonObject("appCommandPayload");
  JsonObject metadata = payload.getAsJsonObject("appCommandMetadata");
  String appCommandType = metadata.get("appCommandType").getAsString();

  if (appCommandType.equals("MESSAGE_ACTION")) {
    int commandId = metadata.get("appCommandId").getAsInt();
    if (commandId == REMIND_ME_COMMAND_ID) {
      // Message actions can access the context of the message they were
      // invoked on, such as the text or sender of that message.
      String messageText = payload.getAsJsonObject("message").get("text").getAsString();

      // Return a response that includes details from the original message.
      JsonObject responseMessage = new JsonObject();
      responseMessage.addProperty("text", "Setting a reminder for message: " + messageText);

      JsonObject createMessageAction = new JsonObject();
      createMessageAction.add("message", responseMessage);

      JsonObject chatDataAction = new JsonObject();
      chatDataAction.add("createMessageAction", createMessageAction);

      JsonObject hostAppDataAction = new JsonObject();
      hostAppDataAction.add("chatDataAction", chatDataAction);

      JsonObject finalResponse = new JsonObject();
      finalResponse.add("hostAppDataAction", hostAppDataAction);

      response.getWriter().write(finalResponse.toString());
    }
  }
}

Apps Script

/**
 * Responds to an APP_COMMAND interaction event in Google Chat.
 *
 * @param {Object} event The interaction event from Google Chat.
 * @return {Object} The JSON response message with a confirmation.
 */
function onAppCommand(event) {
  // Collect the command ID and type from the event metadata.
  const {appCommandId, appCommandType} =
    event.chat.appCommandPayload.appCommandMetadata;

  if (appCommandType === 'MESSAGE_ACTION' &&
      appCommandId === REMIND_ME_COMMAND_ID) {

    // Message actions can access the context of the message they were
    // invoked on, such as the text or sender of that message.
    const messageText = event.chat.appCommandPayload.message.text;

    // Return a response that includes details from the original message.
    return CardService.newChatResponseBuilder()
        .setText("Setting a reminder for message: " + messageText)
        .build();
  }
}

หากต้องการใช้ตัวอย่างโค้ดนี้ ให้แทนที่ REMIND_ME_COMMAND_ID ด้วย รหัสคำสั่งที่คุณระบุเมื่อ กำหนดค่าคำสั่งใน Chat API

ทดสอบคำสั่ง

หากต้องการทดสอบคำสั่งและโค้ด โปรดดูทดสอบฟีเจอร์แบบอินเทอร์แอกทีฟสำหรับแอป Google Chat

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

แอป Chat ที่ไม่ใช่ส่วนเสริม: ตอบกลับคำสั่ง

เอกสารต่อไปนี้ใช้กับแอป Chat ที่ไม่ใช่ส่วนเสริมของ Google Workspace หากต้องการย้ายข้อมูลแอป Chat ที่ไม่ใช่ส่วนเสริม โปรดดูหัวข้อแปลงแอป Google Chat เป็นส่วนเสริม Google Workspace

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

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

ประเภทคำสั่ง ประเภทของกิจกรรม ข้อมูลเมตาของคำสั่ง
คำสั่งเครื่องหมายทับ MESSAGE message.slashCommand หรือ message.annotation.slashCommand
คำสั่งด่วน APP_COMMAND appCommandMetadata
การดำเนินการที่แนะนำสำหรับข้อความ APP_COMMAND appCommandMetadata

ตอบกลับคำสั่งเครื่องหมายทับ

โค้ดต่อไปนี้แสดงตัวอย่างแอป Chat ที่ไม่ใช่ส่วนเสริมซึ่งตอบกลับคำสั่งเครื่องหมายทับ /about แอป Chat จะจัดการMESSAGEเหตุการณ์การโต้ตอบ ตรวจหาว่าเหตุการณ์การโต้ตอบ มีรหัสคำสั่งที่ตรงกันหรือไม่ และแสดงออบเจ็กต์ Message ส่วนตัว

Node.js

node/avatar-app/index.js
/**
 * Handles slash and quick commands.
 *
 * @param {Object} event - The Google Chat event.
 * @param {Object} res - The HTTP response object.
 */
function handleAppCommands(event, res) {
  const {appCommandId, appCommandType} = event.appCommandMetadata;

  switch (appCommandId) {
    case ABOUT_COMMAND_ID:
      return res.send({
        privateMessageViewer: event.user,
        text: 'The Avatar app replies to Google Chat messages.'
      });
    case HELP_COMMAND_ID:
      return res.send({
        privateMessageViewer: event.user,
        text: 'The Avatar app replies to Google Chat messages.'
      });
  }
}

Apps Script

apps-script/avatar-app/avatar-app.gs
// Checks for the presence of a slash command in the message.
if (event.message.slashCommand) {
  // Executes the slash command logic based on its ID.
  // Slash command IDs are set in the Google Chat API configuration.
  switch (event.message.slashCommand.commandId) {
    case ABOUT_COMMAND_ID:
      return {
        privateMessageViewer: event.user,
        text: 'The Avatar app replies to Google Chat messages.'
      };
  }
}

Python

python/avatar-app/main.py
def handle_app_commands(event: Mapping[str, Any]) -> Mapping[str, Any]:
    """Handles slash and quick commands.

    Args:
        Mapping[str, Any] event: The Google Chat event.

    Returns:
        Mapping[str, Any]: the response
    """
    app_command_id = event["appCommandMetadata"]["appCommandId"]

    if app_command_id == ABOUT_COMMAND_ID:
        return {
            "privateMessageViewer": event["user"],
            "text": "The Avatar app replies to Google Chat messages.",
        }
    elif app_command_id == HELP_COMMAND_ID:
        return {
            "privateMessageViewer": event["user"],
            "text": "The Avatar app replies to Google Chat messages.",
        }
    return {}

Java

java/avatar-app/src/main/java/AvatarApp.java
/**
 * Handles slash and quick commands.
 *
 * @param event    The Google Chat event.
 * @param response The HTTP response object.
 */
private void handleAppCommands(JsonObject event, HttpResponse response) throws Exception {
  int appCommandId = event.getAsJsonObject("appCommandMetadata").get("appCommandId").getAsInt();

  switch (appCommandId) {
    case ABOUT_COMMAND_ID:
      Message aboutMessage = new Message();
      aboutMessage.setText("The Avatar app replies to Google Chat messages.");
      aboutMessage.setPrivateMessageViewer(new User()
          .setName(event.getAsJsonObject("user").get("name").getAsString()));
      response.getWriter().write(gson.toJson(aboutMessage));
      return;
    case HELP_COMMAND_ID:
      Message helpMessage = new Message();
      helpMessage.setText("The Avatar app replies to Google Chat messages.");
      helpMessage.setPrivateMessageViewer(new User()
          .setName(event.getAsJsonObject("user").get("name").getAsString()));
      response.getWriter().write(gson.toJson(helpMessage));
      return;
  }
}

แทนที่ ABOUT_COMMAND_ID ด้วยรหัสคำสั่งที่คุณ ระบุเมื่อกำหนดค่าคำสั่งในคอนโซล Google Cloud

ตอบกลับคำสั่งสั้นๆ

โค้ดต่อไปนี้แสดงตัวอย่างแอป Chat ที่ไม่ใช่ส่วนเสริมซึ่งตอบกลับคำสั่งด่วน Help แอป Chat จะจัดการAPP_COMMANDเหตุการณ์การโต้ตอบ ตรวจหาว่าเหตุการณ์การโต้ตอบ มีรหัสคำสั่งที่ตรงกันหรือไม่ และแสดงออบเจ็กต์ Message ส่วนตัว

Node.js

node/avatar-app/index.js
/**
 * Handles slash and quick commands.
 *
 * @param {Object} event - The Google Chat event.
 * @param {Object} res - The HTTP response object.
 */
function handleAppCommands(event, res) {
  const {appCommandId, appCommandType} = event.appCommandMetadata;

  switch (appCommandId) {
    case ABOUT_COMMAND_ID:
      return res.send({
        privateMessageViewer: event.user,
        text: 'The Avatar app replies to Google Chat messages.'
      });
    case HELP_COMMAND_ID:
      return res.send({
        privateMessageViewer: event.user,
        text: 'The Avatar app replies to Google Chat messages.'
      });
  }
}

Apps Script

apps-script/avatar-app/avatar-app.gs
/**
 * Handles the APP_COMMAND event type. This function is triggered when a user
 * interacts with a quick command within the Google Chat app.  It responds
 * based on the command ID.
 *
 * @param {Object} event The event object from Google Chat, containing details
 *     about the app command interaction.  It includes information like the
 *     command ID and the user who triggered it.
 */
function onAppCommand(event) {
  // Executes the quick command logic based on its ID.
  // Command IDs are set in the Google Chat API configuration.
  switch (event.appCommandMetadata.appCommandId) {
    case HELP_COMMAND_ID:
      return {
        privateMessageViewer: event.user,
        text: 'The Avatar app replies to Google Chat messages.'
      };
  }
}

Python

python/avatar-app/main.py
def handle_app_commands(event: Mapping[str, Any]) -> Mapping[str, Any]:
    """Handles slash and quick commands.

    Args:
        Mapping[str, Any] event: The Google Chat event.

    Returns:
        Mapping[str, Any]: the response
    """
    app_command_id = event["appCommandMetadata"]["appCommandId"]

    if app_command_id == ABOUT_COMMAND_ID:
        return {
            "privateMessageViewer": event["user"],
            "text": "The Avatar app replies to Google Chat messages.",
        }
    elif app_command_id == HELP_COMMAND_ID:
        return {
            "privateMessageViewer": event["user"],
            "text": "The Avatar app replies to Google Chat messages.",
        }
    return {}

Java

java/avatar-app/src/main/java/AvatarApp.java
/**
 * Handles slash and quick commands.
 *
 * @param event    The Google Chat event.
 * @param response The HTTP response object.
 */
private void handleAppCommands(JsonObject event, HttpResponse response) throws Exception {
  int appCommandId = event.getAsJsonObject("appCommandMetadata").get("appCommandId").getAsInt();

  switch (appCommandId) {
    case ABOUT_COMMAND_ID:
      Message aboutMessage = new Message();
      aboutMessage.setText("The Avatar app replies to Google Chat messages.");
      aboutMessage.setPrivateMessageViewer(new User()
          .setName(event.getAsJsonObject("user").get("name").getAsString()));
      response.getWriter().write(gson.toJson(aboutMessage));
      return;
    case HELP_COMMAND_ID:
      Message helpMessage = new Message();
      helpMessage.setText("The Avatar app replies to Google Chat messages.");
      helpMessage.setPrivateMessageViewer(new User()
          .setName(event.getAsJsonObject("user").get("name").getAsString()));
      response.getWriter().write(gson.toJson(helpMessage));
      return;
  }
}

แทนที่ HELP_COMMAND_ID ด้วยรหัสคำสั่งที่คุณ ระบุเมื่อกำหนดค่าคำสั่งในคอนโซล Google Cloud

ตอบกลับการดำเนินการที่แนะนำ

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

Node.js

/**
 * Responds to an APP_COMMAND interaction event from Google Chat.
 *
 * @param {Object} event The interaction event from Google Chat.
 * @param {Object} res The HTTP response object.
 * @return {Object} The JSON response message with a confirmation.
 */
function handleAppCommand(event, res) {
  // Collect the command ID and type from the event metadata.
  const {appCommandId, appCommandType} = event.appCommandMetadata;

  // Use appCommandType to detect message actions.
  if (appCommandType === 'MESSAGE_ACTION' &&
      appCommandId === REMIND_ME_COMMAND_ID) {

    // Message actions can access the context of the message they were
    // invoked on, such as the text or sender of that message.
    const messageText = event.message.text;

    // Return a response that includes details from the original message.
    return res.send({
      text: `Setting a reminder for this message: "${messageText}"`
    });
  }
}

Apps Script

/**
 * Responds to an APP_COMMAND interaction event in Google Chat.
 *
 * @param {Object} event The interaction event from Google Chat.
 * @return {Object} The JSON response message with a confirmation.
 */
function onAppCommand(event) {
  // Collect the command ID and type from the event metadata.
  const {appCommandId, appCommandType} = event.appCommandMetadata;

  if (appCommandType === 'MESSAGE_ACTION' &&
      appCommandId === REMIND_ME_COMMAND_ID) {

    // Message actions can access the context of the message they were
    // invoked on, such as the text or sender of that message.
    const messageText = event.message.text;

    // Return a response that includes details from the original message.
    return { "text": "Setting a reminder for message: " + messageText };
  }
}

Python

def handle_app_command(event):
    """Responds to an APP_COMMAND interaction event from Google Chat.

    Args:
        event (dict): The interaction event from Google Chat.

    Returns:
        dict: The JSON response message with a confirmation.
    """
    # Collect the command ID and type from the event metadata.
    metadata = event.get('appCommandMetadata', {})
    if metadata.get('appCommandType') == 'MESSAGE_ACTION' and \
       metadata.get('appCommandId') == REMIND_ME_COMMAND_ID:

        # Message actions can access the context of the message they were
        # invoked on, such as the text or sender of that message.
        message_text = event.get('message', {}).get('text')

        # Return a response that includes details from the original message.
        return {
            "text": f'Setting a reminder for message: "{message_text}"'
        }

Java

/**
 * Responds to an APP_COMMAND interaction event from Google Chat.
 *
 * @param event The interaction event from Google Chat.
 * @param response The HTTP response object.
 */
void handleAppCommand(JsonObject event, HttpResponse response) throws Exception {
  // Collect the command ID and type from the event metadata.
  JsonObject metadata = event.getAsJsonObject("appCommandMetadata");
  String appCommandType = metadata.get("appCommandType").getAsString();

  if (appCommandType.equals("MESSAGE_ACTION")) {
    int commandId = metadata.get("appCommandId").getAsInt();
    if (commandId == REMIND_ME_COMMAND_ID) {
      // Message actions can access the context of the message they were
      // invoked on, such as the text or sender of that message.
      String messageText = event.getAsJsonObject("message").get("text").getAsString();

      // Return a response that includes details from the original message.
      JsonObject responseMessage = new JsonObject();
      responseMessage.addProperty("text", "Setting a reminder for message: " + messageText);
      response.getWriter().write(responseMessage.toString());
    }
  }
}

แทนที่ REMIND_ME_COMMAND_ID ด้วยรหัสคำสั่งที่คุณ ระบุเมื่อกำหนดค่าคำสั่งในคอนโซล Google Cloud