🤖 SmartPR Chatbot API

คู่มือการใช้งาน API สำหรับระบบ AI Chatbot

ภาพรวมระบบ

SmartPR Chatbot API เป็นระบบ AI Chatbot ที่ใช้เทคโนโลยี DeepSeek AI และ RAG (Retrieval-Augmented Generation) เพื่อตอบคำถามจากฐานความรู้

💡 จุดเด่นของระบบ:
  • ✅ ค้นหาข้อมูลจาก SQL Database อัตโนมัติ
  • ✅ ใช้ AI ประมวลผลและตอบคำถาม
  • ✅ รองรับการใช้งานผ่าน LINE Messaging API
  • ✅ บันทึกประวัติการสนทนาทั้งหมด

🏗️ สถาปัตยกรรมระบบ

ผู้ใช้ส่งคำถาม ↓ LINE API ส่งไปที่ Webhook ↓ ระบบค้นหาความรู้จาก SQL (RAG) ↓ ส่งคำถาม + ความรู้ไปที่ DeepSeek AI ↓ AI ประมวลผลและตอบ ↓ ส่งคำตอบกลับผู้ใช้ผ่าน LINE ↓ บันทึกประวัติการสนทนา

LINE Webhook Endpoint

POST รับข้อความจาก LINE และตอบด้วย AI
https://your-domain.com/pr_web/api/chatbot_webhook.php

Endpoint นี้รับ Webhook จาก LINE Messaging API และประมวลผลด้วย AI Chatbot

📥 Request Body (จาก LINE)

{ "events": [ { "type": "message", "replyToken": "nHuyWiB7yP5Zw52FIkcQobQuGDXCTA", "source": { "userId": "U4af4980629...", "type": "user" }, "message": { "id": "325708", "type": "text", "text": "วิทยาลัยอยู่ที่ไหน?" } } ] }

📤 Response (ส่งกลับไปที่ LINE)

{ "replyToken": "nHuyWiB7yP5Zw52FIkcQobQuGDXCTA", "messages": [ { "type": "text", "text": "วิทยาลัยการอาชีพปราสาท ตั้งอยู่เลขที่ 191 หมู่ 15 ตำบลโคกยาง อำเภอปราสาท จังหวัดสุรินทร์ 32140\n\n📞 เบอร์โทรศัพท์: 044-545678\n🌐 เว็บไซต์: https://prasat.ac.th" } ] }
⚠️ หมายเหตุ: Endpoint นี้ใช้สำหรับ LINE Webhook เท่านั้น ต้องตั้งค่า Webhook URL ใน LINE Developers Console

⚙️ การตั้งค่า LINE Webhook

  1. ไปที่ LINE Developers Console
  2. เลือก Channel ของคุณ
  3. ไปที่ Messaging API tab
  4. ในส่วน Webhook settings:
    • Webhook URL: https://your-domain.com/pr_web/api/chatbot_webhook.php
    • Use webhook: เปิด
    • Auto-reply messages: ปิด

n8n Integration Guide

คู่มือการเชื่อมต่อ Knowledge Search API กับ n8n เพื่อสร้าง Workflow อัตโนมัติ

💡 Use Cases:
  • 🔍 สร้างระบบค้นหาข้อมูลอัตโนมัติจากคำถามของผู้ใช้
  • 🤖 เชื่อมต่อกับ Chatbot platforms อื่นๆ (Telegram, Facebook Messenger)
  • 📊 สร้างระบบ FAQ อัตโนมัติ
  • 📧 Auto-reply อีเมลด้วยข้อมูลจากฐานความรู้

🔧 การตั้งค่า n8n HTTP Request Node

Step 1: เพิ่ม HTTP Request Node

  1. เปิด n8n Workflow Editor
  2. เพิ่ม HTTP Request node
  3. ตั้งค่าดังนี้:
Setting Value
Method POST
URL https://your-domain.com/pr_web/api/knowledge_search.php
Authentication Header Auth
Body Content Type JSON

Step 2: ตั้งค่า Headers

เพิ่ม Header สำหรับ Authentication:

