@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
333 lines (292 loc) • 8.53 kB
Markdown
# API Gửi Danh Sách Tin Nhắn Group
API mở rộng cho phép gửi danh sách tin nhắn tới groups với callback tracking real-time.
## Tính năng
- ✅ Gửi danh sách tin nhắn tới 1 group
- ✅ Gửi danh sách tin nhắn tới nhiều groups cùng lúc
- ✅ Hỗ trợ đầy đủ 5 loại tin nhắn: text, image, file, sticker, mention
- ✅ Callback tracking real-time cho từng tin nhắn/group
- ✅ Delay tùy chỉnh giữa tin nhắn và giữa groups
- ✅ Thống kê chi tiết thành công/thất bại
- ✅ Error isolation - lỗi 1 tin nhắn/group không ảnh hưởng phần còn lại
## Cách sử dụng
### 1. Import các interface và service
```typescript
import {
GroupMessageService,
GroupMessageItem,
SendMessageListToGroupRequest,
SendMessageListToMultipleGroupsRequest
} from "../src/services/group-message.service";
import { ZaloClient } from "../src/clients/zalo-client";
```
### 2. Khởi tạo service
```typescript
const zaloClient = new ZaloClient();
const groupMessageService = new GroupMessageService(zaloClient);
```
### 3. Định nghĩa danh sách tin nhắn
```typescript
const messages: GroupMessageItem[] = [
{
type: "text",
text: "📢 Thông báo quan trọng!",
delay: 2000, // Delay 2 giây sau tin nhắn này
},
{
type: "image",
imageUrl: "https://example.com/image.jpg",
caption: "Hình ảnh minh họa",
delay: 1500,
},
{
type: "mention",
text: "@Admin Vui lòng xem thông báo",
mentions: [
{ user_id: "ADMIN_ID", offset: 0, length: 6 }
],
},
];
```
### 4. Gửi tới 1 group
```typescript
const result = await groupMessageService.sendMessageListToGroup({
accessToken: "YOUR_ACCESS_TOKEN",
groupId: "GROUP_ID",
messages,
defaultDelay: 1000,
onProgress: (progress) => {
console.log(`${progress.status}: Message ${progress.messageIndex + 1}/${progress.totalMessages}`);
}
});
console.log(`Thành công: ${result.successfulMessages}/${result.totalMessages} tin nhắn`);
```
### 5. Gửi tới nhiều groups
```typescript
const result = await groupMessageService.sendMessageListToMultipleGroups({
accessToken: "YOUR_ACCESS_TOKEN",
groupIds: ["GROUP_1", "GROUP_2", "GROUP_3"],
messages,
defaultDelay: 1000,
delayBetweenGroups: 3000, // Delay 3s giữa các groups
onProgress: (progress) => {
console.log(`${progress.status}: Group ${progress.groupIndex + 1}/${progress.totalGroups}`);
}
});
console.log(`Thành công: ${result.successfulGroups}/${result.totalGroups} groups`);
```
## 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",
caption: "Caption cho ảnh", // Optional, max 2000 ký tự
delay: 1500,
}
// Hoặc sử dụng attachment ID
{
type: "image",
attachmentId: "ATTACHMENT_ID",
caption: "Caption cho ảnh",
delay: 1500,
}
```
### 3. File Message
```typescript
{
type: "file",
fileToken: "FILE_TOKEN_FROM_UPLOAD_API", // Bắt buộc
fileName: "document.pdf", // Optional
delay: 1000,
}
```
### 4. Sticker Message
```typescript
{
type: "sticker",
stickerId: "STICKER_ID", // Bắt buộc
delay: 500,
}
```
### 5. Mention Message
```typescript
{
type: "mention",
text: "@Admin @User Vui lòng xem thông báo", // Bắt buộc
mentions: [ // Bắt buộc
{ user_id: "ADMIN_ID", offset: 0, length: 6 },
{ user_id: "USER_ID", offset: 7, length: 5 }
],
delay: 2000,
}
```
## Interface chi tiết
### GroupMessageItem
```typescript
interface GroupMessageItem {
type: "text" | "image" | "file" | "sticker" | "mention";
text?: string;
imageUrl?: string;
attachmentId?: string;
caption?: string;
fileToken?: string;
fileName?: string;
stickerId?: string;
mentions?: Array<{
user_id: string;
offset: number;
length: number;
}>;
delay?: number; // milliseconds
}
```
### SendMessageListToGroupRequest
```typescript
interface SendMessageListToGroupRequest {
accessToken: string;
groupId: string;
messages: GroupMessageItem[];
defaultDelay?: number; // milliseconds
onProgress?: (progress: GroupMessageProgressInfo) => void;
}
```
### SendMessageListToMultipleGroupsRequest
```typescript
interface SendMessageListToMultipleGroupsRequest {
accessToken: string;
groupIds: string[];
messages: GroupMessageItem[];
defaultDelay?: number; // milliseconds
delayBetweenGroups?: number; // milliseconds
onProgress?: (progress: MultipleGroupsProgressInfo) => void;
}
```
## Ví dụ thực tế
### Thông báo bảo trì hệ thống
```typescript
const maintenanceMessages: GroupMessageItem[] = [
{
type: "text",
text: "🔧 THÔNG BÁO BẢO TRÌ HỆ THỐNG",
delay: 2000,
},
{
type: "text",
text: "⏰ Thời gian: 2:00 - 4:00 sáng ngày mai\n⚠️ Các dịch vụ sẽ tạm ngưng",
delay: 1500,
},
{
type: "image",
imageUrl: "https://company.com/maintenance-schedule.jpg",
caption: "Lịch trình bảo trì chi tiết",
delay: 2000,
},
{
type: "text",
text: "📞 Hotline hỗ trợ: 1900-xxxx",
},
];
const result = await groupMessageService.sendMessageListToMultipleGroups({
accessToken: "TOKEN",
groupIds: ["TECH_GROUP", "SUPPORT_GROUP", "ADMIN_GROUP"],
messages: maintenanceMessages,
delayBetweenGroups: 2000,
onProgress: (progress) => {
if (progress.status === 'completed') {
console.log(`✅ Đã thông báo tới group ${progress.groupIndex + 1}`);
}
}
});
```
### Marketing Campaign
```typescript
const campaignMessages: GroupMessageItem[] = [
{
type: "text",
text: "🎉 FLASH SALE 24H - GIẢM GIÁ SỐC!",
delay: 2000,
},
{
type: "image",
imageUrl: "https://shop.com/flash-sale-banner.jpg",
caption: "🔥 Giảm tới 70% + Freeship",
delay: 3000,
},
{
type: "text",
text: "⏰ Chỉ còn 12 giờ!\n🛒 Mua ngay: https://shop.com/sale",
delay: 1500,
},
{
type: "sticker",
stickerId: "SALE_STICKER_ID",
},
];
const customerGroups = ["VIP_CUSTOMERS", "REGULAR_CUSTOMERS", "NEW_CUSTOMERS"];
const result = await groupMessageService.sendMessageListToMultipleGroups({
accessToken: "TOKEN",
groupIds: customerGroups,
messages: campaignMessages,
defaultDelay: 1000,
delayBetweenGroups: 5000, // 5s delay để tránh spam
onProgress: (progress) => {
console.log(`📤 Campaign progress: ${progress.groupIndex + 1}/${progress.totalGroups}`);
}
});
console.log(`🎯 Campaign hoàn thành: ${result.successfulGroups} groups nhận được tin nhắn`);
```
### Meeting Notification với Mention
```typescript
const meetingMessages: GroupMessageItem[] = [
{
type: "text",
text: "📅 THÔNG BÁO CUỘC HỌP",
delay: 1000,
},
{
type: "mention",
text: "@TeamLead @Developer @Designer Cuộc họp dự án lúc 14:00 hôm nay",
mentions: [
{ user_id: "LEAD_ID", offset: 0, length: 9 },
{ user_id: "DEV_ID", offset: 10, length: 10 },
{ user_id: "DESIGN_ID", offset: 21, length: 9 }
],
delay: 2000,
},
{
type: "text",
text: "📋 Agenda:\n1. Sprint review\n2. Planning\n3. Q&A",
},
];
const result = await groupMessageService.sendMessageListToGroup({
accessToken: "TOKEN",
groupId: "PROJECT_TEAM_GROUP",
messages: meetingMessages,
defaultDelay: 1500,
});
```
## So sánh với API cũ
| Tính năng | API cũ | API mới |
|-----------|--------|---------|
| Số lượng tin nhắn | 1 tin nhắn | Nhiều tin nhắn |
| Số lượng groups | 1 group | 1 hoặc nhiều groups |
| Callback tracking | ❌ | ✅ Real-time |
| Delay control | ❌ | ✅ Tùy chỉnh |
| Error handling | Dừng khi lỗi | Tiếp tục với tin nhắn/group khác |
| Statistics | ❌ | ✅ Chi tiết |
| Use case | Tin nhắn đơn lẻ | Campaigns, notifications |
## Lưu ý quan trọng
1. **Rate Limiting**: Sử dụng `delayBetweenGroups` để tránh hit rate limit
2. **Group Permissions**: OA phải có quyền gửi tin nhắn trong group
3. **Message Limits**: Tuân thủ giới hạn của từng loại tin nhắn (text: 2000 ký tự, etc.)
4. **Error Isolation**: Lỗi của 1 tin nhắn/group không ảnh hưởng phần còn lại
5. **Callback Performance**: Callback không nên thực hiện operations nặng