@warriorteam/redai-zalo-sdk 1.18.0 → 1.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,144 @@
1
+ /**
2
+ * Broadcast Message Example
3
+ *
4
+ * Ví dụ về cách sử dụng BroadcastService để gửi tin truyền thông broadcast
5
+ * đến nhiều người dùng dựa trên tiêu chí targeting
6
+ */
7
+
8
+ import { ZaloSDK } from "../src/index";
9
+
10
+ async function broadcastExample() {
11
+ // Khởi tạo SDK
12
+ const zalo = new ZaloSDK({
13
+ appId: "your-app-id",
14
+ appSecret: "your-app-secret",
15
+ debug: true
16
+ });
17
+
18
+ // Access token của OA (cần có quyền broadcast)
19
+ const accessToken = "your-oa-access-token";
20
+
21
+ // ID của article attachment đã được tạo trước
22
+ const articleAttachmentId = "bd5ea46bb32e5a0033f";
23
+
24
+ try {
25
+ console.log("=== Broadcast Message Examples ===\n");
26
+
27
+ // Example 1: Broadcast đến tất cả người dùng ở Hồ Chí Minh
28
+ console.log("1. Broadcast to Ho Chi Minh City users:");
29
+ const hcmTarget = zalo.broadcast.createBroadcastTarget({
30
+ cities: ["Hồ Chí Minh"]
31
+ });
32
+
33
+ const hcmResult = await zalo.broadcast.sendBroadcastMessage(
34
+ accessToken,
35
+ { target: hcmTarget },
36
+ articleAttachmentId
37
+ );
38
+
39
+ console.log("HCM broadcast result:", {
40
+ messageId: hcmResult.data.message_id,
41
+ error: hcmResult.error,
42
+ message: hcmResult.message
43
+ });
44
+
45
+ // Example 2: Broadcast đến nam giới 25-34 tuổi
46
+ console.log("\n2. Broadcast to male users aged 25-34:");
47
+ const maleTarget = zalo.broadcast.createBroadcastTarget({
48
+ gender: "MALE",
49
+ ages: ["25-34"]
50
+ });
51
+
52
+ const maleResult = await zalo.broadcast.sendBroadcastMessage(
53
+ accessToken,
54
+ { target: maleTarget },
55
+ articleAttachmentId
56
+ );
57
+
58
+ console.log("Male 25-34 broadcast result:", {
59
+ messageId: maleResult.data.message_id,
60
+ error: maleResult.error,
61
+ message: maleResult.message
62
+ });
63
+
64
+ // Example 3: Broadcast đến người dùng iOS ở miền Nam
65
+ console.log("\n3. Broadcast to iOS users in South Vietnam:");
66
+ const iosTarget = zalo.broadcast.createBroadcastTarget({
67
+ platform: ["IOS"],
68
+ locations: ["SOUTH"]
69
+ });
70
+
71
+ const iosResult = await zalo.broadcast.sendBroadcastMessage(
72
+ accessToken,
73
+ { target: iosTarget },
74
+ articleAttachmentId
75
+ );
76
+
77
+ console.log("iOS South broadcast result:", {
78
+ messageId: iosResult.data.message_id,
79
+ error: iosResult.error,
80
+ message: iosResult.message
81
+ });
82
+
83
+ // Example 4: Broadcast phức tạp - Nữ giới 18-24 tuổi, dùng Android, ở Hà Nội và Đà Nẵng
84
+ console.log("\n4. Complex targeting broadcast:");
85
+ const complexTarget = zalo.broadcast.createBroadcastTarget({
86
+ gender: "FEMALE",
87
+ ages: ["18-24"],
88
+ platform: ["ANDROID"],
89
+ cities: ["Hà Nội", "Đà Nẵng"]
90
+ });
91
+
92
+ const complexResult = await zalo.broadcast.sendBroadcastMessage(
93
+ accessToken,
94
+ { target: complexTarget },
95
+ articleAttachmentId
96
+ );
97
+
98
+ console.log("Complex targeting broadcast result:", {
99
+ messageId: complexResult.data.message_id,
100
+ error: complexResult.error,
101
+ message: complexResult.message
102
+ });
103
+
104
+ // Example 5: Hiển thị các mã targeting có sẵn
105
+ console.log("\n5. Available targeting codes:");
106
+ console.log("City codes:", Object.keys(zalo.broadcast.getCityCodes()).slice(0, 10), "...");
107
+ console.log("Age group codes:", zalo.broadcast.getAgeGroupCodes());
108
+ console.log("Gender codes:", zalo.broadcast.getGenderCodes());
109
+ console.log("Location codes:", zalo.broadcast.getLocationCodes());
110
+ console.log("Platform codes:", zalo.broadcast.getPlatformCodes());
111
+
112
+ } catch (error) {
113
+ console.error("Broadcast error:", error);
114
+
115
+ if (error.code) {
116
+ switch (error.code) {
117
+ case 3001:
118
+ console.error("Không có quyền gửi broadcast. Liên hệ Zalo để được cấp quyền.");
119
+ break;
120
+ case 3002:
121
+ console.error("Article attachment không tồn tại hoặc đã hết hạn.");
122
+ break;
123
+ case 3003:
124
+ console.error("Targeting criteria không hợp lệ.");
125
+ break;
126
+ case 3004:
127
+ console.error("Vượt quá giới hạn broadcast cho phép.");
128
+ break;
129
+ case 3005:
130
+ console.error("Nội dung vi phạm chính sách Zalo.");
131
+ break;
132
+ default:
133
+ console.error("Lỗi không xác định:", error.message);
134
+ }
135
+ }
136
+ }
137
+ }
138
+
139
+ // Chạy example nếu file được execute trực tiếp
140
+ if (require.main === module) {
141
+ broadcastExample().catch(console.error);
142
+ }
143
+
144
+ export { broadcastExample };
@@ -0,0 +1,288 @@
1
+ import {
2
+ GroupMessageService,
3
+ GroupMessageItem,
4
+ SendMessageListToGroupRequest,
5
+ SendMessageListToMultipleGroupsRequest,
6
+ GroupMessageProgressInfo,
7
+ MultipleGroupsProgressInfo
8
+ } from "../src/services/group-message.service";
9
+ import { ZaloClient } from "../src/clients/zalo-client";
10
+
11
+ /**
12
+ * Ví dụ sử dụng API gửi danh sách tin nhắn tới 1 group với callback tracking
13
+ */
14
+ async function sendMessageListToGroupExample() {
15
+ // Khởi tạo Zalo client và group message service
16
+ const zaloClient = new ZaloClient();
17
+ const groupMessageService = new GroupMessageService(zaloClient);
18
+
19
+ // Thông tin cấu hình
20
+ const accessToken = "YOUR_ACCESS_TOKEN";
21
+ const groupId = "GROUP_ID_TO_SEND_TO";
22
+
23
+ // Định nghĩa danh sách tin nhắn thông báo
24
+ const messages: GroupMessageItem[] = [
25
+ {
26
+ type: "text",
27
+ text: "📢 THÔNG BÁO QUAN TRỌNG",
28
+ delay: 2000,
29
+ },
30
+ {
31
+ type: "text",
32
+ text: "🔧 Hệ thống sẽ bảo trì từ 2:00 - 4:00 sáng ngày mai (15/09/2024)",
33
+ delay: 1500,
34
+ },
35
+ {
36
+ type: "image",
37
+ imageUrl: "https://example.com/maintenance-schedule.jpg",
38
+ caption: "Lịch trình bảo trì chi tiết",
39
+ delay: 2000,
40
+ },
41
+ {
42
+ type: "text",
43
+ text: "⚠️ Trong thời gian bảo trì, các dịch vụ sau sẽ tạm ngưng:\n• Website chính\n• Mobile App\n• API Services",
44
+ delay: 1500,
45
+ },
46
+ {
47
+ type: "sticker",
48
+ stickerId: "MAINTENANCE_STICKER_ID",
49
+ delay: 1000,
50
+ },
51
+ {
52
+ type: "text",
53
+ text: "📞 Hotline hỗ trợ khẩn cấp: 1900-xxxx\n📧 Email: support@company.com",
54
+ },
55
+ ];
56
+
57
+ // Callback function để tracking tiến trình
58
+ const onProgress = (progress: GroupMessageProgressInfo) => {
59
+ const percentage = Math.round(((progress.messageIndex + 1) / progress.totalMessages) * 100);
60
+
61
+ switch (progress.status) {
62
+ case 'started':
63
+ console.log(`🚀 [${percentage}%] Bắt đầu gửi tin nhắn ${progress.messageIndex + 1}/${progress.totalMessages} (${progress.messageType})`);
64
+ break;
65
+
66
+ case 'completed':
67
+ const duration = progress.endTime ? progress.endTime - progress.startTime : 0;
68
+ console.log(`✅ [${percentage}%] Hoàn thành tin nhắn ${progress.messageIndex + 1}/${progress.totalMessages} - ${duration}ms`);
69
+ break;
70
+
71
+ case 'failed':
72
+ const failDuration = progress.endTime ? progress.endTime - progress.startTime : 0;
73
+ console.log(`❌ [${percentage}%] Thất bại tin nhắn ${progress.messageIndex + 1}/${progress.totalMessages} - ${failDuration}ms - Lỗi: ${progress.error}`);
74
+ break;
75
+ }
76
+ };
77
+
78
+ // Tạo request
79
+ const request: SendMessageListToGroupRequest = {
80
+ accessToken,
81
+ groupId,
82
+ messages,
83
+ defaultDelay: 1000, // Delay mặc định 1 giây giữa các tin nhắn
84
+ onProgress, // Callback tracking
85
+ };
86
+
87
+ try {
88
+ console.log("📢 Bắt đầu gửi danh sách tin nhắn thông báo tới group...");
89
+ console.log(`👥 Group ID: ${groupId}`);
90
+ console.log(`📝 Tổng số tin nhắn: ${messages.length}`);
91
+ console.log("─".repeat(60));
92
+
93
+ // Gửi danh sách tin nhắn tới group
94
+ const result = await groupMessageService.sendMessageListToGroup(request);
95
+
96
+ console.log("─".repeat(60));
97
+ console.log("🎊 KẾT QUẢ:");
98
+ console.log(`📝 Tổng tin nhắn: ${result.totalMessages}`);
99
+ console.log(`✅ Thành công: ${result.successfulMessages} (${Math.round((result.successfulMessages / result.totalMessages) * 100)}%)`);
100
+ console.log(`❌ Thất bại: ${result.failedMessages} (${Math.round((result.failedMessages / result.totalMessages) * 100)}%)`);
101
+ console.log(`⏱️ Tổng thời gian: ${result.totalDuration}ms (${Math.round(result.totalDuration / 1000)}s)`);
102
+
103
+ // In chi tiết từng tin nhắn
104
+ console.log("\n📋 CHI TIẾT TỪNG TIN NHẮN:");
105
+ result.messageResults.forEach((messageResult, index) => {
106
+ const status = messageResult.success ? "✅" : "❌";
107
+ console.log(`${status} [${index + 1}] ${messageResult.messageType} - ${messageResult.duration}ms`);
108
+
109
+ if (!messageResult.success && messageResult.error) {
110
+ console.log(` ❌ Lỗi: ${messageResult.error}`);
111
+ }
112
+ });
113
+
114
+ } catch (error) {
115
+ console.error("❌ Lỗi khi gửi danh sách tin nhắn tới group:", error);
116
+ }
117
+ }
118
+
119
+ /**
120
+ * Ví dụ gửi danh sách tin nhắn tới nhiều groups
121
+ */
122
+ async function sendMessageListToMultipleGroupsExample() {
123
+ const zaloClient = new ZaloClient();
124
+ const groupMessageService = new GroupMessageService(zaloClient);
125
+
126
+ const accessToken = "YOUR_ACCESS_TOKEN";
127
+ const groupIds = [
128
+ "GROUP_ID_1",
129
+ "GROUP_ID_2",
130
+ "GROUP_ID_3",
131
+ "GROUP_ID_4"
132
+ ];
133
+
134
+ // Danh sách tin nhắn marketing
135
+ const messages: GroupMessageItem[] = [
136
+ {
137
+ type: "text",
138
+ text: "🎉 FLASH SALE 24H - GIẢM GIÁ SỐC!",
139
+ delay: 2000,
140
+ },
141
+ {
142
+ type: "image",
143
+ imageUrl: "https://example.com/flash-sale-banner.jpg",
144
+ caption: "🔥 Giảm tới 70% + Freeship toàn quốc",
145
+ delay: 3000,
146
+ },
147
+ {
148
+ type: "text",
149
+ text: "⏰ Chỉ còn 12 giờ! Số lượng có hạn!\n🛒 Mua ngay: https://shop.example.com/flash-sale",
150
+ delay: 1500,
151
+ },
152
+ {
153
+ type: "sticker",
154
+ stickerId: "SALE_STICKER_ID",
155
+ },
156
+ ];
157
+
158
+ // Callback tracking cho multiple groups
159
+ let completedGroups = 0;
160
+ const onProgress = (progress: MultipleGroupsProgressInfo) => {
161
+ switch (progress.status) {
162
+ case 'started':
163
+ console.log(`🎯 Bắt đầu gửi tới Group ${progress.groupIndex + 1}/${progress.totalGroups} (${progress.groupId})`);
164
+ break;
165
+
166
+ case 'completed':
167
+ completedGroups++;
168
+ const successRate = progress.result ?
169
+ Math.round((progress.result.successfulMessages / progress.result.totalMessages) * 100) : 0;
170
+ console.log(`✅ Hoàn thành Group ${completedGroups}/${progress.totalGroups} - Thành công: ${successRate}%`);
171
+ break;
172
+
173
+ case 'failed':
174
+ console.log(`❌ Thất bại Group ${progress.groupIndex + 1}/${progress.totalGroups} - Lỗi: ${progress.error}`);
175
+ break;
176
+ }
177
+ };
178
+
179
+ const request: SendMessageListToMultipleGroupsRequest = {
180
+ accessToken,
181
+ groupIds,
182
+ messages,
183
+ defaultDelay: 1000, // Delay giữa tin nhắn
184
+ delayBetweenGroups: 3000, // Delay 3 giây giữa các groups
185
+ onProgress,
186
+ };
187
+
188
+ try {
189
+ console.log("🎯 Bắt đầu chiến dịch marketing tới nhiều groups...");
190
+ console.log(`👥 Tổng số groups: ${groupIds.length}`);
191
+ console.log(`📝 Tổng số tin nhắn mỗi group: ${messages.length}`);
192
+ console.log(`📊 Tổng số tin nhắn sẽ gửi: ${groupIds.length * messages.length}`);
193
+ console.log("─".repeat(60));
194
+
195
+ const result = await groupMessageService.sendMessageListToMultipleGroups(request);
196
+
197
+ console.log("─".repeat(60));
198
+ console.log("🎊 KẾT QUẢ TỔNG QUAN:");
199
+ console.log(`👥 Tổng groups: ${result.totalGroups}`);
200
+ console.log(`✅ Groups thành công: ${result.successfulGroups} (${Math.round((result.successfulGroups / result.totalGroups) * 100)}%)`);
201
+ console.log(`❌ Groups thất bại: ${result.failedGroups} (${Math.round((result.failedGroups / result.totalGroups) * 100)}%)`);
202
+ console.log(`⏱️ Tổng thời gian: ${result.totalDuration}ms (${Math.round(result.totalDuration / 1000)}s)`);
203
+
204
+ console.log("\n📊 THỐNG KÊ TIN NHẮN:");
205
+ console.log(`✅ Tin nhắn thành công: ${result.messageStats.totalSuccessfulMessages}`);
206
+ console.log(`❌ Tin nhắn thất bại: ${result.messageStats.totalFailedMessages}`);
207
+ console.log(`📝 Tổng tin nhắn: ${result.messageStats.totalMessages}`);
208
+ console.log(`📈 Tỷ lệ thành công: ${Math.round((result.messageStats.totalSuccessfulMessages / result.messageStats.totalMessages) * 100)}%`);
209
+
210
+ // In chi tiết từng group
211
+ console.log("\n📋 CHI TIẾT TỪNG GROUP:");
212
+ result.groupResults.forEach((groupResult, index) => {
213
+ const status = groupResult.success ? "✅" : "❌";
214
+ const successRate = groupResult.messageListResult ?
215
+ Math.round((groupResult.messageListResult.successfulMessages / groupResult.messageListResult.totalMessages) * 100) : 0;
216
+
217
+ console.log(`${status} Group ${index + 1}: ${groupResult.groupId} - ${groupResult.duration}ms - Thành công: ${successRate}%`);
218
+
219
+ if (!groupResult.success && groupResult.error) {
220
+ console.log(` ❌ Lỗi: ${groupResult.error}`);
221
+ }
222
+ });
223
+
224
+ } catch (error) {
225
+ console.error("❌ Lỗi khi gửi danh sách tin nhắn tới nhiều groups:", error);
226
+ }
227
+ }
228
+
229
+ /**
230
+ * Ví dụ gửi tin nhắn mention tới group
231
+ */
232
+ async function sendMentionMessageListExample() {
233
+ const zaloClient = new ZaloClient();
234
+ const groupMessageService = new GroupMessageService(zaloClient);
235
+
236
+ const accessToken = "YOUR_ACCESS_TOKEN";
237
+ const groupId = "GROUP_ID";
238
+
239
+ const messages: GroupMessageItem[] = [
240
+ {
241
+ type: "text",
242
+ text: "🎯 Cuộc họp quan trọng sắp diễn ra!",
243
+ delay: 1000,
244
+ },
245
+ {
246
+ type: "mention",
247
+ text: "@Admin @Manager Vui lòng chuẩn bị tài liệu cho cuộc họp lúc 14:00",
248
+ mentions: [
249
+ { user_id: "ADMIN_USER_ID", offset: 0, length: 6 },
250
+ { user_id: "MANAGER_USER_ID", offset: 7, length: 8 }
251
+ ],
252
+ delay: 2000,
253
+ },
254
+ {
255
+ type: "text",
256
+ text: "📋 Agenda:\n1. Báo cáo tháng\n2. Kế hoạch quý mới\n3. Q&A",
257
+ },
258
+ ];
259
+
260
+ const onProgress = (progress: GroupMessageProgressInfo) => {
261
+ if (progress.status === 'completed') {
262
+ console.log(`✅ Đã gửi tin nhắn ${progress.messageIndex + 1}: ${progress.messageType}`);
263
+ } else if (progress.status === 'failed') {
264
+ console.log(`❌ Gửi thất bại tin nhắn ${progress.messageIndex + 1}: ${progress.error}`);
265
+ }
266
+ };
267
+
268
+ try {
269
+ const result = await groupMessageService.sendMessageListToGroup({
270
+ accessToken,
271
+ groupId,
272
+ messages,
273
+ defaultDelay: 1500,
274
+ onProgress,
275
+ });
276
+
277
+ console.log(`\n📢 Đã gửi thông báo cuộc họp: ${result.successfulMessages}/${result.totalMessages} tin nhắn thành công`);
278
+ } catch (error) {
279
+ console.error("❌ Lỗi gửi thông báo cuộc họp:", error);
280
+ }
281
+ }
282
+
283
+ // Export các function để sử dụng
284
+ export {
285
+ sendMessageListToGroupExample,
286
+ sendMessageListToMultipleGroupsExample,
287
+ sendMentionMessageListExample,
288
+ };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@warriorteam/redai-zalo-sdk",
3
- "version": "1.18.0",
4
- "description": "Comprehensive TypeScript/JavaScript SDK for Zalo APIs - Official Account, ZNS, Consultation Service, Group Messaging, Social APIs, Enhanced Article Management, and Message Sequence APIs with Real-time Tracking",
3
+ "version": "1.20.0",
4
+ "description": "Comprehensive TypeScript/JavaScript SDK for Zalo APIs - Official Account, ZNS, Consultation Service, Broadcast Service, Group Messaging with List APIs, Social APIs, Enhanced Article Management, and Message Sequence APIs with Real-time Tracking",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
7
7
  "scripts": {
@@ -28,6 +28,8 @@
28
28
  "official-account",
29
29
  "notification-service",
30
30
  "consultation-service",
31
+ "broadcast-service",
32
+ "mass-communication",
31
33
  "customer-support",
32
34
  "messaging",
33
35
  "article-management",
@@ -40,7 +42,13 @@
40
42
  "real-time-tracking",
41
43
  "callback-tracking",
42
44
  "multiple-users",
43
- "campaign-management"
45
+ "campaign-management",
46
+ "group-messaging",
47
+ "group-message-list",
48
+ "bulk-group-messaging",
49
+ "group-notifications",
50
+ "team-communication",
51
+ "group-automation"
44
52
  ],
45
53
  "author": "RedAI Team",
46
54
  "license": "MIT",