Initial commit

This commit is contained in:
Victor Phan
2026-07-17 20:29:31 +07:00
commit caa9717571
4 changed files with 300 additions and 0 deletions
+65
View File
@@ -0,0 +1,65 @@
class BotController {
constructor(zaloClient) {
// zaloClient là instance của thư viện zalo (ví dụ: zca-js) đã đăng nhập thành công
this.zalo = zaloClient;
}
/**
* API Endpoint: Nhận yêu cầu từ n8n và gửi tin nhắn vào Group Zalo
*/
async sendMessage(req, res) {
try {
const { groupId, message, mentions } = req.body;
if (!groupId || !message) {
return res.status(400).json({
success: false,
error: "Vui lòng cung cấp đủ groupId và message"
});
}
// Xử lý Mentions để bôi xanh tên người dùng (Zalo API yêu cầu vị trí và độ dài)
let formattedMentions = [];
if (mentions && Array.isArray(mentions)) {
mentions.forEach(mention => {
// Nếu n8n gửi lên biến name (VD: "@Hiển Phan")
if (mention.name) {
// Tìm vị trí chữ "@Hiển Phan" trong câu chat
const pos = message.indexOf(mention.name);
if (pos !== -1) {
formattedMentions.push({
uid: mention.id, // ID người dùng
pos: pos, // Vị trí bắt đầu
len: mention.name.length // Số ký tự cần bôi xanh
});
}
} else {
// Nếu không có tên, đành truyền ID chay
formattedMentions.push({ uid: mention.id, pos: 0, len: 0 });
}
});
}
// Thực hiện gửi tin nhắn qua thư viện Zalo
// Cú pháp của zca-js: sendMessage(groupId, message, quote, mentions)
const result = await this.zalo.sendMessage(groupId, message, null, formattedMentions);
console.log(`[Zalo Bot] Đã gửi tin nhắn vào group ${groupId} thành công!`);
return res.json({
success: true,
message: "Đã gửi tin nhắn",
mentions_processed: formattedMentions,
data: result
});
} catch (error) {
console.error("[Zalo Bot] Lỗi khi gửi tin nhắn:", error);
return res.status(500).json({ success: false, error: error.message });
}
}
}
module.exports = BotController;