UNPKG

@warriorteam/redai-zalo-sdk

Version:

Comprehensive TypeScript/JavaScript SDK for Zalo APIs - Official Account v3.0, ZNS with Full Type Safety, Consultation Service, Broadcast Service, Group Messaging with List APIs, Social APIs, Enhanced Article Management, Promotion Service v3.0 with Multip

465 lines (399 loc) 12.6 kB
# API Gửi Chuỗi Tin Nhắn Tư Vấn API này cho phép gửi một chuỗi tin nhắn tư vấn tới một người dùng với khả năng delay tùy chỉnh giữa các tin nhắn. ## Tính năng - ✅ Hỗ trợ tất cả các loại tin nhắn: `text`, `image`, `gif`, `file`, `sticker`, `request_user_info` - ✅ Delay tùy chỉnh cho từng tin nhắn - ✅ Delay mặc định cho toàn bộ chuỗi tin nhắn - ✅ Xử lý lỗi chi tiết cho từng tin nhắn - ✅ Thống kê kết quả gửi tin nhắn - ✅ Ghi log thời gian thực hiện ## Cách sử dụng ### 1. Import các interface và service ```typescript import { ConsultationService, MessageItem, SendMessageSequenceRequest } from "../src/services/consultation.service"; import { ZaloClient } from "../src/clients/zalo-client"; ``` ### 2. Khởi tạo service ```typescript const zaloClient = new ZaloClient(); const consultationService = new ConsultationService(zaloClient); ``` ### 3. Định nghĩa chuỗi tin nhắn ```typescript const messages: MessageItem[] = [ { type: "text", text: "Xin chào! 👋", delay: 2000, // Delay 2 giây sau tin nhắn này }, { type: "image", imageUrl: "https://example.com/image.jpg", text: "Hình ảnh minh họa", delay: 1500, }, { type: "sticker", stickerAttachmentId: "STICKER_ID", }, ]; ``` ### 4. Gửi chuỗi tin nhắn ```typescript const request: SendMessageSequenceRequest = { accessToken: "YOUR_ACCESS_TOKEN", userId: "USER_ID", messages, defaultDelay: 1000, // Delay mặc định 1 giây }; try { const result = await consultationService.sendMessageSequence(request); console.log(`Thành công: ${result.successCount}/${messages.length}`); } catch (error) { console.error("Lỗi:", error); } ``` ## Các loại tin nhắn được hỗ trợ ### 1. Text Message ```typescript { type: "text", text: "Nội dung tin nhắn", delay: 1000, // Optional } ``` ### 2. Image Message ```typescript // Sử dụng URL { type: "image", imageUrl: "https://example.com/image.jpg", text: "Caption cho ảnh", // Optional delay: 1500, } // Hoặc sử dụng attachment ID { type: "image", attachmentId: "ATTACHMENT_ID", text: "Caption cho ảnh", // Optional delay: 1500, } ``` ### 3. GIF Message ```typescript { type: "gif", gifUrl: "https://example.com/animation.gif", width: 300, // Bắt buộc height: 200, // Bắt buộc text: "Caption cho GIF", // Optional delay: 2000, } ``` ### 4. File Message ```typescript { type: "file", fileToken: "FILE_TOKEN_FROM_UPLOAD_API", // Bắt buộc delay: 1000, } ``` ### 5. Sticker Message ```typescript { type: "sticker", stickerAttachmentId: "STICKER_ID", // Bắt buộc delay: 500, } ``` ### 6. Request User Info Message ```typescript { type: "request_user_info", title: "Đăng ký tư vấn", // Bắt buộc, max 100 ký tự subtitle: "Vui lòng cung cấp...", // Bắt buộc, max 500 ký tự imageUrl: "https://example.com/form.jpg", // Bắt buộc delay: 2000, } ``` ## Interface chi tiết ### MessageItem ```typescript interface MessageItem { type: "text" | "image" | "gif" | "file" | "sticker" | "request_user_info"; text?: string; imageUrl?: string; gifUrl?: string; width?: number; height?: number; fileToken?: string; attachmentId?: string; stickerAttachmentId?: string; title?: string; subtitle?: string; delay?: number; // milliseconds } ``` ### SendMessageSequenceRequest ```typescript interface SendMessageSequenceRequest { accessToken: string; userId: string; messages: MessageItem[]; defaultDelay?: number; // milliseconds } ``` ### SendMessageSequenceResponse ```typescript interface SendMessageSequenceResponse { successCount: number; failureCount: number; results: Array<{ index: number; type: string; success: boolean; response?: SendMessageResponse; error?: string; timestamp: number; }>; totalDuration: number; // milliseconds } ``` ## Ví dụ thực tế ### Chuỗi tin nhắn chào mừng khách hàng mới ```typescript const welcomeMessages: MessageItem[] = [ { type: "text", text: "🎉 Chào mừng bạn đến với dịch vụ của chúng tôi!", delay: 2000, }, { type: "sticker", stickerAttachmentId: "WELCOME_STICKER_ID", delay: 1500, }, { type: "image", imageUrl: "https://company.com/welcome-banner.jpg", text: "Khám phá các dịch vụ tuyệt vời", delay: 3000, }, { type: "text", text: "Chúng tôi sẽ hỗ trợ bạn 24/7. Hãy cho chúng tôi biết nếu bạn cần giúp đỡ! 💪", }, ]; ``` ### Chuỗi tin nhắn hỗ trợ kỹ thuật ```typescript const supportMessages: MessageItem[] = [ { type: "text", text: "Chúng tôi đã nhận được yêu cầu hỗ trợ của bạn 🔧", delay: 1000, }, { type: "file", fileToken: "TROUBLESHOOTING_GUIDE_TOKEN", delay: 2000, }, { type: "text", text: "Vui lòng tham khảo hướng dẫn trên. Nếu vẫn gặp vấn đề, hãy liên hệ trực tiếp:", delay: 1500, }, { type: "request_user_info", title: "Thông tin liên hệ", subtitle: "Để chúng tôi hỗ trợ bạn nhanh nhất", imageUrl: "https://company.com/support-form.jpg", }, ]; ``` ## Lưu ý quan trọng 1. **Delay**: Tính bằng milliseconds. Delay chỉ áp dụng giữa các tin nhắn, không có delay sau tin nhắn cuối cùng. 2. **Error Handling**: API sẽ tiếp tục gửi các tin nhắn tiếp theo ngay cả khi một tin nhắn thất bại. 3. **Rate Limiting**: Cần tuân thủ giới hạn tần suất gửi tin nhắn của Zalo để tránh bị chặn. 4. **Validation**: Mỗi loại tin nhắn có các trường bắt buộc riêng, cần đảm bảo cung cấp đầy đủ thông tin. 5. **File Upload**: Đối với file message, cần upload file trước và lấy token từ API upload của Zalo. --- # API Gửi Chuỗi Tin Nhắn Tới Nhiều Users API mở rộng cho phép gửi chuỗi tin nhắn tư vấn tới nhiều users cùng lúc với callback tracking real-time. ## Tính năng mới - ✅ Gửi chuỗi tin nhắn tới nhiều users - ✅ Callback tracking real-time cho từng user - ✅ Thống kê chi tiết (thành công/thất bại) - ✅ Delay tùy chỉnh giữa các users - ✅ Loại bỏ user IDs trùng lặp tự động - ✅ Error handling riêng biệt cho từng user ## Cách sử dụng ### 1. Import interface mới ```typescript import { SendMessageSequenceToMultipleUsersRequest, UserProgressInfo } from "../src/services/consultation.service"; ``` ### 2. Định nghĩa callback tracking ```typescript const onProgress = (progress: UserProgressInfo) => { switch (progress.status) { case 'started': console.log(`🚀 Bắt đầu gửi cho User ${progress.userIndex + 1}/${progress.totalUsers}`); break; case 'completed': console.log(`✅ Hoàn thành User ${progress.userIndex + 1} - Thành công: ${progress.result?.successCount}`); break; case 'failed': console.log(`❌ Thất bại User ${progress.userIndex + 1} - Lỗi: ${progress.error}`); break; } }; ``` ### 3. Gửi tới nhiều users ```typescript const request: SendMessageSequenceToMultipleUsersRequest = { accessToken: "YOUR_ACCESS_TOKEN", userIds: ["USER_1", "USER_2", "USER_3"], messages: [ { type: "text", text: "Tin nhắn 1", delay: 1000 }, { type: "text", text: "Tin nhắn 2" }, ], delayBetweenUsers: 2000, // Delay 2s giữa các user onProgress, // Callback tracking }; const result = await consultationService.sendMessageSequenceToMultipleUsers(request); ``` ## Interface chi tiết ### SendMessageSequenceToMultipleUsersRequest ```typescript interface SendMessageSequenceToMultipleUsersRequest { accessToken: string; userIds: string[]; // Danh sách user IDs messages: MessageItem[]; // Chuỗi tin nhắn defaultDelay?: number; // Delay giữa tin nhắn (ms) delayBetweenUsers?: number; // Delay giữa users (ms) onProgress?: (progress: UserProgressInfo) => void; // Callback tracking } ``` ### UserProgressInfo ```typescript interface UserProgressInfo { userId: string; // User ID hiện tại userIndex: number; // Index của user (0-based) totalUsers: number; // Tổng số users status: 'started' | 'completed' | 'failed'; // Trạng thái result?: SendMessageSequenceResponse; // Kết quả (nếu completed) error?: string; // Lỗi (nếu failed) startTime: number; // Thời gian bắt đầu endTime?: number; // Thời gian kết thúc } ``` ### SendMessageSequenceToMultipleUsersResponse ```typescript interface SendMessageSequenceToMultipleUsersResponse { totalUsers: number; // Tổng số users successfulUsers: number; // Số users thành công failedUsers: number; // Số users thất bại userResults: Array<{ // Chi tiết từng user userId: string; userIndex: number; success: boolean; messageSequenceResult?: SendMessageSequenceResponse; error?: string; startTime: number; endTime: number; duration: number; }>; totalDuration: number; // Tổng thời gian (ms) messageStats: { // Thống kê tin nhắn totalSuccessfulMessages: number; totalFailedMessages: number; totalMessages: number; }; } ``` ## Ví dụ thực tế ### Marketing Campaign ```typescript const marketingMessages: MessageItem[] = [ { type: "text", text: "🎉 Flash Sale 24h - Giảm 50% tất cả sản phẩm!", delay: 2000, }, { type: "image", imageUrl: "https://shop.com/flash-sale-banner.jpg", text: "Khuyến mãi khủng - Số lượng có hạn", delay: 3000, }, { type: "text", text: "⏰ Chỉ còn 12 giờ! Mua ngay: https://shop.com/sale", }, ]; const customerIds = ["CUSTOMER_1", "CUSTOMER_2", "CUSTOMER_3"]; let sentCount = 0; const onProgress = (progress: UserProgressInfo) => { if (progress.status === 'completed') { sentCount++; console.log(`📤 Đã gửi cho ${sentCount}/${progress.totalUsers} khách hàng`); } }; const result = await consultationService.sendMessageSequenceToMultipleUsers({ accessToken: "TOKEN", userIds: customerIds, messages: marketingMessages, delayBetweenUsers: 1500, // Tránh spam onProgress, }); console.log(`🎯 Campaign hoàn thành: ${result.successfulUsers}/${result.totalUsers} khách hàng`); ``` ### Customer Support Notification ```typescript const supportMessages: MessageItem[] = [ { type: "text", text: "🔧 Hệ thống sẽ bảo trì từ 2:00-4:00 sáng mai", delay: 1000, }, { type: "text", text: "📞 Hotline hỗ trợ 24/7: 1900-xxxx", }, ]; const allCustomers = ["USER_1", "USER_2", "USER_3", "USER_4"]; const result = await consultationService.sendMessageSequenceToMultipleUsers({ accessToken: "TOKEN", userIds: allCustomers, messages: supportMessages, delayBetweenUsers: 500, onProgress: (progress) => { if (progress.status === 'failed') { console.log(`❌ Không gửi được cho ${progress.userId}: ${progress.error}`); } }, }); console.log(`📢 Thông báo đã gửi tới ${result.successfulUsers} khách hàng`); ``` ## So sánh API cũ vs mới | Tính năng | API đơn user | API nhiều users | |-----------|-------------|-----------------| | Số lượng users | 1 user | Nhiều users | | Callback tracking | ❌ | ✅ Real-time | | Thống kê tổng quan | ❌ | ✅ Chi tiết | | Delay giữa users | ❌ | ✅ Tùy chỉnh | | Error handling | Dừng khi lỗi | Tiếp tục với user khác | | Use case | Tư vấn 1-1 | Marketing, thông báo | ## Lưu ý quan trọng 1. **Rate Limiting**: Sử dụng `delayBetweenUsers` để tránh hit rate limit của Zalo 2. **Memory Usage**: Với số lượng users lớn, cân nhắc chia batch 3. **Callback Performance**: Callback không nên thực hiện operations nặng 4. **Error Isolation**: Lỗi của 1 user không ảnh hưởng đến users khác 5. **Duplicate Handling**: API tự động loại bỏ user IDs trùng lặp