Name Value
X-API-Key sk-your-api-key-here
Content-Type application/json

Step 3: ตั้งค่า Request Body

{ "query": "{{ $json.message }}", "limit": 3 }

หมายเหตุ: {{ $json.message }} จะดึงค่าจาก node ก่อนหน้า (เช่น Webhook, Trigger)

Step 4: ประมวลผล Response

เพิ่ม Code node หรือ Set node เพื่อประมวลผลข้อมูลที่ได้:

// ตัวอย่าง Code node สำหรับ format ข้อมูล const results = $input.item.json.results; if (results && results.length > 0) { // สร้างข้อความจากผลลัพธ์ let response = "พบข้อมูลที่เกี่ยวข้อง:\\n\\n"; results.forEach((item, index) => { response += `${index + 1}. ${item.title}\\n`; response += `${item.content}\\n\\n`; }); return { json: { found: true, message: response, total: results.length } }; } else { return { json: { found: false, message: "ไม่พบข้อมูลที่เกี่ยวข้อง" } }; }

📝 ตัวอย่าง n8n Workflow (JSON)

{ "nodes": [ { "parameters": { "httpMethod": "POST", "path": "chatbot", "responseMode": "responseNode", "options": {} }, "name": "Webhook", "type": "n8n-nodes-base.webhook", "position": [250, 300] }, { "parameters": { "url": "https://your-domain.com/pr_web/api/knowledge_search.php", "sendBody": true, "specifyBody": "json", "jsonBody": "={{ { \"query\": $json.message, \"limit\": 3 } }}", "options": { "headers": { "entries": [ { "name": "X-API-Key", "value": "sk-your-api-key-here" } ] } } }, "name": "Knowledge Search", "type": "n8n-nodes-base.httpRequest", "position": [450, 300] }, { "parameters": { "respondWith": "json", "responseBody": "={{ $json }}" }, "name": "Respond to Webhook", "type": "n8n-nodes-base.respondToWebhook", "position": [650, 300] } ], "connections": { "Webhook": { "main": [[{"node": "Knowledge Search", "type": "main", "index": 0}]] }, "Knowledge Search": { "main": [[{"node": "Respond to Webhook", "type": "main", "index": 0}]] } } }

🧪 ทดสอบ Workflow

ใช้ cURL ทดสอบ n8n Webhook:

curl -X POST https://your-n8n-instance.com/webhook/chatbot \ -H "Content-Type: application/json" \ -d '{ "message": "วิทยาลัยมีสาขาอะไรบ้าง" }'

ผลลัพธ์ที่ได้รับ

{ "success": true, "query": "วิทยาลัยมีสาขาอะไรบ้าง", "total_results": 3, "results": [ { "title": "สาขาวิชาที่เปิดสอน", "content": "วิทยาลัยการอาชีพปราสาท เปิดสอน 5 สาขา..." } ] }
💡 Tips:
  • ✅ ใช้ Error Trigger node เพื่อจัดการข้อผิดพลาด
  • ✅ เก็บ API Key ใน n8n Credentials แทนการ hardcode
  • ✅ ใช้ IF node เพื่อตรวจสอบว่ามีผลลัพธ์หรือไม่
  • ✅ เพิ่ม Retry logic เมื่อ API ล้มเหลว

API ทดสอบการสนทนา

POST ทดสอบการสนทนากับ AI
https://your-domain.com/pr_web/admin/chatbot_test.php

API นี้ใช้สำหรับทดสอบการสนทนากับ AI Chatbot โดยตรง (ไม่ผ่าน LINE)

📋 Request Parameters

Parameter Type Required Description
action string Required ต้องเป็น "send_message"
message string Required ข้อความคำถามที่ต้องการถาม AI

📥 Request Example

