Update services/facebookService.js
Browse files- services/facebookService.js +79 -84
services/facebookService.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
| 1 |
// C:\Users\Hi\OneDrive\Desktop\TCCS\Chatbot\chatbot_server\services\facebookService.js
|
| 2 |
const fetch = require('node-fetch');
|
| 3 |
-
const https = require('https');
|
| 4 |
|
| 5 |
// 🎯 TẠO AGENT KHÓA CHẾT CƠ CHẾ BỎ QUA SSL TRÊN HUGGING FACE
|
| 6 |
const agent = new https.Agent({
|
| 7 |
rejectUnauthorized: false,
|
| 8 |
-
secureOptions: require('crypto').constants.SSL_OP_LEGACY_SERVER_CONNECT
|
| 9 |
});
|
| 10 |
|
| 11 |
/**
|
|
@@ -13,19 +13,19 @@ const agent = new https.Agent({
|
|
| 13 |
*/
|
| 14 |
function cleanTextContent(text) {
|
| 15 |
return (text || "")
|
| 16 |
-
.replace(/<[^>]*>/g, "")
|
| 17 |
-
.replace(/\[\[.*?\]\]/g, "")
|
| 18 |
.trim();
|
| 19 |
}
|
| 20 |
|
| 21 |
/**
|
| 22 |
-
* Hàm lọc và trích xuất TOÀN BỘ link ảnh có trong tin nhắn
|
| 23 |
*/
|
| 24 |
function extractAllImageUrls(text) {
|
| 25 |
if (!text) return [];
|
| 26 |
-
const urlRegex = /https?:\/\/[^\s"<>]+
|
| 27 |
const matches = text.match(urlRegex);
|
| 28 |
-
return matches ? [...new Set(matches)] : [];
|
| 29 |
}
|
| 30 |
|
| 31 |
/**
|
|
@@ -45,14 +45,14 @@ function formatMessage(text, psid) {
|
|
| 45 |
text: cleanText || "Dạ Mẹ nhấn vào nút bên dưới để điền thông tin cho bé nhen! ❤️",
|
| 46 |
buttons: [{
|
| 47 |
type: "web_url",
|
| 48 |
-
url: `${appUrl}/order-form.html?userId=${psid}`,
|
| 49 |
title: "📝 ĐIỀN THÔNG TIN",
|
| 50 |
webview_height_ratio: "full",
|
| 51 |
-
messenger_extensions: false
|
| 52 |
}]
|
| 53 |
}
|
| 54 |
-
}
|
| 55 |
-
}
|
| 56 |
}
|
| 57 |
|
| 58 |
// 2. TỰ ĐỘNG BẮT SĐT
|
|
@@ -96,6 +96,23 @@ function formatMessage(text, psid) {
|
|
| 96 |
return { text: cleanText };
|
| 97 |
}
|
| 98 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 99 |
/**
|
| 100 |
* Hàm chính thực hiện gửi tin nhắn thông minh
|
| 101 |
*/
|
|
@@ -104,21 +121,21 @@ async function sendResponse(senderPsid, responseText) {
|
|
| 104 |
const accessToken = process.env.FB_PAGE_ACCESS_TOKEN;
|
| 105 |
const imageUrls = extractAllImageUrls(responseText);
|
| 106 |
const fbUrl = `https://graph.facebook.com/v19.0/me/messages?access_token=${accessToken}`;
|
| 107 |
-
|
| 108 |
// --- TRƯỜNG HỢP NHIỀU SẢN PHẨM (Dựng Album Carousel) ---
|
| 109 |
if (imageUrls.length >= 2) {
|
| 110 |
-
console.log(`📚 [FB Service] Đang cấu trúc
|
| 111 |
|
| 112 |
const blocks = responseText.split(/https?:\/\/[^\s"<>]+/gi);
|
| 113 |
const elements = [];
|
| 114 |
|
| 115 |
for (let i = 0; i < imageUrls.length; i++) {
|
| 116 |
const currentUrl = imageUrls[i];
|
| 117 |
-
const currentBlock = blocks[i] || "";
|
| 118 |
|
| 119 |
-
// Khớp mã sản phẩm thông minh
|
| 120 |
-
const codeMatch =
|
| 121 |
-
currentBlock.match(/\*\*Mã:\s*([^*\[\n]+)\*\*/i) ||
|
| 122 |
currentBlock.match(/Mã\s*(?:sản phẩm)?:\s*([^\n\[|-]+)/i) ||
|
| 123 |
currentBlock.match(/(?:🔹|👉|#|^)\s*([A-Z0-9]{2,5})\b/i) ||
|
| 124 |
currentBlock.match(/\b([A-Z]+[0-9]+)\b/);
|
|
@@ -127,119 +144,97 @@ async function sendResponse(senderPsid, responseText) {
|
|
| 127 |
|
| 128 |
const nameMatch = currentBlock.match(/(?:👕|👚|🌱|👉|^)\s*([^\n$*|]+)/m);
|
| 129 |
let itemName = nameMatch ? nameMatch[1].trim() : "Thời trang cho bé";
|
| 130 |
-
if (itemName.toLowerCase().includes("giá") || itemName.length < 3)
|
|
|
|
|
|
|
| 131 |
|
| 132 |
-
const priceMatch =
|
|
|
|
|
|
|
| 133 |
const itemPrice = priceMatch ? priceMatch[1].trim() : "Liên hệ shop";
|
| 134 |
|
| 135 |
-
const buttons = [];
|
| 136 |
-
const finalPayload = `[ACTION_ADD:${itemCode}]`; // Ăn theo mã bóc được thực tế
|
| 137 |
-
|
| 138 |
-
buttons.push({
|
| 139 |
-
type: "postback",
|
| 140 |
-
title: `🛍️ CHỌN MẪU ${itemCode}`,
|
| 141 |
-
payload: finalPayload
|
| 142 |
-
});
|
| 143 |
-
|
| 144 |
if (elements.length < 10) {
|
| 145 |
elements.push({
|
| 146 |
title: `Mã: ${itemCode} - ${itemName}`.substring(0, 80),
|
| 147 |
image_url: currentUrl,
|
| 148 |
subtitle: `💰 Giá: ${itemPrice}\nMẹ bấm nút bên dưới để chọn nhen!`.substring(0, 80),
|
| 149 |
-
buttons:
|
|
|
|
|
|
|
|
|
|
|
|
|
| 150 |
});
|
| 151 |
}
|
| 152 |
}
|
| 153 |
|
| 154 |
-
// Gửi
|
| 155 |
if (elements.length > 0) {
|
| 156 |
-
await
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
payload: {
|
| 165 |
-
template_type: "generic",
|
| 166 |
-
elements: elements
|
| 167 |
-
}
|
| 168 |
}
|
| 169 |
}
|
| 170 |
-
}
|
| 171 |
-
agent: agent // <--- 🎯 ÉP CHẠY QUA AGENT ĐỂ BẺ GÃY BỘ LỌC SSL
|
| 172 |
});
|
| 173 |
}
|
| 174 |
|
|
|
|
| 175 |
const lines = responseText.split('\n');
|
| 176 |
-
const bottomTextLines = lines.filter(line =>
|
| 177 |
-
!line.includes('http') &&
|
| 178 |
-
!line.toLowerCase().includes('mã:') &&
|
| 179 |
!line.toLowerCase().includes('giá:') &&
|
| 180 |
!line.toLowerCase().includes('action_add')
|
| 181 |
);
|
| 182 |
-
|
| 183 |
-
let bottomText = bottomTextLines.join('\n').trim();
|
| 184 |
-
bottomText = cleanTextContent(bottomText);
|
| 185 |
|
| 186 |
-
|
| 187 |
if (bottomText) {
|
| 188 |
const formattedBottom = formatMessage(bottomText, senderPsid);
|
| 189 |
-
await
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
body: JSON.stringify({
|
| 193 |
-
recipient: { id: senderPsid },
|
| 194 |
-
message: formattedBottom
|
| 195 |
-
}),
|
| 196 |
-
agent: agent // <--- 🎯 ÉP CHẠY QUA AGENT ĐỂ BẺ GÃY BỘ LỌC SSL
|
| 197 |
});
|
| 198 |
}
|
| 199 |
-
|
|
|
|
| 200 |
return;
|
| 201 |
}
|
| 202 |
|
| 203 |
// --- TRƯỜNG HỢP THÔNG THƯỜNG (1 ẢNH HOẶC KHÔNG CÓ ẢNH) ---
|
| 204 |
const formatted = formatMessage(responseText, senderPsid);
|
| 205 |
-
|
| 206 |
-
// Gửi 1 ảnh lẻ
|
| 207 |
if (imageUrls.length === 1) {
|
| 208 |
console.log(`📸 [FB Service] Gửi 1 ảnh sản phẩm lẻ: ${imageUrls[0]}`);
|
| 209 |
try {
|
| 210 |
-
await
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
attachment: {
|
| 217 |
-
type: "image",
|
| 218 |
-
payload: { url: imageUrls[0], is_reusable: true }
|
| 219 |
-
}
|
| 220 |
}
|
| 221 |
-
}
|
| 222 |
-
agent: agent // <--- 🎯 ÉP CHẠY QUA AGENT ĐỂ BẺ GÃY BỘ LỌC SSL
|
| 223 |
});
|
| 224 |
} catch (imgErr) {
|
| 225 |
console.error("⚠️ Lỗi gửi ảnh đơn:", imgErr.message);
|
| 226 |
}
|
| 227 |
}
|
| 228 |
|
| 229 |
-
// Gửi tin nhắn
|
| 230 |
if (formatted && (formatted.text || formatted.attachment)) {
|
| 231 |
-
await
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
body: JSON.stringify({
|
| 235 |
-
recipient: { id: senderPsid },
|
| 236 |
-
message: formatted
|
| 237 |
-
}),
|
| 238 |
-
agent: agent // <--- 🎯 ÉP CHẠY QUA AGENT ĐỂ BẺ GÃY BỘ LỌC SSL
|
| 239 |
});
|
| 240 |
}
|
| 241 |
|
| 242 |
-
console.log(`✅ [FB Service] Đã xử lý tin nhắn
|
| 243 |
} catch (err) {
|
| 244 |
console.error("❌ [FB Service] Lỗi nghiêm trọng:", err.message);
|
| 245 |
}
|
|
|
|
| 1 |
// C:\Users\Hi\OneDrive\Desktop\TCCS\Chatbot\chatbot_server\services\facebookService.js
|
| 2 |
const fetch = require('node-fetch');
|
| 3 |
+
const https = require('https');
|
| 4 |
|
| 5 |
// 🎯 TẠO AGENT KHÓA CHẾT CƠ CHẾ BỎ QUA SSL TRÊN HUGGING FACE
|
| 6 |
const agent = new https.Agent({
|
| 7 |
rejectUnauthorized: false,
|
| 8 |
+
secureOptions: require('crypto').constants.SSL_OP_LEGACY_SERVER_CONNECT
|
| 9 |
});
|
| 10 |
|
| 11 |
/**
|
|
|
|
| 13 |
*/
|
| 14 |
function cleanTextContent(text) {
|
| 15 |
return (text || "")
|
| 16 |
+
.replace(/<[^>]*>/g, "")
|
| 17 |
+
.replace(/\[\[.*?\]\]/g, "")
|
| 18 |
.trim();
|
| 19 |
}
|
| 20 |
|
| 21 |
/**
|
| 22 |
+
* Hàm lọc và trích xuất TOÀN BỘ link ảnh có trong tin nhắn
|
| 23 |
*/
|
| 24 |
function extractAllImageUrls(text) {
|
| 25 |
if (!text) return [];
|
| 26 |
+
const urlRegex = /https?:\/\/[^\s"<>]+(?:\.jpg|\.jpeg|\.png|\.gif|\.webp|thumbnail\?[^\s"<>]+)/gi;
|
| 27 |
const matches = text.match(urlRegex);
|
| 28 |
+
return matches ? [...new Set(matches)] : [];
|
| 29 |
}
|
| 30 |
|
| 31 |
/**
|
|
|
|
| 45 |
text: cleanText || "Dạ Mẹ nhấn vào nút bên dưới để điền thông tin cho bé nhen! ❤️",
|
| 46 |
buttons: [{
|
| 47 |
type: "web_url",
|
| 48 |
+
url: `${appUrl}/order-form.html?userId=${psid}`,
|
| 49 |
title: "📝 ĐIỀN THÔNG TIN",
|
| 50 |
webview_height_ratio: "full",
|
| 51 |
+
messenger_extensions: false
|
| 52 |
}]
|
| 53 |
}
|
| 54 |
+
}
|
| 55 |
+
};
|
| 56 |
}
|
| 57 |
|
| 58 |
// 2. TỰ ĐỘNG BẮT SĐT
|
|
|
|
| 96 |
return { text: cleanText };
|
| 97 |
}
|
| 98 |
|
| 99 |
+
/**
|
| 100 |
+
* Hàm gửi request đến Facebook API (dùng chung, tránh lặp code)
|
| 101 |
+
*/
|
| 102 |
+
async function sendToFacebook(fbUrl, body) {
|
| 103 |
+
const response = await fetch(fbUrl, {
|
| 104 |
+
method: 'POST',
|
| 105 |
+
headers: { 'Content-Type': 'application/json' },
|
| 106 |
+
body: JSON.stringify(body),
|
| 107 |
+
agent: agent
|
| 108 |
+
});
|
| 109 |
+
const result = await response.json();
|
| 110 |
+
if (result.error) {
|
| 111 |
+
console.error("❌ [FB API] Lỗi phản hồi từ Facebook:", JSON.stringify(result.error));
|
| 112 |
+
}
|
| 113 |
+
return result;
|
| 114 |
+
}
|
| 115 |
+
|
| 116 |
/**
|
| 117 |
* Hàm chính thực hiện gửi tin nhắn thông minh
|
| 118 |
*/
|
|
|
|
| 121 |
const accessToken = process.env.FB_PAGE_ACCESS_TOKEN;
|
| 122 |
const imageUrls = extractAllImageUrls(responseText);
|
| 123 |
const fbUrl = `https://graph.facebook.com/v19.0/me/messages?access_token=${accessToken}`;
|
| 124 |
+
|
| 125 |
// --- TRƯỜNG HỢP NHIỀU SẢN PHẨM (Dựng Album Carousel) ---
|
| 126 |
if (imageUrls.length >= 2) {
|
| 127 |
+
console.log(`📚 [FB Service] Đang cấu trúc Album Carousel cho ${imageUrls.length} sản phẩm...`);
|
| 128 |
|
| 129 |
const blocks = responseText.split(/https?:\/\/[^\s"<>]+/gi);
|
| 130 |
const elements = [];
|
| 131 |
|
| 132 |
for (let i = 0; i < imageUrls.length; i++) {
|
| 133 |
const currentUrl = imageUrls[i];
|
| 134 |
+
const currentBlock = blocks[i] || "";
|
| 135 |
|
| 136 |
+
// Khớp mã sản phẩm thông minh
|
| 137 |
+
const codeMatch =
|
| 138 |
+
currentBlock.match(/\*\*Mã:\s*([^*\[\n]+)\*\*/i) ||
|
| 139 |
currentBlock.match(/Mã\s*(?:sản phẩm)?:\s*([^\n\[|-]+)/i) ||
|
| 140 |
currentBlock.match(/(?:🔹|👉|#|^)\s*([A-Z0-9]{2,5})\b/i) ||
|
| 141 |
currentBlock.match(/\b([A-Z]+[0-9]+)\b/);
|
|
|
|
| 144 |
|
| 145 |
const nameMatch = currentBlock.match(/(?:👕|👚|🌱|👉|^)\s*([^\n$*|]+)/m);
|
| 146 |
let itemName = nameMatch ? nameMatch[1].trim() : "Thời trang cho bé";
|
| 147 |
+
if (itemName.toLowerCase().includes("giá") || itemName.length < 3) {
|
| 148 |
+
itemName = "Quần áo trẻ em xịn";
|
| 149 |
+
}
|
| 150 |
|
| 151 |
+
const priceMatch =
|
| 152 |
+
currentBlock.match(/Giá:\s*\*?([^*|\n]+)\*?/i) ||
|
| 153 |
+
currentBlock.match(/(\d{1,3}(?:\.\d{3})*\s*(?:k|đ|đồng|vnd))/i);
|
| 154 |
const itemPrice = priceMatch ? priceMatch[1].trim() : "Liên hệ shop";
|
| 155 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 156 |
if (elements.length < 10) {
|
| 157 |
elements.push({
|
| 158 |
title: `Mã: ${itemCode} - ${itemName}`.substring(0, 80),
|
| 159 |
image_url: currentUrl,
|
| 160 |
subtitle: `💰 Giá: ${itemPrice}\nMẹ bấm nút bên dưới để chọn nhen!`.substring(0, 80),
|
| 161 |
+
buttons: [{
|
| 162 |
+
type: "postback",
|
| 163 |
+
title: `🛍️ CHỌN MẪU ${itemCode}`,
|
| 164 |
+
payload: `[ACTION_ADD:${itemCode}]`
|
| 165 |
+
}]
|
| 166 |
});
|
| 167 |
}
|
| 168 |
}
|
| 169 |
|
| 170 |
+
// Gửi Carousel
|
| 171 |
if (elements.length > 0) {
|
| 172 |
+
await sendToFacebook(fbUrl, {
|
| 173 |
+
recipient: { id: senderPsid },
|
| 174 |
+
message: {
|
| 175 |
+
attachment: {
|
| 176 |
+
type: "template",
|
| 177 |
+
payload: {
|
| 178 |
+
template_type: "generic",
|
| 179 |
+
elements: elements
|
|
|
|
|
|
|
|
|
|
|
|
|
| 180 |
}
|
| 181 |
}
|
| 182 |
+
}
|
|
|
|
| 183 |
});
|
| 184 |
}
|
| 185 |
|
| 186 |
+
// Gửi text hướng dẫn ở cuối Carousel
|
| 187 |
const lines = responseText.split('\n');
|
| 188 |
+
const bottomTextLines = lines.filter(line =>
|
| 189 |
+
!line.includes('http') &&
|
| 190 |
+
!line.toLowerCase().includes('mã:') &&
|
| 191 |
!line.toLowerCase().includes('giá:') &&
|
| 192 |
!line.toLowerCase().includes('action_add')
|
| 193 |
);
|
|
|
|
|
|
|
|
|
|
| 194 |
|
| 195 |
+
const bottomText = cleanTextContent(bottomTextLines.join('\n').trim());
|
| 196 |
if (bottomText) {
|
| 197 |
const formattedBottom = formatMessage(bottomText, senderPsid);
|
| 198 |
+
await sendToFacebook(fbUrl, {
|
| 199 |
+
recipient: { id: senderPsid },
|
| 200 |
+
message: formattedBottom
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 201 |
});
|
| 202 |
}
|
| 203 |
+
|
| 204 |
+
console.log(`✅ [FB Service] Đã gửi xong Album Carousel cho khách: ${senderPsid}`);
|
| 205 |
return;
|
| 206 |
}
|
| 207 |
|
| 208 |
// --- TRƯỜNG HỢP THÔNG THƯỜNG (1 ẢNH HOẶC KHÔNG CÓ ẢNH) ---
|
| 209 |
const formatted = formatMessage(responseText, senderPsid);
|
| 210 |
+
|
| 211 |
+
// Gửi 1 ảnh lẻ
|
| 212 |
if (imageUrls.length === 1) {
|
| 213 |
console.log(`📸 [FB Service] Gửi 1 ảnh sản phẩm lẻ: ${imageUrls[0]}`);
|
| 214 |
try {
|
| 215 |
+
await sendToFacebook(fbUrl, {
|
| 216 |
+
recipient: { id: senderPsid },
|
| 217 |
+
message: {
|
| 218 |
+
attachment: {
|
| 219 |
+
type: "image",
|
| 220 |
+
payload: { url: imageUrls[0], is_reusable: true }
|
|
|
|
|
|
|
|
|
|
|
|
|
| 221 |
}
|
| 222 |
+
}
|
|
|
|
| 223 |
});
|
| 224 |
} catch (imgErr) {
|
| 225 |
console.error("⚠️ Lỗi gửi ảnh đơn:", imgErr.message);
|
| 226 |
}
|
| 227 |
}
|
| 228 |
|
| 229 |
+
// Gửi tin nhắn text thông thường
|
| 230 |
if (formatted && (formatted.text || formatted.attachment)) {
|
| 231 |
+
await sendToFacebook(fbUrl, {
|
| 232 |
+
recipient: { id: senderPsid },
|
| 233 |
+
message: formatted
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 234 |
});
|
| 235 |
}
|
| 236 |
|
| 237 |
+
console.log(`✅ [FB Service] Đã xử lý tin nhắn cho khách: ${senderPsid}`);
|
| 238 |
} catch (err) {
|
| 239 |
console.error("❌ [FB Service] Lỗi nghiêm trọng:", err.message);
|
| 240 |
}
|