google app script เชื่อมต่อกับ diaglogflow

 function doPost(e) {

  try {

    const body = JSON.parse(e.postData.contents);

    const queryResult = body.queryResult;

    const outputContexts = queryResult.outputContexts;


    let productEntity = '';


    // ค้นหา context ที่มีชื่อลงท้ายด้วย 'getprice-followup'

    const getPriceContext = outputContexts.find(context => context.name.endsWith('getprice-followup'));


    if (getPriceContext && getPriceContext.parameters) {

      productEntity = getPriceContext.parameters.product_entity;

    }


    // ค้นหาข้อมูลใน Google Sheets

    const sheetName = "ชื่อ Sheet ของคุณ"; // แทนที่ด้วยชื่อ Sheet ที่ถูกต้อง

    const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheetName);

    const data = sheet.getDataRange().getValues();


    // ค้นหาแถวที่มี productEntity

    const row = data.find(row => row[0] === productEntity); // สมมติว่า productEntity อยู่ในคอลัมน์แรก


    let response;

    if (row) {

      // ถ้าพบข้อมูล

      const price = row[1]; // สมมติว่าราคาอยู่ในคอลัมน์ที่สอง

      response = {

        fulfillmentText: `ราคาของ ${productEntity} คือ ${price} บาท`

      };

    } else {

      // ถ้าไม่พบข้อมูล

      response = {

        fulfillmentText: `ขออภัย ไม่พบข้อมูลสำหรับ ${productEntity}`

      };

    }


    // ส่งค่ากลับเป็น JSON

    return ContentService.createTextOutput(JSON.stringify(response))

      .setMimeType(ContentService.MimeType.JSON);


  } catch (error) {

    console.error('Error in doPost:', error);

    return ContentService.createTextOutput(JSON.stringify({ 

      fulfillmentText: "ขออภัย เกิดข้อผิดพลาดบางอย่าง" 

    })).setMimeType(ContentService.MimeType.JSON);

  }

}

ความคิดเห็น

โพสต์ยอดนิยมจากบล็อกนี้