Update services/facebookService.js
Browse files- services/facebookService.js +20 -21
services/facebookService.js
CHANGED
|
@@ -1,5 +1,11 @@
|
|
| 1 |
// C:\Users\Hi\OneDrive\Desktop\TCCS\Chatbot\chatbot_server\services\facebookService.js
|
| 2 |
const axios = require('axios');
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
|
| 4 |
/**
|
| 5 |
* Hàm làm sạch văn bản: Xóa HTML rác và các tag lệnh ẩn
|
|
@@ -29,7 +35,7 @@ function formatMessage(text, psid) {
|
|
| 29 |
|
| 30 |
// 1. XỬ LÝ FORM CHỐT ĐƠN WEBVIEW
|
| 31 |
if (text.includes("[[SHOW_ORDER_FORM") || text.toUpperCase().includes("ACTION_CONFIRM")) {
|
| 32 |
-
const appUrl = process.env.APP_URL || 'https://chatbot-robot-automation.
|
| 33 |
return {
|
| 34 |
attachment: {
|
| 35 |
type: "template",
|
|
@@ -101,53 +107,43 @@ async function sendResponse(senderPsid, responseText) {
|
|
| 101 |
if (imageUrls.length >= 2) {
|
| 102 |
console.log(`📚 [FB Service] Đang cấu trúc lại Album Carousel cho ${imageUrls.length} sản phẩm...`);
|
| 103 |
|
| 104 |
-
// 1. Tách văn bản thành các khối nhỏ theo từng sản phẩm để không lấy râu ông nọ cắm cằm bà kia
|
| 105 |
const blocks = responseText.split(/(?=🔹|\*\*Mã:)/i).filter(b => b.includes('http'));
|
| 106 |
const elements = [];
|
| 107 |
|
| 108 |
-
// 2. Duyệt qua từng khối ảnh và text tương ứng
|
| 109 |
for (let i = 0; i < imageUrls.length; i++) {
|
| 110 |
const currentUrl = imageUrls[i];
|
| 111 |
const currentBlock = blocks[i] || "";
|
| 112 |
|
| 113 |
-
// Bóc tách Mã sản phẩm
|
| 114 |
const codeMatch = currentBlock.match(/\*\*Mã:\s*([^*]+)\*\*/i) || currentBlock.match(/Mã:\s*([^\n[-]+)/i);
|
| 115 |
const itemCode = codeMatch ? codeMatch[1].trim() : `Mẫu ${i + 1}`;
|
| 116 |
|
| 117 |
-
// Bóc tách Tên sản phẩm
|
| 118 |
const nameMatch = currentBlock.match(/(?:👕|👚|👕|🌱|👉|^)\s*([^\n$*|]+)/m);
|
| 119 |
let itemName = nameMatch ? nameMatch[1].trim() : "Quần áo trẻ em";
|
| 120 |
if (itemName.toLowerCase().includes("giá")) itemName = "Thời trang bé trai";
|
| 121 |
|
| 122 |
-
// Bóc tách Giá sản phẩm
|
| 123 |
const priceMatch = currentBlock.match(/Giá:\s*\*?([^*|\n]+)\*?/i);
|
| 124 |
const itemPrice = priceMatch ? priceMatch[1].trim() : "Liên hệ shop";
|
| 125 |
|
| 126 |
-
// Bóc tách cấu trúc nút bấm: Tìm kiếm toàn bộ chuỗi nằm trong cặp ngoặc vuông [LỆNH] nguyên bản
|
| 127 |
const rawButtonRegex = /(\[[^\]]+\])/g;
|
| 128 |
const rawButtons = currentBlock.match(rawButtonRegex) || [];
|
| 129 |
|
| 130 |
const buttons = [];
|
| 131 |
-
let finalPayload = `[ACTION_ADD:${itemCode}]`;
|
| 132 |
|
| 133 |
if (rawButtons.length > 0) {
|
| 134 |
-
// Lấy chính xác chuỗi thô bao gồm cả dấu ngoặc vuông (Ví dụ: "[ACTION_ADD:G02]")
|
| 135 |
const rawText = rawButtons[0].trim();
|
| 136 |
-
|
| 137 |
-
// Phân tách Nhãn và Lệnh bên trong dấu ngoặc vuông nếu có dấu gạch đứng "|"
|
| 138 |
-
const innerContent = rawText.slice(1, -1); // Bỏ dấu [ và ]
|
| 139 |
if (innerContent.includes('|')) {
|
| 140 |
finalPayload = innerContent.split('|')[1].trim();
|
| 141 |
} else {
|
| 142 |
-
finalPayload = rawText;
|
| 143 |
}
|
| 144 |
}
|
| 145 |
|
| 146 |
-
// Thiết lập cấu trúc nút bấm Postback gửi lên Facebook
|
| 147 |
buttons.push({
|
| 148 |
type: "postback",
|
| 149 |
-
title: `🛍️ CHỌN MẪU ${itemCode}`,
|
| 150 |
-
payload: finalPayload
|
| 151 |
});
|
| 152 |
|
| 153 |
if (elements.length < 10) {
|
|
@@ -162,6 +158,7 @@ async function sendResponse(senderPsid, responseText) {
|
|
| 162 |
|
| 163 |
// Gửi cấu trúc Album hoàn chỉnh
|
| 164 |
if (elements.length > 0) {
|
|
|
|
| 165 |
await axios.post(`https://graph.facebook.com/v19.0/me/messages?access_token=${accessToken}`, {
|
| 166 |
recipient: { id: senderPsid },
|
| 167 |
message: {
|
|
@@ -173,10 +170,9 @@ async function sendResponse(senderPsid, responseText) {
|
|
| 173 |
}
|
| 174 |
}
|
| 175 |
}
|
| 176 |
-
});
|
| 177 |
}
|
| 178 |
|
| 179 |
-
// 3. LỌC VÀ GỬI TEXT HƯỚNG DẪN / GIỎ HÀNG Ở CUỐI (Xóa bỏ hoàn toàn bảng kê chữ xanh cũ)
|
| 180 |
const lines = responseText.split('\n');
|
| 181 |
const bottomTextLines = lines.filter(line =>
|
| 182 |
!line.includes('http') &&
|
|
@@ -190,10 +186,11 @@ async function sendResponse(senderPsid, responseText) {
|
|
| 190 |
|
| 191 |
if (bottomText) {
|
| 192 |
const formattedBottom = formatMessage(bottomText, senderPsid);
|
|
|
|
| 193 |
await axios.post(`https://graph.facebook.com/v19.0/me/messages?access_token=${accessToken}`, {
|
| 194 |
recipient: { id: senderPsid },
|
| 195 |
message: formattedBottom
|
| 196 |
-
});
|
| 197 |
}
|
| 198 |
return;
|
| 199 |
}
|
|
@@ -204,6 +201,7 @@ async function sendResponse(senderPsid, responseText) {
|
|
| 204 |
if (imageUrls.length === 1) {
|
| 205 |
console.log(`📸 [FB Service] Gửi 1 ảnh sản phẩm lẻ: ${imageUrls[0]}`);
|
| 206 |
try {
|
|
|
|
| 207 |
await axios.post(`https://graph.facebook.com/v19.0/me/messages?access_token=${accessToken}`, {
|
| 208 |
recipient: { id: senderPsid },
|
| 209 |
message: {
|
|
@@ -212,17 +210,18 @@ async function sendResponse(senderPsid, responseText) {
|
|
| 212 |
payload: { url: imageUrls[0], is_reusable: true }
|
| 213 |
}
|
| 214 |
}
|
| 215 |
-
});
|
| 216 |
} catch (imgErr) {
|
| 217 |
console.error("⚠️ Lỗi gửi ảnh đơn:", imgErr.message);
|
| 218 |
}
|
| 219 |
}
|
| 220 |
|
| 221 |
if (formatted && (formatted.text || formatted.attachment)) {
|
|
|
|
| 222 |
await axios.post(`https://graph.facebook.com/v19.0/me/messages?access_token=${accessToken}`, {
|
| 223 |
recipient: { id: senderPsid },
|
| 224 |
message: formatted
|
| 225 |
-
});
|
| 226 |
}
|
| 227 |
|
| 228 |
console.log(`✅ [FB Service] Đã xử lý tin nhắn sạch cho khách: ${senderPsid}`);
|
|
|
|
| 1 |
// C:\Users\Hi\OneDrive\Desktop\TCCS\Chatbot\chatbot_server\services\facebookService.js
|
| 2 |
const axios = require('axios');
|
| 3 |
+
const https = require('https'); // 🎯 THÊM THƯ VIỆN ĐỂ XỬ LÝ LỖI HANDSHAKE SSL
|
| 4 |
+
|
| 5 |
+
// 🎯 TẠO HTTPS AGENT ĐỂ BẺ GÃY CÁC BỘ LỌC CHỨNG CHỈ TRÊN DOCKER HUGGING FACE
|
| 6 |
+
const sslAgent = new https.Agent({
|
| 7 |
+
rejectUnauthorized: false
|
| 8 |
+
});
|
| 9 |
|
| 10 |
/**
|
| 11 |
* Hàm làm sạch văn bản: Xóa HTML rác và các tag lệnh ẩn
|
|
|
|
| 35 |
|
| 36 |
// 1. XỬ LÝ FORM CHỐT ĐƠN WEBVIEW
|
| 37 |
if (text.includes("[[SHOW_ORDER_FORM") || text.toUpperCase().includes("ACTION_CONFIRM")) {
|
| 38 |
+
const appUrl = process.env.APP_URL || 'https://phanquocdat123-chatbot-robot-automation.hf.space';
|
| 39 |
return {
|
| 40 |
attachment: {
|
| 41 |
type: "template",
|
|
|
|
| 107 |
if (imageUrls.length >= 2) {
|
| 108 |
console.log(`📚 [FB Service] Đang cấu trúc lại Album Carousel cho ${imageUrls.length} sản phẩm...`);
|
| 109 |
|
|
|
|
| 110 |
const blocks = responseText.split(/(?=🔹|\*\*Mã:)/i).filter(b => b.includes('http'));
|
| 111 |
const elements = [];
|
| 112 |
|
|
|
|
| 113 |
for (let i = 0; i < imageUrls.length; i++) {
|
| 114 |
const currentUrl = imageUrls[i];
|
| 115 |
const currentBlock = blocks[i] || "";
|
| 116 |
|
|
|
|
| 117 |
const codeMatch = currentBlock.match(/\*\*Mã:\s*([^*]+)\*\*/i) || currentBlock.match(/Mã:\s*([^\n[-]+)/i);
|
| 118 |
const itemCode = codeMatch ? codeMatch[1].trim() : `Mẫu ${i + 1}`;
|
| 119 |
|
|
|
|
| 120 |
const nameMatch = currentBlock.match(/(?:👕|👚|👕|🌱|👉|^)\s*([^\n$*|]+)/m);
|
| 121 |
let itemName = nameMatch ? nameMatch[1].trim() : "Quần áo trẻ em";
|
| 122 |
if (itemName.toLowerCase().includes("giá")) itemName = "Thời trang bé trai";
|
| 123 |
|
|
|
|
| 124 |
const priceMatch = currentBlock.match(/Giá:\s*\*?([^*|\n]+)\*?/i);
|
| 125 |
const itemPrice = priceMatch ? priceMatch[1].trim() : "Liên hệ shop";
|
| 126 |
|
|
|
|
| 127 |
const rawButtonRegex = /(\[[^\]]+\])/g;
|
| 128 |
const rawButtons = currentBlock.match(rawButtonRegex) || [];
|
| 129 |
|
| 130 |
const buttons = [];
|
| 131 |
+
let finalPayload = `[ACTION_ADD:${itemCode}]`;
|
| 132 |
|
| 133 |
if (rawButtons.length > 0) {
|
|
|
|
| 134 |
const rawText = rawButtons[0].trim();
|
| 135 |
+
const innerContent = rawText.slice(1, -1);
|
|
|
|
|
|
|
| 136 |
if (innerContent.includes('|')) {
|
| 137 |
finalPayload = innerContent.split('|')[1].trim();
|
| 138 |
} else {
|
| 139 |
+
finalPayload = rawText;
|
| 140 |
}
|
| 141 |
}
|
| 142 |
|
|
|
|
| 143 |
buttons.push({
|
| 144 |
type: "postback",
|
| 145 |
+
title: `🛍️ CHỌN MẪU ${itemCode}`,
|
| 146 |
+
payload: finalPayload
|
| 147 |
});
|
| 148 |
|
| 149 |
if (elements.length < 10) {
|
|
|
|
| 158 |
|
| 159 |
// Gửi cấu trúc Album hoàn chỉnh
|
| 160 |
if (elements.length > 0) {
|
| 161 |
+
// 🎯 TRUYỀN HTTPS AGENT VÀO ĐỂ TRÁNH LỖI EPROTO VỚI META
|
| 162 |
await axios.post(`https://graph.facebook.com/v19.0/me/messages?access_token=${accessToken}`, {
|
| 163 |
recipient: { id: senderPsid },
|
| 164 |
message: {
|
|
|
|
| 170 |
}
|
| 171 |
}
|
| 172 |
}
|
| 173 |
+
}, { httpsAgent: sslAgent });
|
| 174 |
}
|
| 175 |
|
|
|
|
| 176 |
const lines = responseText.split('\n');
|
| 177 |
const bottomTextLines = lines.filter(line =>
|
| 178 |
!line.includes('http') &&
|
|
|
|
| 186 |
|
| 187 |
if (bottomText) {
|
| 188 |
const formattedBottom = formatMessage(bottomText, senderPsid);
|
| 189 |
+
// 🎯 TRUYỀN HTTPS AGENT VÀO ĐỂ TRÁNH LỖI EPROTO VỚI META
|
| 190 |
await axios.post(`https://graph.facebook.com/v19.0/me/messages?access_token=${accessToken}`, {
|
| 191 |
recipient: { id: senderPsid },
|
| 192 |
message: formattedBottom
|
| 193 |
+
}, { httpsAgent: sslAgent });
|
| 194 |
}
|
| 195 |
return;
|
| 196 |
}
|
|
|
|
| 201 |
if (imageUrls.length === 1) {
|
| 202 |
console.log(`📸 [FB Service] Gửi 1 ảnh sản phẩm lẻ: ${imageUrls[0]}`);
|
| 203 |
try {
|
| 204 |
+
// 🎯 TRUYỀN HTTPS AGENT VÀO ĐỂ TRÁNH LỖI EPROTO VỚI META
|
| 205 |
await axios.post(`https://graph.facebook.com/v19.0/me/messages?access_token=${accessToken}`, {
|
| 206 |
recipient: { id: senderPsid },
|
| 207 |
message: {
|
|
|
|
| 210 |
payload: { url: imageUrls[0], is_reusable: true }
|
| 211 |
}
|
| 212 |
}
|
| 213 |
+
}, { httpsAgent: sslAgent });
|
| 214 |
} catch (imgErr) {
|
| 215 |
console.error("⚠️ Lỗi gửi ảnh đơn:", imgErr.message);
|
| 216 |
}
|
| 217 |
}
|
| 218 |
|
| 219 |
if (formatted && (formatted.text || formatted.attachment)) {
|
| 220 |
+
// 🎯 TRUYỀN HTTPS AGENT VÀO ĐỂ TRÁNH LỖI EPROTO VỚI META
|
| 221 |
await axios.post(`https://graph.facebook.com/v19.0/me/messages?access_token=${accessToken}`, {
|
| 222 |
recipient: { id: senderPsid },
|
| 223 |
message: formatted
|
| 224 |
+
}, { httpsAgent: sslAgent });
|
| 225 |
}
|
| 226 |
|
| 227 |
console.log(`✅ [FB Service] Đã xử lý tin nhắn sạch cho khách: ${senderPsid}`);
|