Chatbot_Robot_Automation / services /facebookService.js
phanquocdat123's picture
Update services/facebookService.js
fbb64e4 verified
Raw History Blame Contribute Delete
12.3 kB
// C:\Users\Hi\OneDrive\Desktop\TCCS\Chatbot\chatbot_server\services\facebookService.js
const axios = require('axios');
const https = require('https');
// 🎯 CHIẾN THUẬT CHỐNG TIMEOUT: Khởi tạo tác nhân HTTPS giữ kết nối sống (Keep-Alive)
// Giúp tái sử dụng socket cũ, đẩy tốc độ truyền tải Album ảnh lên gấp 3 lần và tránh nghẽn mạch.
const httpsAgent = new https.Agent({
rejectUnauthorized: false,
keepAlive: true,
keepAliveMsecs: 30000, // Giữ socket mở trong 30 giây để phục vụ lượt chat tiếp theo
secureOptions: require('crypto').constants.SSL_OP_LEGACY_SERVER_CONNECT
});
// 🎯 RELAY QUA CLOUDFLARE WORKER ĐỂ TRÁNH BỊ HUGGING FACE BLOCK
const CF_RELAY_URL = process.env.CF_RELAY_URL;
const CF_RELAY_SECRET = process.env.CF_RELAY_SECRET;
/**
* Hàm làm sạch văn bản: Xóa HTML rác và các tag lệnh ẩn
*/
function cleanTextContent(text) {
return (text || "")
.replace(/<[^>]*>/g, "")
.replace(/\[\[.*?\]\]/g, "")
.trim();
}
/**
* Hàm lọc và trích xuất TOÀN BỘ link ảnh có trong tin nhắn
*/
function extractAllImageUrls(text) {
if (!text) return [];
const urlRegex = /https?:\/\/[^\s"<>]+(?:\.jpg|\.jpeg|\.png|\.gif|\.webp|thumbnail\?[^\s"<>]+)/gi;
const matches = text.match(urlRegex);
return matches ? [...new Set(matches)] : [];
}
/**
* Hàm phân tích tin nhắn để dựng cấu trúc Facebook (Quick Replies / Webview)
*/
function formatMessage(text, psid) {
const cleanText = cleanTextContent(text);
// 1. XỬ LÝ FORM CHỐT ĐƠN WEBVIEW
if (text.includes("[[SHOW_ORDER_FORM") || text.toUpperCase().includes("ACTION_CONFIRM")) {
const appUrl = process.env.APP_URL || 'https://phanquocdat123-chatbot-robot-automation.hf.space';
return {
attachment: {
type: "template",
payload: {
template_type: "button",
text: cleanText || "Dạ Mẹ nhấn vào nút bên dưới để điền thông tin cho bé nhen! ❤️",
buttons: [{
type: "web_url",
url: `${appUrl}/order-form.html?userId=${psid}`,
title: "📝 ĐIỀN THÔNG TIN",
webview_height_ratio: "full",
messenger_extensions: false
}]
}
}
};
}
// 2. TỰ ĐỘNG BẮT SĐT
if (cleanText.toLowerCase().includes("sđt") || cleanText.toLowerCase().includes("số điện thoại")) {
return {
text: cleanText,
quick_replies: [{ content_type: "user_phone_number" }]
};
}
// 3. XỬ LÝ NÚT BẤM [Nhãn|Lệnh] DẠNG QUICK REPLIES
const buttonRegex = /\[([^\]|]+)\|?([^\]]*)\]/g;
const matches = [...text.matchAll(buttonRegex)];
if (matches.length > 0) {
const isAskingAddress = cleanText.toLowerCase().includes("địa chỉ");
const quickReplies = matches.map(match => {
const label = match[1].trim();
const command = match[2] ? match[2].trim() : label;
return {
content_type: "text",
title: label.substring(0, 20),
payload: command
};
});
if (isAskingAddress) {
quickReplies.unshift({
content_type: "text",
title: "Mẫu: Tên - SĐT - ĐC",
payload: "TEMPLATE_ADDRESS"
});
}
return {
text: cleanText || "Mẹ chọn ở dưới nhen:",
quick_replies: quickReplies.slice(0, 13)
};
}
return { text: cleanText };
}
/**
* Hàm phụ trợ: Gọi trực tiếp đến Meta không qua trung gian khi gặp sự cố cứu hộ
*/
async function sendDirectlyToFacebook(fbUrl, payload, timeoutMs) {
try {
console.log("💻 [FB API] Đang gọi trực tiếp API Facebook Graph (Luồng cứu hộ)...");
const response = await axios.post(fbUrl, payload, {
headers: { 'Content-Type': 'application/json' },
httpsAgent: httpsAgent,
timeout: timeoutMs
});
if (response.data && response.data.error) {
console.error("❌ [FB API - Direct] Facebook báo lỗi:", JSON.stringify(response.data.error));
} else {
console.log("✅ [FB API - Direct] Luồng cứu hộ gọi trực tiếp thành công!");
}
return response.data;
} catch (directErr) {
console.error("❌ [FB API] Luồng cứu hộ gọi trực tiếp cũng thất bại:", directErr.message);
throw directErr;
}
}
/**
* Gửi tới Facebook API — tích hợp cơ chế tự động Fallback gọi trực tiếp nếu Relay lỗi/Timeout
*/
/**
* Gửi tới Facebook API — Phân tách luồng độc lập, bảo vệ hệ thống khỏi nghẽn mạch
*/
async function sendToFacebook(fbUrl, payload, customTimeout = 10000) {
// Mặc định cho luồng chính là 10 giây để an toàn cho cả Album nặng
if (CF_RELAY_URL && CF_RELAY_SECRET) {
try {
// 🌐 LUỒNG CHÍNH: CHỈ GỌI QUA CLOUDFLARE WORKER
const response = await axios.post(CF_RELAY_URL, { fbUrl, payload }, {
headers: {
'Content-Type': 'application/json',
'X-Relay-Secret': CF_RELAY_SECRET
},
httpsAgent: httpsAgent,
timeout: customTimeout // Giữ thời gian đợi theo yêu cầu của từng loại tin nhắn
});
if (response.data && response.data.error) {
console.error("❌ [FB API - Worker] Facebook báo lỗi:", JSON.stringify(response.data.error));
}
return response.data;
} catch (err) {
console.warn(`⚠️ [FB API - Worker] Gặp sự cố (${err.message}). KÍCH HOẠT LUỒNG CỨU HỘ GỌI TRỰC TIẾP...`);
// 🚑 ĐƯỜNG LÙI CỨU HỘ: Chỉ chạy khi luồng Worker ở trên thất bại hoàn toàn
// Nới rộng hẳn thời gian chờ lên 20 giây để Meta kịp phản hồi dữ liệu cấu trúc
return await sendDirectlyToFacebook(fbUrl, payload, 20000);
}
} else {
// Nếu môi trường Local không cài Worker -> Đi thẳng trực tiếp ngay từ đầu
return await sendDirectlyToFacebook(fbUrl, payload, customTimeout);
}
}
/**
* Hàm chính thực hiện gửi tin nhắn thông minh
*/
async function sendResponse(senderPsid, responseText) {
try {
const accessToken = process.env.FB_PAGE_ACCESS_TOKEN;
const imageUrls = extractAllImageUrls(responseText);
const fbUrl = `https://graph.facebook.com/v19.0/me/messages?access_token=${accessToken}`;
// --- TRƯỜNG HỢP NHIỀU SẢN PHẨM (Dựng Album Carousel) ---
if (imageUrls.length >= 2) {
console.log(`📚 [FB Service] Đang cấu trúc Album Carousel cho ${imageUrls.length} sản phẩm...`);
const blocks = responseText.split(/https?:\/\/[^\s"<>]+/gi);
const elements = [];
for (let i = 0; i < imageUrls.length; i++) {
const currentUrl = imageUrls[i];
const currentBlock = blocks[i] || "";
const codeMatch =
currentBlock.match(/\*\*Mã:\s*([^*\[\n]+)\*\*/i) ||
currentBlock.match(/Mã\s*(?:sản phẩm)?:\s*([^\n\[|:-]+)/i) ||
currentBlock.match(/(?:🔹|👉|#)\s*Mã\s*:\s*([A-Z0-9]+)/i) ||
currentBlock.match(/\b([A-Z]+[0-9]+)\b/);
let itemCode = "MẪU";
if (codeMatch) {
itemCode = (codeMatch[1] || codeMatch[0]).trim().toUpperCase();
} else {
const backupMatch = currentBlock.match(/([A-Z]+[0-9]+)/i);
if (backupMatch) itemCode = backupMatch[1].toUpperCase();
}
const nameMatch = currentBlock.match(/(?:👕|👚|🌱|👉|^)\s*([^\n$*|]+)/m);
let itemName = nameMatch ? nameMatch[1].trim() : "Thời trang cho bé";
if (itemName.toLowerCase().includes("giá") || itemName.length < 3) {
itemName = "Quần áo trẻ em xịn";
}
const priceMatch =
currentBlock.match(/Giá:\s*\*?([^*|\n]+)\*?/i) ||
currentBlock.match(/(\d{1,3}(?:\.\d{3})*\s*(?:k|đ|đồng|vnd))/i);
const itemPrice = priceMatch ? priceMatch[1].trim() : "Liên hệ shop";
if (elements.length < 10) {
elements.push({
title: `Mã: ${itemCode} - ${itemName}`.substring(0, 80),
image_url: currentUrl,
subtitle: `💰 Giá: ${itemPrice}\nMẹ bấm nút bên dưới để chọn nhen!`.substring(0, 80),
buttons: [{
type: "postback",
title: `🛍️ CHỌN MẪU ${itemCode}`,
payload: `[ACTION_ADD:${itemCode}]`
}]
});
}
}
if (elements.length > 0) {
console.log("📤 [FB Service] Đang bắn Album Carousel sang Meta...");
// Nới timeout lên 20 giây cho gói Album nặng hình ảnh
await sendToFacebook(fbUrl, {
recipient: { id: senderPsid },
message: {
attachment: {
type: "template",
payload: { template_type: "generic", elements }
}
}
}, 20000);
}
// Gửi text hướng dẫn ở cuối Album
const lines = responseText.split('\n');
const bottomText = cleanTextContent(
lines.filter(line =>
!line.includes('http') &&
!line.toLowerCase().includes('mã:') &&
!line.toLowerCase().includes('giá:') &&
!line.toLowerCase().includes('action_add')
).join('\n').trim()
);
if (bottomText) {
await sendToFacebook(fbUrl, {
recipient: { id: senderPsid },
message: formatMessage(bottomText, senderPsid)
}, 6000);
}
console.log(`✅ [FB Service] Đã gửi xong Album Carousel cho khách: ${senderPsid}`);
return;
}
// --- TRƯỜNG HỢP THÔNG THƯỜNG (1 ẢNH HOẶC KHÔNG CÓ ẢNH) ---
const formatted = formatMessage(responseText, senderPsid);
// Gửi 1 ảnh lẻ
if (imageUrls.length === 1) {
console.log(`📸 [FB Service] Gửi 1 ảnh sản phẩm lẻ: ${imageUrls[0]}`);
try {
await sendToFacebook(fbUrl, {
recipient: { id: senderPsid },
message: {
attachment: {
type: "image",
payload: { url: imageUrls[0], is_reusable: true }
}
}
}, 8000);
} catch (imgErr) {
console.error("⚠️ Lỗi gửi ảnh đơn:", imgErr.message);
}
}
// Gửi tin nhắn text thông thường
if (formatted && (formatted.text || formatted.attachment)) {
await sendToFacebook(fbUrl, {
recipient: { id: senderPsid },
message: formatted
}, 6000);
}
console.log(`✅ [FB Service] Đã xử lý tin nhắn cho khách: ${senderPsid}`);
} catch (err) {
console.error("❌ [FB Service] Lỗi nghiêm trọng tại sendResponse:", err.message);
}
}
module.exports = { sendResponse };