curl -X POST https://your-domain.com/pr_web/admin/chatbot_test.php \ -H "Content-Type: application/x-www-form-urlencoded" \ -d "action=send_message&message=วิทยาลัยมีสาขาอะไรบ้าง"
fetch('https://your-domain.com/pr_web/admin/chatbot_test.php', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', }, body: new URLSearchParams({ 'action': 'send_message', 'message': 'วิทยาลัยมีสาขาอะไรบ้าง?' }) }) .then(response => response.json()) .then(data => console.log(data));
$ch = curl_init(); curl_setopt($ch, CURLOPT_URL, 'https://your-domain.com/pr_web/admin/chatbot_test.php'); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query([ 'action' => 'send_message', 'message' => 'วิทยาลัยมีสาขาอะไรบ้าง?' ])); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); $result = json_decode($response, true); echo $result['response'];

📤 Response Example

✅ Success Response

{ "success": true, "response": "สาขาวิชาที่เปิดสอน:\n\nระดับ ปวช.:\n• ช่างยนต์\n• ช่างไฟฟ้า\n• ช่างอิเล็กทรอนิกส์\n• คอมพิวเตอร์ธุรกิจ\n• การบัญชี\n• การตลาด\n\nระดับ ปวส.:\n• เทคนิคยานยนต์\n• เทคนิคไฟฟ้า\n• เทคโนโลยีสารสนเทศ\n• การบัญชี\n• การตลาด" }

❌ Error Response

{ "success": false, "error": "กรุณากรอกข้อความ" }

Authentication

การใช้งาน API บางส่วนต้องมีการ Authentication

🔓 Public Endpoints (ไม่ต้อง Auth)

🔐 Protected Endpoints (ต้อง Auth)

💡 การ Login Admin: ใช้ระบบ Session-based Authentication
// ตัวอย่างการ Login session_start(); if (isset($_SESSION['user_id']) && isset($_SESSION['user_role'])) { // User is authenticated }

ตัวอย่างการใช้งาน

📱 ตัวอย่างที่ 1: เชื่อมต่อ LINE Bot

// api/chatbot_webhook.php require_once '../includes/chatbot_functions.php'; $input = file_get_contents('php://input'); $events = json_decode($input, true); foreach ($events['events'] as $event) { if ($event['type'] === 'message' && $event['message']['type'] === 'text') { $userId = $event['source']['userId']; $message = $event['message']['text']; // ประมวลผลด้วย AI $response = processChatbotMessage($userId, $message); // ส่งคำตอบกลับ replyMessage($event['replyToken'], $response); } }

🌐 ตัวอย่างที่ 2: เรียกใช้ผ่าน AJAX

// Frontend JavaScript async function askChatbot(question) { const formData = new FormData(); formData.append('action', 'send_message'); formData.append('message', question); const response = await fetch('/pr_web/admin/chatbot_test.php', { method: 'POST', body: formData }); const result = await response.json(); if (result.success) { console.log('AI ตอบ:', result.response); return result.response; } else { console.error('Error:', result.error); return null; } } // ใช้งาน askChatbot('สมัครเรียนอย่างไร?').then(answer => { document.getElementById('answer').textContent = answer; });

🔌 ตัวอย่างที่ 3: Integration กับ Website

Error Codes

HTTP Code Error Message Description Solution
200 Success การประมวลผลสำเร็จ -
400 กรุณากรอกข้อความ ไม่มีพารามิเตอร์ message ตรวจสอบว่าส่ง message มาด้วย
401 Unauthorized ไม่มีสิทธิ์เข้าถึง Login ก่อนใช้งาน
500 API Key not configured ยังไม่ได้ตั้งค่า API Key ไปที่ chatbot_settings.php เพื่อตั้งค่า
500 Chatbot is disabled Chatbot ถูกปิดการใช้งาน เปิดใช้งานใน chatbot_settings.php

🔍 Troubleshooting

วิธีตรวจสอบ Error:
  1. ตรวจสอบ Error Log: /Applications/XAMPP/xamppfiles/logs/error_log
  2. ตรวจสอบว่า Chatbot เปิดใช้งานหรือไม่
  3. ตรวจสอบว่ามี API Key หรือไม่
  4. ทดสอบด้วย /admin/chatbot_test.php ก่อน

ต้องการความช่วยเหลือ?

หากมีคำถามหรือพบปัญหา:

Made with ❤️ for วิทยาลัยการอาชีพปราสาท