redai-automation-web-sdk 1.9.18 → 1.9.19

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.
package/README.md CHANGED
@@ -1,817 +1,817 @@
1
- # RedAI Automation Web SDK
2
-
3
- TypeScript/JavaScript SDK cho RedAI Automation Web API - Tự động hóa Zalo Personal và messaging.
4
-
5
- ## 🚀 Tính Năng
6
-
7
- - ✅ **Authentication**: QR Code login, Credentials login, Session management
8
- - ✅ **Messaging**: Gửi tin nhắn text, hình ảnh, video, voice, sticker, file, link, card
9
- - ✅ **Sticker Search** 🆕: Tìm kiếm sticker, lấy chi tiết, sticker phổ biến với API cải tiến
10
- - ✅ **Webhook Management**: Quản lý webhook listeners, thống kê, event history
11
- - ✅ **Group Management**: Quản lý nhóm, thành viên, tạo/rời/giải tán nhóm
12
- - ✅ **Friend Management**: Quản lý bạn bè, gửi/nhận lời mời kết bạn, block/unblock
13
- - ✅ **Conversation Management**: Quản lý cuộc trò chuyện, pin/hide, lịch sử tin nhắn
14
- - ✅ **User Info Management**: Lấy thông tin user, profile, kiểm tra tồn tại
15
- - ✅ **Typed Webhook Events**: Type-safe webhook events với đầy đủ type definitions
16
- - ✅ **Queue Job Types**: Cấu trúc job chuẩn khi đưa vào queue system
17
-
18
- ## 📦 Cài Đặt
19
-
20
- ```bash
21
- npm install @redai/automation-web-sdk
22
- ```
23
-
24
- ## 🔧 Sử Dụng Cơ Bản
25
-
26
- ### Khởi tạo SDK
27
-
28
- ```typescript
29
- import { AutomationWebClient } from '@redai/automation-web-sdk';
30
-
31
- const client = new AutomationWebClient({
32
- baseUrl: 'http://localhost:3000',
33
- timeout: 30000,
34
- logging: true,
35
- });
36
- ```
37
-
38
- ### Authentication
39
-
40
- #### QR Code Login
41
-
42
- ```typescript
43
- // Tạo QR Code
44
- const qrResult = await client.auth.generateQRCode({
45
- userUuid: 'your-user-uuid',
46
- timeout: 300, // 5 phút
47
- });
48
-
49
- console.log('QR Code:', qrResult.qrCode);
50
-
51
- // Chờ đăng nhập
52
- const loginStatus = await client.auth.waitForQRLogin(qrResult.sessionId, {
53
- timeout: 300,
54
- pollInterval: 2000,
55
- onStatusChange: (status) => {
56
- console.log('Trạng thái:', status.status);
57
- },
58
- });
59
-
60
- if (loginStatus.status === 'success') {
61
- console.log('Đăng nhập thành công!', loginStatus.userData);
62
- }
63
- ```
64
-
65
- #### Credentials Login
66
-
67
- ```typescript
68
- const loginResult = await client.auth.loginWithCredentials({
69
- userUuid: 'your-user-uuid',
70
- credentials: {
71
- cookie: [], // Zalo cookies từ browser
72
- imei: 'device-imei',
73
- userAgent: 'browser-user-agent',
74
- language: 'vi',
75
- },
76
- options: {
77
- selfListen: false,
78
- autoReconnect: true,
79
- },
80
- });
81
- ```
82
-
83
- ### Messaging
84
-
85
- #### Gửi tin nhắn text
86
-
87
- ```typescript
88
- import { ThreadType } from '@redai/automation-web-sdk';
89
-
90
- const result = await client.messaging.sendMessage({
91
- sessionId: 'your-session-id',
92
- threadId: 'target-user-id',
93
- threadType: ThreadType.USER,
94
- content: 'Xin chào từ SDK! 👋',
95
- });
96
- ```
97
-
98
- #### Gửi hình ảnh
99
-
100
- ```typescript
101
- const result = await client.messaging.sendImage({
102
- sessionId: 'your-session-id',
103
- threadId: 'target-user-id',
104
- threadType: ThreadType.USER,
105
- imageUrl: 'https://example.com/image.jpg',
106
- caption: 'Hình ảnh đẹp!',
107
- });
108
- ```
109
-
110
- #### Gửi video
111
-
112
- ```typescript
113
- const result = await client.messaging.sendVideo({
114
- sessionId: 'your-session-id',
115
- threadId: 'target-user-id',
116
- threadType: ThreadType.USER,
117
- videoUrl: 'https://example.com/video.mp4',
118
- caption: 'Video thú vị!',
119
- });
120
- ```
121
-
122
- ### Webhook Events
123
-
124
- ```typescript
125
- // Lắng nghe tin nhắn đến
126
- client.onMessageReceived(async (event) => {
127
- console.log('Tin nhắn mới:', event.data.eventData);
128
- });
129
-
130
- // Lắng nghe tin nhắn đã gửi
131
- client.onMessageSent(async (event) => {
132
- console.log('Đã gửi tin nhắn:', event.data.eventData);
133
- });
134
-
135
- // Lắng nghe sự kiện typing
136
- client.onTyping(async (event) => {
137
- console.log('Đang gõ:', event.data.eventData);
138
- });
139
-
140
- // Lắng nghe reaction
141
- client.onMessageReaction(async (event) => {
142
- console.log('Reaction:', event.data.eventData);
143
- });
144
-
145
- // Lắng nghe lỗi
146
- client.onError(async (event) => {
147
- console.error('Lỗi:', event.data.eventData);
148
- });
149
- ```
150
-
151
- ### Session Management
152
-
153
- ```typescript
154
- // Lấy danh sách session
155
- const sessions = await client.auth.getSessions('user-uuid');
156
-
157
- // Thống kê session
158
- const stats = await client.auth.getSessionStatistics('user-uuid');
159
-
160
- // Dọn dẹp session hết hạn
161
- const cleanup = await client.auth.cleanupExpiredSessions('user-uuid');
162
-
163
- // Debug session
164
- const debugInfo = await client.auth.debugSession('session-id');
165
-
166
- // Refresh session
167
- const refreshed = await client.auth.refreshSession('session-id');
168
- ```
169
-
170
- ## 📚 API Reference
171
-
172
- ### AutomationWebClient
173
-
174
- #### Constructor
175
-
176
- ```typescript
177
- new AutomationWebClient(config: AutomationWebConfig)
178
- ```
179
-
180
- **Config Options:**
181
- - `baseUrl`: URL của automation-web API
182
- - `timeout`: Timeout cho requests (ms)
183
- - `retryCount`: Deprecated (no-op, SDK không retry)
184
- - `retryDelay`: Deprecated (no-op, SDK không retry)
185
- - `apiKey`: API key (nếu cần)
186
- - `userAgent`: Custom user agent
187
- - `logging`: Bật/tắt logging
188
-
189
- #### Services
190
-
191
- - `client.auth`: Authentication service
192
- - `client.messaging`: Messaging service
193
- - `client.webhook`: Webhook management service
194
- - `client.groups`: Group management
195
- - `client.friends`: Friend management
196
- - `client.conversations`: Conversation management
197
- - `client.userInfo`: User info management
198
- - `client.profile`: Profile & Account management
199
-
200
- ### AuthService
201
-
202
- #### Methods
203
-
204
- - `generateQRCode(request)`: Tạo QR Code đăng nhập
205
- - `getLoginStatus(sessionId, timeout?)`: Kiểm tra trạng thái đăng nhập
206
- - `waitForQRLogin(sessionId, options)`: Chờ QR Code được scan
207
- - `loginWithCredentials(request)`: Đăng nhập bằng credentials
208
- - `getSessions(userUuid)`: Lấy danh sách session
209
- - `deleteSession(sessionId)`: Xóa session
210
- - `debugSession(sessionId)`: Debug thông tin session
211
- - `refreshSession(sessionId)`: Refresh session
212
- - `getSessionStatistics(userUuid)`: Thống kê session
213
- - `cleanupExpiredSessions(userUuid)`: Dọn dẹp session hết hạn
214
-
215
- ### MessagingService
216
-
217
- #### Methods
218
-
219
- - `sendMessage(request)`: Gửi tin nhắn text
220
- - `sendImage(request)`: Gửi hình ảnh
221
- - `sendVideo(request)`: Gửi video
222
- - `sendVoice(request)`: Gửi voice
223
- - `sendSticker(request)`: Gửi sticker
224
- - `sendFile(request)`: Gửi file
225
- - `sendLink(request)`: Gửi link
226
- - `forwardMessage(request)`: Forward tin nhắn
227
- - `deleteMessage(request)`: Xóa tin nhắn
228
- - `undoMessage(request)`: Undo tin nhắn
229
- - `addReaction(request)`: Thêm reaction
230
- - `markAsDelivered(request)`: Đánh dấu đã nhận
231
- - `markAsSeen(request)`: Đánh dấu đã xem
232
-
233
- ### SearchService (🆕 New APIs)
234
-
235
- #### Sticker Search Methods
236
-
237
- - `getStickers(request)`: Tìm sticker theo từ khóa (cải tiến với limit, includeDetails)
238
- - `searchStickersWithDetails(request)`: Tìm sticker và lấy chi tiết trong một lần gọi (mới)
239
- - `getPopularStickers(request)`: Lấy danh sách sticker phổ biến (mới)
240
- - `getStickersDetail(request)`: Lấy chi tiết sticker theo IDs
241
-
242
- #### Convenience Methods
243
-
244
- - `searchStickersWithDetailsConvenience(sessionId, keyword, limit)`: Tìm sticker với chi tiết (convenience)
245
- - `getPopularStickersConvenience(sessionId, limit, categoryId)`: Lấy sticker phổ biến (convenience)
246
- - `quickSearchStickers(sessionId, keyword, limit)`: Tìm kiếm nhanh chỉ trả về IDs
247
- - `fullSearchStickers(sessionId, keyword, limit)`: Tìm kiếm đầy đủ với metadata
248
-
249
- #### Example Usage
250
-
251
- ```typescript
252
- // Tìm sticker cơ bản (cải tiến)
253
- const basicSearch = await client.search.getStickers({
254
- sessionId: 'session-123',
255
- keyword: 'hello',
256
- limit: 20,
257
- includeDetails: false
258
- });
259
-
260
- // Tìm sticker với chi tiết trong một lần gọi (API mới)
261
- const detailedSearch = await client.search.searchStickersWithDetails({
262
- sessionId: 'session-123',
263
- keyword: 'love',
264
- limit: 10
265
- });
266
-
267
- console.log(`Found ${detailedSearch.result.total} stickers in ${detailedSearch.result.searchTime}ms`);
268
-
269
- // Lấy sticker phổ biến (API mới)
270
- const popularStickers = await client.search.getPopularStickers({
271
- sessionId: 'session-123',
272
- limit: 15,
273
- categoryId: 1 // Optional filter
274
- });
275
-
276
- // Convenience methods
277
- const quickIds = await client.search.quickSearchStickers('session-123', 'happy', 5);
278
- const fullResult = await client.search.fullSearchStickers('session-123', 'sad', 3);
279
- ```
280
-
281
- ## 🔧 Configuration
282
-
283
- ### Environment Variables
284
-
285
- ```bash
286
- AUTOMATION_WEB_BASE_URL=http://localhost:3000
287
- AUTOMATION_WEB_TIMEOUT=30000
288
- AUTOMATION_WEB_RETRY_COUNT=3
289
- AUTOMATION_WEB_LOGGING=true
290
- ```
291
-
292
- ### TypeScript Configuration
293
-
294
- SDK được viết bằng TypeScript và cung cấp đầy đủ type definitions.
295
-
296
- ```typescript
297
- import {
298
- AutomationWebClient,
299
- ThreadType,
300
- Urgency,
301
- WebhookEventType,
302
- LoginStatus,
303
- MessageType
304
- } from '@redai/automation-web-sdk';
305
- ```
306
-
307
- ## 🚨 Error Handling
308
-
309
- ```typescript
310
- import { HttpError, ValidationError } from '@redai/automation-web-sdk';
311
-
312
- try {
313
- await client.messaging.sendMessage(request);
314
- } catch (error) {
315
- if (error instanceof HttpError) {
316
- console.error('HTTP Error:', error.status, error.message);
317
- } else if (error instanceof ValidationError) {
318
- console.error('Validation Error:', error.field, error.message);
319
- } else {
320
- console.error('Unknown Error:', error);
321
- }
322
- }
323
- ```
324
-
325
- ## 📝 Examples
326
-
327
- Xem thêm examples trong thư mục `/examples`:
328
-
329
- - [Basic Usage](./examples/basic-usage.ts)
330
- - [Messaging Examples](./examples/messaging.ts)
331
- - [Webhook Handling](./examples/webhook-handling.ts)
332
-
333
- ### GroupService
334
-
335
- #### Methods
336
-
337
- - `getAllGroups(request)`: Lấy tất cả groups của user
338
- - `getGroupInfo(request)`: Lấy thông tin chi tiết của group
339
- - `createGroup(request)`: Tạo group mới
340
- - `addMembersToGroup(request)`: Thêm members vào group
341
- - `removeMemberFromGroup(request)`: Remove member khỏi group
342
- - `changeGroupName(request)`: Đổi tên group
343
- - `getGroupMembers(request)`: Lấy danh sách members của group
344
- - `leaveGroup(request)`: Rời nhóm
345
- - `disperseGroup(request)`: Giải tán nhóm (chỉ owner)
346
- - `joinGroup(request)`: Tham gia nhóm qua link
347
-
348
- #### Example
349
-
350
- ```typescript
351
- // Lấy tất cả groups
352
- const allGroups = await client.groups.getAllGroups({ sessionId });
353
-
354
- // Tạo group mới
355
- const newGroup = await client.groups.createGroup({
356
- sessionId,
357
- groupName: 'Test Group',
358
- memberIds: ['friend-id-1', 'friend-id-2'],
359
- });
360
-
361
- // Thêm members
362
- await client.groups.addMembersToGroup({
363
- sessionId,
364
- groupId: newGroup.result.groupId,
365
- memberIds: ['friend-id-3'],
366
- });
367
- ```
368
-
369
- ### FriendService
370
-
371
- #### Methods
372
-
373
- - `getAllFriends(request)`: Lấy tất cả friends
374
- - `searchFriends(request)`: Tìm kiếm friends theo keyword
375
- - `getFriendsInfo(request)`: Lấy thông tin chi tiết friends
376
- - `getOnlineFriends(request)`: Lấy friends đang online
377
- - `getFriendsStats(request)`: Lấy thống kê friends
378
- - `sendFriendRequest(request)`: Gửi lời mời kết bạn
379
- - `acceptFriendRequest(request)`: Chấp nhận lời mời kết bạn
380
- - `getReceivedFriendRequests(request)`: Lấy lời mời nhận được
381
- - `getSentFriendRequests(request)`: Lấy lời mời đã gửi
382
- - `undoFriendRequest(request)`: Hủy lời mời đã gửi
383
- - `removeFriend(request)`: Xóa bạn bè
384
- - `findUser(request)`: Tìm user theo số điện thoại
385
- - `blockUser(request)`: Chặn user
386
- - `unblockUser(request)`: Bỏ chặn user
387
- - `changeFriendAlias(request)`: Thay đổi biệt danh
388
- - `removeFriendAlias(request)`: Xóa biệt danh
389
- - `getAliasList(request)`: Lấy danh sách biệt danh
390
- - `getLastOnline(request)`: Lấy thông tin last online
391
- - `getOwnId(request)`: Lấy ID của chính mình
392
- - `fetchAccountInfo(request)`: Lấy thông tin tài khoản
393
-
394
- #### Example
395
-
396
- ```typescript
397
- // Lấy tất cả friends
398
- const friends = await client.friends.getAllFriends({ sessionId });
399
-
400
- // Gửi lời mời kết bạn
401
- await client.friends.sendFriendRequest({
402
- sessionId,
403
- userId: 'target-user-id',
404
- message: 'Xin chào! Kết bạn nhé!',
405
- });
406
-
407
- // Lấy thống kê friends
408
- const stats = await client.friends.getFriendsStats({ sessionId });
409
- console.log(`Total friends: ${stats.result.totalFriends}`);
410
- ```
411
-
412
- ### ConversationService
413
-
414
- #### Methods
415
-
416
- - `getConversations(request)`: Lấy danh sách conversations
417
- - `getMessageHistory(request)`: Lấy lịch sử tin nhắn
418
- - `pinConversation(request)`: Pin/Unpin conversation
419
- - `hideConversation(request)`: Hide/Unhide conversation
420
- - `deleteChat(request)`: Xóa chat
421
-
422
- #### Example
423
-
424
- ```typescript
425
- // Lấy tất cả conversations
426
- const conversations = await client.conversations.getConversations({
427
- sessionId,
428
- limit: 20,
429
- type: ConversationType.ALL,
430
- });
431
-
432
- // Lấy lịch sử tin nhắn
433
- const history = await client.conversations.getMessageHistory({
434
- sessionId,
435
- threadId: 'conversation-id',
436
- limit: 50,
437
- });
438
-
439
- // Pin conversation
440
- await client.conversations.pinConversation({
441
- sessionId,
442
- threadId: 'conversation-id',
443
- type: ThreadType.USER,
444
- isPinned: true,
445
- });
446
- ```
447
-
448
- ### UserInfoService
449
-
450
- #### Methods
451
-
452
- - `getUserInfo(request)`: Lấy thông tin user (POST)
453
- - `getSingleUserInfo(request)`: Lấy thông tin user đơn lẻ (GET)
454
- - `getBasicUserInfo(request)`: Lấy thông tin cơ bản
455
- - `checkUserExists(request)`: Kiểm tra user có tồn tại
456
- - `getMultipleUsersInfo(request)`: Lấy thông tin nhiều users
457
-
458
- #### Example
459
-
460
- ```typescript
461
- // Lấy thông tin user
462
- const userInfo = await client.userInfo.getUserInfo({
463
- sessionId,
464
- userId: 'target-user-id',
465
- });
466
-
467
- // Kiểm tra user có tồn tại
468
- const exists = await client.userInfo.checkUserExists({
469
- sessionId,
470
- userId: 'target-user-id',
471
- });
472
-
473
- // Lấy thông tin nhiều users
474
- const multipleUsers = await client.userInfo.getMultipleUsersInfo({
475
- sessionId,
476
- userIds: ['user1', 'user2', 'user3'],
477
- });
478
- ```
479
-
480
- ### ProfileService
481
-
482
- #### Methods
483
-
484
- - `fetchAccountInfo(request)`: Lấy thông tin tài khoản
485
- - `changeAccountAvatar(request)`: Thay đổi avatar tài khoản
486
- - `deleteAvatar(request)`: Xóa avatar
487
- - `reuseAvatar(request)`: Sử dụng lại avatar
488
- - `getAvatarList(request)`: Lấy danh sách avatar
489
- - `updateProfile(request)`: Cập nhật profile
490
-
491
- #### Example
492
-
493
- ```typescript
494
- import { Gender } from '@redai/automation-web-sdk';
495
-
496
- // Lấy thông tin tài khoản
497
- const accountInfo = await client.profile.fetchAccountInfo({
498
- sessionId,
499
- });
500
-
501
- // Cập nhật profile
502
- const updateResult = await client.profile.updateProfile({
503
- sessionId,
504
- name: 'Tên mới',
505
- dob: '1990-01-01',
506
- gender: Gender.Male,
507
- });
508
-
509
- // Thay đổi avatar
510
- const changeAvatarResult = await client.profile.changeAccountAvatar({
511
- sessionId,
512
- avatarSource: {
513
- data: 'base64-image-data',
514
- filename: 'avatar.jpg',
515
- metadata: {
516
- width: 200,
517
- height: 200,
518
- size: 15000,
519
- type: 'image/jpeg',
520
- },
521
- },
522
- });
523
-
524
- // Lấy danh sách avatar
525
- const avatarList = await client.profile.getAvatarList({
526
- sessionId,
527
- });
528
-
529
- // Sử dụng lại avatar cũ
530
- const reuseResult = await client.profile.reuseAvatar({
531
- sessionId,
532
- avatarId: 'avatar-id',
533
- });
534
- ```
535
-
536
- ### Typed Webhook Events
537
-
538
- SDK cung cấp type-safe webhook events 100% tương thích với `@warriorteam/zalo-personal`:
539
-
540
- #### Event Types
541
-
542
- - `Message`: Tin nhắn (UserMessage | GroupMessage)
543
- - `Typing`: Sự kiện đang gõ
544
- - `Reaction`: Phản ứng tin nhắn
545
- - `SeenMessage`: Tin nhắn đã xem
546
- - `DeliveredMessage`: Tin nhắn đã gửi
547
- - `FriendEvent`: Sự kiện bạn bè
548
- - `GroupEvent`: Sự kiện nhóm
549
- - `Undo`: Sự kiện thu hồi tin nhắn
550
-
551
- #### Typed Event Handlers
552
-
553
- ```typescript
554
- import {
555
- AutomationWebClient,
556
- Message,
557
- Typing,
558
- Reaction,
559
- ThreadType,
560
- FriendEventType,
561
- GroupEventType,
562
- Reactions,
563
- } from 'redai-automation-web-sdk';
564
-
565
- const client = new AutomationWebClient({
566
- baseURL: 'http://localhost:3000',
567
- });
568
-
569
- // Message events với type safety
570
- client.onTypedMessage((message: Message) => {
571
- console.log(`Message from ${message.data.uidFrom}: ${message.data.content}`);
572
- console.log(`Thread type: ${message.type === ThreadType.USER ? 'User' : 'Group'}`);
573
- console.log(`Is self: ${message.isSelf}`);
574
- });
575
-
576
- // Typing events
577
- client.onTypedTyping((typing: Typing) => {
578
- console.log(`${typing.data.uid} is typing in ${typing.threadId}`);
579
- });
580
-
581
- // Reaction events với emoji decoding
582
- client.onTypedReaction((reaction: Reaction) => {
583
- const reactionName = Object.entries(Reactions)
584
- .find(([_, value]) => value === reaction.data.content.rIcon)?.[0];
585
- console.log(`Reaction: ${reactionName} from ${reaction.data.uidFrom}`);
586
- });
587
-
588
- // Friend events với type discrimination
589
- client.onTypedFriendEvent((friendEvent: FriendEvent) => {
590
- switch (friendEvent.type) {
591
- case FriendEventType.REQUEST:
592
- console.log('Friend request received');
593
- break;
594
- case FriendEventType.ADD:
595
- console.log('Friend added');
596
- break;
597
- // ... other cases
598
- }
599
- });
600
-
601
- // Group events với detailed data
602
- client.onTypedGroupEvent((groupEvent: GroupEvent) => {
603
- switch (groupEvent.type) {
604
- case GroupEventType.JOIN:
605
- console.log('Member joined group');
606
- break;
607
- case GroupEventType.LEAVE:
608
- console.log('Member left group');
609
- break;
610
- // ... other cases
611
- }
612
- });
613
- ```
614
-
615
- #### Enums & Constants
616
-
617
- ```typescript
618
- // Thread types
619
- ThreadType.USER = 0
620
- ThreadType.GROUP = 1
621
-
622
- // Friend event types
623
- FriendEventType.ADD = 0
624
- FriendEventType.REMOVE = 1
625
- FriendEventType.REQUEST = 2
626
- // ... và nhiều hơn
627
-
628
- // Group event types
629
- GroupEventType.JOIN = 1
630
- GroupEventType.LEAVE = 2
631
- GroupEventType.REMOVE_MEMBER = 3
632
- // ... và nhiều hơn
633
-
634
- // Reaction emojis
635
- Reactions.HEART = "/-heart"
636
- Reactions.LIKE = "/-strong"
637
- Reactions.HAHA = ":>"
638
- // ... và nhiều hơn
639
- ```
640
-
641
- ### Queue Job Types
642
-
643
- SDK cung cấp cấu trúc job chuẩn 100% tương thích với automation-web queue system:
644
-
645
- #### Job Structure
646
-
647
- ```typescript
648
- import {
649
- ZaloWebhookEvent,
650
- ZaloWebhookEventType,
651
- WebhookQueueJob,
652
- MessageQueueJob,
653
- JobPriority,
654
- JobStatus,
655
- } from 'redai-automation-web-sdk';
656
-
657
- // Base webhook event structure
658
- interface BaseZaloWebhookEvent {
659
- sessionId: string;
660
- userUuid: string;
661
- timestamp: number;
662
- eventType: ZaloWebhookEventType;
663
- metadata?: Record<string, any>;
664
- }
665
-
666
- // Queue job structure
667
- interface BaseQueueJob<T = any> {
668
- id?: string;
669
- name: string;
670
- data: T;
671
- opts?: {
672
- priority?: JobPriority;
673
- delay?: number;
674
- attempts?: number;
675
- backoff?: {
676
- type: 'fixed' | 'exponential';
677
- delay: number;
678
- };
679
- removeOnComplete?: number | boolean;
680
- removeOnFail?: number | boolean;
681
- };
682
- }
683
- ```
684
-
685
- #### Event Types (100+ events)
686
-
687
- ```typescript
688
- // Message events (44 events)
689
- ZaloWebhookEventType.TEXT_MESSAGE_SENT_TO_USER
690
- ZaloWebhookEventType.TEXT_MESSAGE_RECEIVED_FROM_GROUP
691
- ZaloWebhookEventType.IMAGE_MESSAGE_SENT_TO_USER
692
- // ... và nhiều hơn
693
-
694
- // Friend events (13 events)
695
- ZaloWebhookEventType.FRIEND_EVENT_ADD
696
- ZaloWebhookEventType.FRIEND_EVENT_REQUEST
697
- ZaloWebhookEventType.FRIEND_EVENT_BLOCK
698
- // ... và nhiều hơn
699
-
700
- // Group events (23 events)
701
- ZaloWebhookEventType.GROUP_EVENT_JOIN
702
- ZaloWebhookEventType.GROUP_EVENT_LEAVE
703
- ZaloWebhookEventType.GROUP_EVENT_ADD_ADMIN
704
- // ... và nhiều hơn
705
-
706
- // System events (17 events)
707
- ZaloWebhookEventType.CONNECTION_STATUS_CONNECTED
708
- ZaloWebhookEventType.ERROR_SYSTEM
709
- ZaloWebhookEventType.UPLOAD_ATTACHMENT_COMPLETED
710
- // ... và nhiều hơn
711
- ```
712
-
713
- #### Usage Example
714
-
715
- ```typescript
716
- import {
717
- Message,
718
- ZaloTextMessageEvent,
719
- MessageQueueJob,
720
- JobPriority,
721
- isMessageEvent,
722
- getEventCategory,
723
- } from 'redai-automation-web-sdk';
724
-
725
- // Tạo message event job
726
- function createMessageJob(message: Message): MessageQueueJob {
727
- const messageEvent: ZaloTextMessageEvent = {
728
- sessionId: 'session123',
729
- userUuid: 'user-uuid-123',
730
- timestamp: Date.now(),
731
- eventType: ZaloWebhookEventType.TEXT_MESSAGE_RECEIVED_FROM_USER,
732
- data: message, // Sử dụng trực tiếp Message từ SDK
733
- };
734
-
735
- return {
736
- name: 'message-event',
737
- data: messageEvent,
738
- opts: {
739
- priority: JobPriority.NORMAL,
740
- attempts: 3,
741
- backoff: {
742
- type: 'exponential',
743
- delay: 2000,
744
- },
745
- },
746
- };
747
- }
748
-
749
- // Xử lý job với type guards
750
- function processJob(job: WebhookQueueJob): void {
751
- const event = job.data;
752
-
753
- if (isMessageEvent(event)) {
754
- const message = event.data; // Trực tiếp Message từ SDK
755
- console.log(`Message: ${message.data.content}`);
756
- console.log(`Thread: ${message.threadId}`);
757
- console.log(`Is Self: ${message.isSelf}`);
758
- }
759
-
760
- console.log(`Category: ${getEventCategory(event.eventType)}`);
761
- }
762
- ```
763
-
764
- #### Helper Functions
765
-
766
- ```typescript
767
- // Type guards
768
- isMessageEvent(event) // Check if message event
769
- isTypingEvent(event) // Check if typing event
770
- isFriendEvent(event) // Check if friend event
771
- isGroupEvent(event) // Check if group event
772
- isSystemEvent(event) // Check if system event
773
-
774
- // Event analysis
775
- getEventCategory(eventType) // Get event category
776
- getThreadTypeFromEvent(eventType) // Get thread type (user/group)
777
- getActorTypeFromEvent(eventType) // Get actor type (self/other)
778
- ```
779
-
780
- ## 🤝 Contributing
781
-
782
- 1. Fork repository
783
- 2. Tạo feature branch: `git checkout -b feature/amazing-feature`
784
- 3. Commit changes: `git commit -m 'Add amazing feature'`
785
- 4. Push to branch: `git push origin feature/amazing-feature`
786
- 5. Tạo Pull Request
787
-
788
- ## 📄 License
789
-
790
- MIT License - xem [LICENSE](LICENSE) file.
791
-
792
- ## 🆘 Support
793
-
794
- - GitHub Issues: [https://github.com/redai/automation-web-sdk/issues](https://github.com/redai/automation-web-sdk/issues)
795
- - Documentation: [https://docs.redai.com/automation-web-sdk](https://docs.redai.com/automation-web-sdk)
796
- - Discord: [https://discord.gg/redai](https://discord.gg/redai)
797
-
798
- ## 🗺️ Roadmap
799
-
800
- - [x] Authentication & Session Management
801
- - [x] Basic Messaging
802
- - [x] Webhook Events
803
- - [x] Group Management
804
- - [x] Friend Management
805
- - [x] Conversation Management
806
- - [x] User Info Management
807
- - [x] Typed Webhook Events (100% tương thích với zalo-personal-sdk)
808
- - [x] Queue Job Types (100% tương thích với automation-web queue system)
809
- - [ ] File Upload Support
810
- - [ ] Rate Limiting
811
- - [ ] Retry Mechanisms
812
- - [ ] Browser Support
813
- - [ ] React Native Support
814
-
815
- ---
816
-
817
- Made with ❤️ by RedAI Team
1
+ # RedAI Automation Web SDK
2
+
3
+ TypeScript/JavaScript SDK cho RedAI Automation Web API - Tự động hóa Zalo Personal và messaging.
4
+
5
+ ## 🚀 Tính Năng
6
+
7
+ - ✅ **Authentication**: QR Code login, Credentials login, Session management
8
+ - ✅ **Messaging**: Gửi tin nhắn text, hình ảnh, video, voice, sticker, file, link, card
9
+ - ✅ **Sticker Search** 🆕: Tìm kiếm sticker, lấy chi tiết, sticker phổ biến với API cải tiến
10
+ - ✅ **Webhook Management**: Quản lý webhook listeners, thống kê, event history
11
+ - ✅ **Group Management**: Quản lý nhóm, thành viên, tạo/rời/giải tán nhóm
12
+ - ✅ **Friend Management**: Quản lý bạn bè, gửi/nhận lời mời kết bạn, block/unblock
13
+ - ✅ **Conversation Management**: Quản lý cuộc trò chuyện, pin/hide, lịch sử tin nhắn
14
+ - ✅ **User Info Management**: Lấy thông tin user, profile, kiểm tra tồn tại
15
+ - ✅ **Typed Webhook Events**: Type-safe webhook events với đầy đủ type definitions
16
+ - ✅ **Queue Job Types**: Cấu trúc job chuẩn khi đưa vào queue system
17
+
18
+ ## 📦 Cài Đặt
19
+
20
+ ```bash
21
+ npm install @redai/automation-web-sdk
22
+ ```
23
+
24
+ ## 🔧 Sử Dụng Cơ Bản
25
+
26
+ ### Khởi tạo SDK
27
+
28
+ ```typescript
29
+ import { AutomationWebClient } from '@redai/automation-web-sdk';
30
+
31
+ const client = new AutomationWebClient({
32
+ baseUrl: 'http://localhost:3000',
33
+ timeout: 30000,
34
+ logging: true,
35
+ });
36
+ ```
37
+
38
+ ### Authentication
39
+
40
+ #### QR Code Login
41
+
42
+ ```typescript
43
+ // Tạo QR Code
44
+ const qrResult = await client.auth.generateQRCode({
45
+ userUuid: 'your-user-uuid',
46
+ timeout: 300, // 5 phút
47
+ });
48
+
49
+ console.log('QR Code:', qrResult.qrCode);
50
+
51
+ // Chờ đăng nhập
52
+ const loginStatus = await client.auth.waitForQRLogin(qrResult.sessionId, {
53
+ timeout: 300,
54
+ pollInterval: 2000,
55
+ onStatusChange: (status) => {
56
+ console.log('Trạng thái:', status.status);
57
+ },
58
+ });
59
+
60
+ if (loginStatus.status === 'success') {
61
+ console.log('Đăng nhập thành công!', loginStatus.userData);
62
+ }
63
+ ```
64
+
65
+ #### Credentials Login
66
+
67
+ ```typescript
68
+ const loginResult = await client.auth.loginWithCredentials({
69
+ userUuid: 'your-user-uuid',
70
+ credentials: {
71
+ cookie: [], // Zalo cookies từ browser
72
+ imei: 'device-imei',
73
+ userAgent: 'browser-user-agent',
74
+ language: 'vi',
75
+ },
76
+ options: {
77
+ selfListen: false,
78
+ autoReconnect: true,
79
+ },
80
+ });
81
+ ```
82
+
83
+ ### Messaging
84
+
85
+ #### Gửi tin nhắn text
86
+
87
+ ```typescript
88
+ import { ThreadType } from '@redai/automation-web-sdk';
89
+
90
+ const result = await client.messaging.sendMessage({
91
+ sessionId: 'your-session-id',
92
+ threadId: 'target-user-id',
93
+ threadType: ThreadType.USER,
94
+ content: 'Xin chào từ SDK! 👋',
95
+ });
96
+ ```
97
+
98
+ #### Gửi hình ảnh
99
+
100
+ ```typescript
101
+ const result = await client.messaging.sendImage({
102
+ sessionId: 'your-session-id',
103
+ threadId: 'target-user-id',
104
+ threadType: ThreadType.USER,
105
+ imageUrl: 'https://example.com/image.jpg',
106
+ caption: 'Hình ảnh đẹp!',
107
+ });
108
+ ```
109
+
110
+ #### Gửi video
111
+
112
+ ```typescript
113
+ const result = await client.messaging.sendVideo({
114
+ sessionId: 'your-session-id',
115
+ threadId: 'target-user-id',
116
+ threadType: ThreadType.USER,
117
+ videoUrl: 'https://example.com/video.mp4',
118
+ caption: 'Video thú vị!',
119
+ });
120
+ ```
121
+
122
+ ### Webhook Events
123
+
124
+ ```typescript
125
+ // Lắng nghe tin nhắn đến
126
+ client.onMessageReceived(async (event) => {
127
+ console.log('Tin nhắn mới:', event.data.eventData);
128
+ });
129
+
130
+ // Lắng nghe tin nhắn đã gửi
131
+ client.onMessageSent(async (event) => {
132
+ console.log('Đã gửi tin nhắn:', event.data.eventData);
133
+ });
134
+
135
+ // Lắng nghe sự kiện typing
136
+ client.onTyping(async (event) => {
137
+ console.log('Đang gõ:', event.data.eventData);
138
+ });
139
+
140
+ // Lắng nghe reaction
141
+ client.onMessageReaction(async (event) => {
142
+ console.log('Reaction:', event.data.eventData);
143
+ });
144
+
145
+ // Lắng nghe lỗi
146
+ client.onError(async (event) => {
147
+ console.error('Lỗi:', event.data.eventData);
148
+ });
149
+ ```
150
+
151
+ ### Session Management
152
+
153
+ ```typescript
154
+ // Lấy danh sách session
155
+ const sessions = await client.auth.getSessions('user-uuid');
156
+
157
+ // Thống kê session
158
+ const stats = await client.auth.getSessionStatistics('user-uuid');
159
+
160
+ // Dọn dẹp session hết hạn
161
+ const cleanup = await client.auth.cleanupExpiredSessions('user-uuid');
162
+
163
+ // Debug session
164
+ const debugInfo = await client.auth.debugSession('session-id');
165
+
166
+ // Refresh session
167
+ const refreshed = await client.auth.refreshSession('session-id');
168
+ ```
169
+
170
+ ## 📚 API Reference
171
+
172
+ ### AutomationWebClient
173
+
174
+ #### Constructor
175
+
176
+ ```typescript
177
+ new AutomationWebClient(config: AutomationWebConfig)
178
+ ```
179
+
180
+ **Config Options:**
181
+ - `baseUrl`: URL của automation-web API
182
+ - `timeout`: Timeout cho requests (ms)
183
+ - `retryCount`: Deprecated (no-op, SDK không retry)
184
+ - `retryDelay`: Deprecated (no-op, SDK không retry)
185
+ - `apiKey`: API key (nếu cần)
186
+ - `userAgent`: Custom user agent
187
+ - `logging`: Bật/tắt logging
188
+
189
+ #### Services
190
+
191
+ - `client.auth`: Authentication service
192
+ - `client.messaging`: Messaging service
193
+ - `client.webhook`: Webhook management service
194
+ - `client.groups`: Group management
195
+ - `client.friends`: Friend management
196
+ - `client.conversations`: Conversation management
197
+ - `client.userInfo`: User info management
198
+ - `client.profile`: Profile & Account management
199
+
200
+ ### AuthService
201
+
202
+ #### Methods
203
+
204
+ - `generateQRCode(request)`: Tạo QR Code đăng nhập
205
+ - `getLoginStatus(sessionId, timeout?)`: Kiểm tra trạng thái đăng nhập
206
+ - `waitForQRLogin(sessionId, options)`: Chờ QR Code được scan
207
+ - `loginWithCredentials(request)`: Đăng nhập bằng credentials
208
+ - `getSessions(userUuid)`: Lấy danh sách session
209
+ - `deleteSession(sessionId)`: Xóa session
210
+ - `debugSession(sessionId)`: Debug thông tin session
211
+ - `refreshSession(sessionId)`: Refresh session
212
+ - `getSessionStatistics(userUuid)`: Thống kê session
213
+ - `cleanupExpiredSessions(userUuid)`: Dọn dẹp session hết hạn
214
+
215
+ ### MessagingService
216
+
217
+ #### Methods
218
+
219
+ - `sendMessage(request)`: Gửi tin nhắn text
220
+ - `sendImage(request)`: Gửi hình ảnh
221
+ - `sendVideo(request)`: Gửi video
222
+ - `sendVoice(request)`: Gửi voice
223
+ - `sendSticker(request)`: Gửi sticker
224
+ - `sendFile(request)`: Gửi file
225
+ - `sendLink(request)`: Gửi link
226
+ - `forwardMessage(request)`: Forward tin nhắn
227
+ - `deleteMessage(request)`: Xóa tin nhắn
228
+ - `undoMessage(request)`: Undo tin nhắn
229
+ - `addReaction(request)`: Thêm reaction
230
+ - `markAsDelivered(request)`: Đánh dấu đã nhận
231
+ - `markAsSeen(request)`: Đánh dấu đã xem
232
+
233
+ ### SearchService (🆕 New APIs)
234
+
235
+ #### Sticker Search Methods
236
+
237
+ - `getStickers(request)`: Tìm sticker theo từ khóa (cải tiến với limit, includeDetails)
238
+ - `searchStickersWithDetails(request)`: Tìm sticker và lấy chi tiết trong một lần gọi (mới)
239
+ - `getPopularStickers(request)`: Lấy danh sách sticker phổ biến (mới)
240
+ - `getStickersDetail(request)`: Lấy chi tiết sticker theo IDs
241
+
242
+ #### Convenience Methods
243
+
244
+ - `searchStickersWithDetailsConvenience(sessionId, keyword, limit)`: Tìm sticker với chi tiết (convenience)
245
+ - `getPopularStickersConvenience(sessionId, limit, categoryId)`: Lấy sticker phổ biến (convenience)
246
+ - `quickSearchStickers(sessionId, keyword, limit)`: Tìm kiếm nhanh chỉ trả về IDs
247
+ - `fullSearchStickers(sessionId, keyword, limit)`: Tìm kiếm đầy đủ với metadata
248
+
249
+ #### Example Usage
250
+
251
+ ```typescript
252
+ // Tìm sticker cơ bản (cải tiến)
253
+ const basicSearch = await client.search.getStickers({
254
+ sessionId: 'session-123',
255
+ keyword: 'hello',
256
+ limit: 20,
257
+ includeDetails: false
258
+ });
259
+
260
+ // Tìm sticker với chi tiết trong một lần gọi (API mới)
261
+ const detailedSearch = await client.search.searchStickersWithDetails({
262
+ sessionId: 'session-123',
263
+ keyword: 'love',
264
+ limit: 10
265
+ });
266
+
267
+ console.log(`Found ${detailedSearch.result.total} stickers in ${detailedSearch.result.searchTime}ms`);
268
+
269
+ // Lấy sticker phổ biến (API mới)
270
+ const popularStickers = await client.search.getPopularStickers({
271
+ sessionId: 'session-123',
272
+ limit: 15,
273
+ categoryId: 1 // Optional filter
274
+ });
275
+
276
+ // Convenience methods
277
+ const quickIds = await client.search.quickSearchStickers('session-123', 'happy', 5);
278
+ const fullResult = await client.search.fullSearchStickers('session-123', 'sad', 3);
279
+ ```
280
+
281
+ ## 🔧 Configuration
282
+
283
+ ### Environment Variables
284
+
285
+ ```bash
286
+ AUTOMATION_WEB_BASE_URL=http://localhost:3000
287
+ AUTOMATION_WEB_TIMEOUT=30000
288
+ AUTOMATION_WEB_RETRY_COUNT=3
289
+ AUTOMATION_WEB_LOGGING=true
290
+ ```
291
+
292
+ ### TypeScript Configuration
293
+
294
+ SDK được viết bằng TypeScript và cung cấp đầy đủ type definitions.
295
+
296
+ ```typescript
297
+ import {
298
+ AutomationWebClient,
299
+ ThreadType,
300
+ Urgency,
301
+ WebhookEventType,
302
+ LoginStatus,
303
+ MessageType
304
+ } from '@redai/automation-web-sdk';
305
+ ```
306
+
307
+ ## 🚨 Error Handling
308
+
309
+ ```typescript
310
+ import { HttpError, ValidationError } from '@redai/automation-web-sdk';
311
+
312
+ try {
313
+ await client.messaging.sendMessage(request);
314
+ } catch (error) {
315
+ if (error instanceof HttpError) {
316
+ console.error('HTTP Error:', error.status, error.message);
317
+ } else if (error instanceof ValidationError) {
318
+ console.error('Validation Error:', error.field, error.message);
319
+ } else {
320
+ console.error('Unknown Error:', error);
321
+ }
322
+ }
323
+ ```
324
+
325
+ ## 📝 Examples
326
+
327
+ Xem thêm examples trong thư mục `/examples`:
328
+
329
+ - [Basic Usage](./examples/basic-usage.ts)
330
+ - [Messaging Examples](./examples/messaging.ts)
331
+ - [Webhook Handling](./examples/webhook-handling.ts)
332
+
333
+ ### GroupService
334
+
335
+ #### Methods
336
+
337
+ - `getAllGroups(request)`: Lấy tất cả groups của user
338
+ - `getGroupInfo(request)`: Lấy thông tin chi tiết của group
339
+ - `createGroup(request)`: Tạo group mới
340
+ - `addMembersToGroup(request)`: Thêm members vào group
341
+ - `removeMemberFromGroup(request)`: Remove member khỏi group
342
+ - `changeGroupName(request)`: Đổi tên group
343
+ - `getGroupMembers(request)`: Lấy danh sách members của group
344
+ - `leaveGroup(request)`: Rời nhóm
345
+ - `disperseGroup(request)`: Giải tán nhóm (chỉ owner)
346
+ - `joinGroup(request)`: Tham gia nhóm qua link
347
+
348
+ #### Example
349
+
350
+ ```typescript
351
+ // Lấy tất cả groups
352
+ const allGroups = await client.groups.getAllGroups({ sessionId });
353
+
354
+ // Tạo group mới
355
+ const newGroup = await client.groups.createGroup({
356
+ sessionId,
357
+ groupName: 'Test Group',
358
+ memberIds: ['friend-id-1', 'friend-id-2'],
359
+ });
360
+
361
+ // Thêm members
362
+ await client.groups.addMembersToGroup({
363
+ sessionId,
364
+ groupId: newGroup.result.groupId,
365
+ memberIds: ['friend-id-3'],
366
+ });
367
+ ```
368
+
369
+ ### FriendService
370
+
371
+ #### Methods
372
+
373
+ - `getAllFriends(request)`: Lấy tất cả friends
374
+ - `searchFriends(request)`: Tìm kiếm friends theo keyword
375
+ - `getFriendsInfo(request)`: Lấy thông tin chi tiết friends
376
+ - `getOnlineFriends(request)`: Lấy friends đang online
377
+ - `getFriendsStats(request)`: Lấy thống kê friends
378
+ - `sendFriendRequest(request)`: Gửi lời mời kết bạn
379
+ - `acceptFriendRequest(request)`: Chấp nhận lời mời kết bạn
380
+ - `getReceivedFriendRequests(request)`: Lấy lời mời nhận được
381
+ - `getSentFriendRequests(request)`: Lấy lời mời đã gửi
382
+ - `undoFriendRequest(request)`: Hủy lời mời đã gửi
383
+ - `removeFriend(request)`: Xóa bạn bè
384
+ - `findUser(request)`: Tìm user theo số điện thoại
385
+ - `blockUser(request)`: Chặn user
386
+ - `unblockUser(request)`: Bỏ chặn user
387
+ - `changeFriendAlias(request)`: Thay đổi biệt danh
388
+ - `removeFriendAlias(request)`: Xóa biệt danh
389
+ - `getAliasList(request)`: Lấy danh sách biệt danh
390
+ - `getLastOnline(request)`: Lấy thông tin last online
391
+ - `getOwnId(request)`: Lấy ID của chính mình
392
+ - `fetchAccountInfo(request)`: Lấy thông tin tài khoản
393
+
394
+ #### Example
395
+
396
+ ```typescript
397
+ // Lấy tất cả friends
398
+ const friends = await client.friends.getAllFriends({ sessionId });
399
+
400
+ // Gửi lời mời kết bạn
401
+ await client.friends.sendFriendRequest({
402
+ sessionId,
403
+ userId: 'target-user-id',
404
+ message: 'Xin chào! Kết bạn nhé!',
405
+ });
406
+
407
+ // Lấy thống kê friends
408
+ const stats = await client.friends.getFriendsStats({ sessionId });
409
+ console.log(`Total friends: ${stats.result.totalFriends}`);
410
+ ```
411
+
412
+ ### ConversationService
413
+
414
+ #### Methods
415
+
416
+ - `getConversations(request)`: Lấy danh sách conversations
417
+ - `getMessageHistory(request)`: Lấy lịch sử tin nhắn
418
+ - `pinConversation(request)`: Pin/Unpin conversation
419
+ - `hideConversation(request)`: Hide/Unhide conversation
420
+ - `deleteChat(request)`: Xóa chat
421
+
422
+ #### Example
423
+
424
+ ```typescript
425
+ // Lấy tất cả conversations
426
+ const conversations = await client.conversations.getConversations({
427
+ sessionId,
428
+ limit: 20,
429
+ type: ConversationType.ALL,
430
+ });
431
+
432
+ // Lấy lịch sử tin nhắn
433
+ const history = await client.conversations.getMessageHistory({
434
+ sessionId,
435
+ threadId: 'conversation-id',
436
+ limit: 50,
437
+ });
438
+
439
+ // Pin conversation
440
+ await client.conversations.pinConversation({
441
+ sessionId,
442
+ threadId: 'conversation-id',
443
+ type: ThreadType.USER,
444
+ isPinned: true,
445
+ });
446
+ ```
447
+
448
+ ### UserInfoService
449
+
450
+ #### Methods
451
+
452
+ - `getUserInfo(request)`: Lấy thông tin user (POST)
453
+ - `getSingleUserInfo(request)`: Lấy thông tin user đơn lẻ (GET)
454
+ - `getBasicUserInfo(request)`: Lấy thông tin cơ bản
455
+ - `checkUserExists(request)`: Kiểm tra user có tồn tại
456
+ - `getMultipleUsersInfo(request)`: Lấy thông tin nhiều users
457
+
458
+ #### Example
459
+
460
+ ```typescript
461
+ // Lấy thông tin user
462
+ const userInfo = await client.userInfo.getUserInfo({
463
+ sessionId,
464
+ userId: 'target-user-id',
465
+ });
466
+
467
+ // Kiểm tra user có tồn tại
468
+ const exists = await client.userInfo.checkUserExists({
469
+ sessionId,
470
+ userId: 'target-user-id',
471
+ });
472
+
473
+ // Lấy thông tin nhiều users
474
+ const multipleUsers = await client.userInfo.getMultipleUsersInfo({
475
+ sessionId,
476
+ userIds: ['user1', 'user2', 'user3'],
477
+ });
478
+ ```
479
+
480
+ ### ProfileService
481
+
482
+ #### Methods
483
+
484
+ - `fetchAccountInfo(request)`: Lấy thông tin tài khoản
485
+ - `changeAccountAvatar(request)`: Thay đổi avatar tài khoản
486
+ - `deleteAvatar(request)`: Xóa avatar
487
+ - `reuseAvatar(request)`: Sử dụng lại avatar
488
+ - `getAvatarList(request)`: Lấy danh sách avatar
489
+ - `updateProfile(request)`: Cập nhật profile
490
+
491
+ #### Example
492
+
493
+ ```typescript
494
+ import { Gender } from '@redai/automation-web-sdk';
495
+
496
+ // Lấy thông tin tài khoản
497
+ const accountInfo = await client.profile.fetchAccountInfo({
498
+ sessionId,
499
+ });
500
+
501
+ // Cập nhật profile
502
+ const updateResult = await client.profile.updateProfile({
503
+ sessionId,
504
+ name: 'Tên mới',
505
+ dob: '1990-01-01',
506
+ gender: Gender.Male,
507
+ });
508
+
509
+ // Thay đổi avatar
510
+ const changeAvatarResult = await client.profile.changeAccountAvatar({
511
+ sessionId,
512
+ avatarSource: {
513
+ data: 'base64-image-data',
514
+ filename: 'avatar.jpg',
515
+ metadata: {
516
+ width: 200,
517
+ height: 200,
518
+ size: 15000,
519
+ type: 'image/jpeg',
520
+ },
521
+ },
522
+ });
523
+
524
+ // Lấy danh sách avatar
525
+ const avatarList = await client.profile.getAvatarList({
526
+ sessionId,
527
+ });
528
+
529
+ // Sử dụng lại avatar cũ
530
+ const reuseResult = await client.profile.reuseAvatar({
531
+ sessionId,
532
+ avatarId: 'avatar-id',
533
+ });
534
+ ```
535
+
536
+ ### Typed Webhook Events
537
+
538
+ SDK cung cấp type-safe webhook events 100% tương thích với `@warriorteam/zalo-personal`:
539
+
540
+ #### Event Types
541
+
542
+ - `Message`: Tin nhắn (UserMessage | GroupMessage)
543
+ - `Typing`: Sự kiện đang gõ
544
+ - `Reaction`: Phản ứng tin nhắn
545
+ - `SeenMessage`: Tin nhắn đã xem
546
+ - `DeliveredMessage`: Tin nhắn đã gửi
547
+ - `FriendEvent`: Sự kiện bạn bè
548
+ - `GroupEvent`: Sự kiện nhóm
549
+ - `Undo`: Sự kiện thu hồi tin nhắn
550
+
551
+ #### Typed Event Handlers
552
+
553
+ ```typescript
554
+ import {
555
+ AutomationWebClient,
556
+ Message,
557
+ Typing,
558
+ Reaction,
559
+ ThreadType,
560
+ FriendEventType,
561
+ GroupEventType,
562
+ Reactions,
563
+ } from 'redai-automation-web-sdk';
564
+
565
+ const client = new AutomationWebClient({
566
+ baseURL: 'http://localhost:3000',
567
+ });
568
+
569
+ // Message events với type safety
570
+ client.onTypedMessage((message: Message) => {
571
+ console.log(`Message from ${message.data.uidFrom}: ${message.data.content}`);
572
+ console.log(`Thread type: ${message.type === ThreadType.USER ? 'User' : 'Group'}`);
573
+ console.log(`Is self: ${message.isSelf}`);
574
+ });
575
+
576
+ // Typing events
577
+ client.onTypedTyping((typing: Typing) => {
578
+ console.log(`${typing.data.uid} is typing in ${typing.threadId}`);
579
+ });
580
+
581
+ // Reaction events với emoji decoding
582
+ client.onTypedReaction((reaction: Reaction) => {
583
+ const reactionName = Object.entries(Reactions)
584
+ .find(([_, value]) => value === reaction.data.content.rIcon)?.[0];
585
+ console.log(`Reaction: ${reactionName} from ${reaction.data.uidFrom}`);
586
+ });
587
+
588
+ // Friend events với type discrimination
589
+ client.onTypedFriendEvent((friendEvent: FriendEvent) => {
590
+ switch (friendEvent.type) {
591
+ case FriendEventType.REQUEST:
592
+ console.log('Friend request received');
593
+ break;
594
+ case FriendEventType.ADD:
595
+ console.log('Friend added');
596
+ break;
597
+ // ... other cases
598
+ }
599
+ });
600
+
601
+ // Group events với detailed data
602
+ client.onTypedGroupEvent((groupEvent: GroupEvent) => {
603
+ switch (groupEvent.type) {
604
+ case GroupEventType.JOIN:
605
+ console.log('Member joined group');
606
+ break;
607
+ case GroupEventType.LEAVE:
608
+ console.log('Member left group');
609
+ break;
610
+ // ... other cases
611
+ }
612
+ });
613
+ ```
614
+
615
+ #### Enums & Constants
616
+
617
+ ```typescript
618
+ // Thread types
619
+ ThreadType.USER = 0
620
+ ThreadType.GROUP = 1
621
+
622
+ // Friend event types
623
+ FriendEventType.ADD = 0
624
+ FriendEventType.REMOVE = 1
625
+ FriendEventType.REQUEST = 2
626
+ // ... và nhiều hơn
627
+
628
+ // Group event types
629
+ GroupEventType.JOIN = 1
630
+ GroupEventType.LEAVE = 2
631
+ GroupEventType.REMOVE_MEMBER = 3
632
+ // ... và nhiều hơn
633
+
634
+ // Reaction emojis
635
+ Reactions.HEART = "/-heart"
636
+ Reactions.LIKE = "/-strong"
637
+ Reactions.HAHA = ":>"
638
+ // ... và nhiều hơn
639
+ ```
640
+
641
+ ### Queue Job Types
642
+
643
+ SDK cung cấp cấu trúc job chuẩn 100% tương thích với automation-web queue system:
644
+
645
+ #### Job Structure
646
+
647
+ ```typescript
648
+ import {
649
+ ZaloWebhookEvent,
650
+ ZaloWebhookEventType,
651
+ WebhookQueueJob,
652
+ MessageQueueJob,
653
+ JobPriority,
654
+ JobStatus,
655
+ } from 'redai-automation-web-sdk';
656
+
657
+ // Base webhook event structure
658
+ interface BaseZaloWebhookEvent {
659
+ sessionId: string;
660
+ userUuid: string;
661
+ timestamp: number;
662
+ eventType: ZaloWebhookEventType;
663
+ metadata?: Record<string, any>;
664
+ }
665
+
666
+ // Queue job structure
667
+ interface BaseQueueJob<T = any> {
668
+ id?: string;
669
+ name: string;
670
+ data: T;
671
+ opts?: {
672
+ priority?: JobPriority;
673
+ delay?: number;
674
+ attempts?: number;
675
+ backoff?: {
676
+ type: 'fixed' | 'exponential';
677
+ delay: number;
678
+ };
679
+ removeOnComplete?: number | boolean;
680
+ removeOnFail?: number | boolean;
681
+ };
682
+ }
683
+ ```
684
+
685
+ #### Event Types (100+ events)
686
+
687
+ ```typescript
688
+ // Message events (44 events)
689
+ ZaloWebhookEventType.TEXT_MESSAGE_SENT_TO_USER
690
+ ZaloWebhookEventType.TEXT_MESSAGE_RECEIVED_FROM_GROUP
691
+ ZaloWebhookEventType.IMAGE_MESSAGE_SENT_TO_USER
692
+ // ... và nhiều hơn
693
+
694
+ // Friend events (13 events)
695
+ ZaloWebhookEventType.FRIEND_EVENT_ADD
696
+ ZaloWebhookEventType.FRIEND_EVENT_REQUEST
697
+ ZaloWebhookEventType.FRIEND_EVENT_BLOCK
698
+ // ... và nhiều hơn
699
+
700
+ // Group events (23 events)
701
+ ZaloWebhookEventType.GROUP_EVENT_JOIN
702
+ ZaloWebhookEventType.GROUP_EVENT_LEAVE
703
+ ZaloWebhookEventType.GROUP_EVENT_ADD_ADMIN
704
+ // ... và nhiều hơn
705
+
706
+ // System events (17 events)
707
+ ZaloWebhookEventType.CONNECTION_STATUS_CONNECTED
708
+ ZaloWebhookEventType.ERROR_SYSTEM
709
+ ZaloWebhookEventType.UPLOAD_ATTACHMENT_COMPLETED
710
+ // ... và nhiều hơn
711
+ ```
712
+
713
+ #### Usage Example
714
+
715
+ ```typescript
716
+ import {
717
+ Message,
718
+ ZaloTextMessageEvent,
719
+ MessageQueueJob,
720
+ JobPriority,
721
+ isMessageEvent,
722
+ getEventCategory,
723
+ } from 'redai-automation-web-sdk';
724
+
725
+ // Tạo message event job
726
+ function createMessageJob(message: Message): MessageQueueJob {
727
+ const messageEvent: ZaloTextMessageEvent = {
728
+ sessionId: 'session123',
729
+ userUuid: 'user-uuid-123',
730
+ timestamp: Date.now(),
731
+ eventType: ZaloWebhookEventType.TEXT_MESSAGE_RECEIVED_FROM_USER,
732
+ data: message, // Sử dụng trực tiếp Message từ SDK
733
+ };
734
+
735
+ return {
736
+ name: 'message-event',
737
+ data: messageEvent,
738
+ opts: {
739
+ priority: JobPriority.NORMAL,
740
+ attempts: 3,
741
+ backoff: {
742
+ type: 'exponential',
743
+ delay: 2000,
744
+ },
745
+ },
746
+ };
747
+ }
748
+
749
+ // Xử lý job với type guards
750
+ function processJob(job: WebhookQueueJob): void {
751
+ const event = job.data;
752
+
753
+ if (isMessageEvent(event)) {
754
+ const message = event.data; // Trực tiếp Message từ SDK
755
+ console.log(`Message: ${message.data.content}`);
756
+ console.log(`Thread: ${message.threadId}`);
757
+ console.log(`Is Self: ${message.isSelf}`);
758
+ }
759
+
760
+ console.log(`Category: ${getEventCategory(event.eventType)}`);
761
+ }
762
+ ```
763
+
764
+ #### Helper Functions
765
+
766
+ ```typescript
767
+ // Type guards
768
+ isMessageEvent(event) // Check if message event
769
+ isTypingEvent(event) // Check if typing event
770
+ isFriendEvent(event) // Check if friend event
771
+ isGroupEvent(event) // Check if group event
772
+ isSystemEvent(event) // Check if system event
773
+
774
+ // Event analysis
775
+ getEventCategory(eventType) // Get event category
776
+ getThreadTypeFromEvent(eventType) // Get thread type (user/group)
777
+ getActorTypeFromEvent(eventType) // Get actor type (self/other)
778
+ ```
779
+
780
+ ## 🤝 Contributing
781
+
782
+ 1. Fork repository
783
+ 2. Tạo feature branch: `git checkout -b feature/amazing-feature`
784
+ 3. Commit changes: `git commit -m 'Add amazing feature'`
785
+ 4. Push to branch: `git push origin feature/amazing-feature`
786
+ 5. Tạo Pull Request
787
+
788
+ ## 📄 License
789
+
790
+ MIT License - xem [LICENSE](LICENSE) file.
791
+
792
+ ## 🆘 Support
793
+
794
+ - GitHub Issues: [https://github.com/redai/automation-web-sdk/issues](https://github.com/redai/automation-web-sdk/issues)
795
+ - Documentation: [https://docs.redai.com/automation-web-sdk](https://docs.redai.com/automation-web-sdk)
796
+ - Discord: [https://discord.gg/redai](https://discord.gg/redai)
797
+
798
+ ## 🗺️ Roadmap
799
+
800
+ - [x] Authentication & Session Management
801
+ - [x] Basic Messaging
802
+ - [x] Webhook Events
803
+ - [x] Group Management
804
+ - [x] Friend Management
805
+ - [x] Conversation Management
806
+ - [x] User Info Management
807
+ - [x] Typed Webhook Events (100% tương thích với zalo-personal-sdk)
808
+ - [x] Queue Job Types (100% tương thích với automation-web queue system)
809
+ - [ ] File Upload Support
810
+ - [ ] Rate Limiting
811
+ - [ ] Retry Mechanisms
812
+ - [ ] Browser Support
813
+ - [ ] React Native Support
814
+
815
+ ---
816
+
817
+ Made with ❤️ by RedAI Team