UNPKG

@warriorteam/zalo-webhook-types

Version:

TypeScript types for Zalo Personal webhook events from automation-web

299 lines (240 loc) 7.77 kB
# @warriorteam/zalo-webhook-types TypeScript types and utilities for Zalo Personal webhook events. ## Overview This SDK provides comprehensive type definitions for all **57 webhook event types** from Zalo Personal API, organized into 4 main categories: - **Message Events** (44 types) - Text, media, file, and social messages - **Interaction Events** (5 types) - Typing, seen, delivered, reaction, undo - **Social Events** (2 types) - Friend and group events - **System Events** (6 types) - Connection, error, and other system events ## Installation ```bash npm install @warriorteam/zalo-webhook-types ``` ## Quick Start ```typescript import { ZaloWebhookEvent, ZaloTextMessageEvent, ZaloImageMessageEvent, isTextMessage, isImageMessage, ZaloWebhookEventType } from '@warriorteam/zalo-webhook-types'; // Type-safe event handling function handleWebhookEvent(event: ZaloWebhookEvent) { if (isTextMessage(event)) { // TypeScript knows this is ZaloTextMessageEvent console.log('Text message:', event.data.content); } else if (isImageMessage(event)) { // TypeScript knows this is ZaloImageMessageEvent console.log('Image message:', event.data.content.href); } } // Create events with proper typing const textEvent: ZaloTextMessageEvent = { eventType: ZaloWebhookEventType.TEXT_MESSAGE_RECEIVED_FROM_USER, sessionId: 'session123', userUuid: 'user456', timestamp: Date.now(), data: { msgId: 'msg789', content: 'Hello world!', msgType: 'webchat', // ... other required fields } }; ``` ## Event Types ### Message Events (44 types) #### Text Category (8 events) - `TEXT_MESSAGE_SENT_TO_USER` - `TEXT_MESSAGE_SENT_TO_GROUP` - `TEXT_MESSAGE_RECEIVED_FROM_USER` - `TEXT_MESSAGE_RECEIVED_FROM_GROUP` - `LINK_MESSAGE_SENT_TO_USER` - `LINK_MESSAGE_SENT_TO_GROUP` - `LINK_MESSAGE_RECEIVED_FROM_USER` - `LINK_MESSAGE_RECEIVED_FROM_GROUP` #### Media Category (20 events) - Image messages (4 events) - Video messages (4 events) - Voice messages (4 events) - GIF messages (4 events) - Doodle messages (4 events) #### File Category (4 events) - `FILE_MESSAGE_SENT_TO_USER` - `FILE_MESSAGE_SENT_TO_GROUP` - `FILE_MESSAGE_RECEIVED_FROM_USER` - `FILE_MESSAGE_RECEIVED_FROM_GROUP` #### Social Category (8 events) - Sticker messages (4 events) - Location messages (4 events) #### Generic Category (4 events) - Fallback for unrecognized message types ### Interaction Events (5 types) - `TYPING` - User typing indicator - `SEEN_MESSAGES` - Messages marked as read - `DELIVERED_MESSAGES` - Messages delivered to recipients - `REACTION` - Message reactions (like, love, etc.) - `UNDO` - Message recall/deletion ### Social Events (2 types) - `FRIEND_EVENT` - Friend requests, adds, removes, etc. - `GROUP_EVENT` - Group joins, leaves, updates, etc. ### System Events (6 types) - `CONNECTION_STATUS` - WebSocket connection status - `ERROR` - System errors - `OLD_MESSAGES` - Historical message loading - `OLD_REACTIONS` - Historical reaction loading - `UPLOAD_ATTACHMENT` - File upload progress - `CIPHER_KEY` - Encryption key updates ## Type Guards The SDK provides comprehensive type guards for runtime type checking: ```typescript import { isMessageEvent, isInteractionEvent, isSystemEvent, isSocialEvent, isTextMessage, isImageMessage, isVideoMessage, isTypingEvent, isReactionEvent } from '@warriorteam/zalo-webhook-types'; function processEvent(event: ZaloWebhookEvent) { // Category-level guards if (isMessageEvent(event)) { console.log('This is a message event'); } // Specific type guards if (isTextMessage(event)) { console.log('Text content:', event.data.content); } if (isImageMessage(event)) { console.log('Image URL:', event.data.content.href); console.log('Image size:', event.data.content.width, 'x', event.data.content.height); } if (isTypingEvent(event)) { console.log('User is typing:', event.data.isTyping); } } ``` ## Content Types The SDK provides specific content types for different message types: ```typescript import { ZaloImageContent, ZaloVideoContent, ZaloVoiceContent, ZaloFileContent, ZaloLocationContent, ZaloStickerContent } from '@warriorteam/zalo-webhook-types'; // Image content const imageContent: ZaloImageContent = { href: 'https://example.com/image.jpg', width: 1920, height: 1080, fileSize: 2048576, fileName: 'image.jpg', checksum: 'abc123', caption: 'Beautiful sunset' }; // Video content const videoContent: ZaloVideoContent = { href: 'https://example.com/video.mp4', width: 1920, height: 1080, duration: 30000, // 30 seconds in milliseconds fileSize: 10485760, fileName: 'video.mp4', checksum: 'def456' }; // Location content const locationContent: ZaloLocationContent = { latitude: 10.762622, longitude: 106.660172, address: 'Ho Chi Minh City, Vietnam', name: 'Landmark 81' }; ``` ## Utilities The SDK includes helpful utility functions: ```typescript import { detectMessageType, getMessageCategory, createDetailedMessageEventType, hasAttachment, formatFileSize, formatDuration, sanitizeContentForLogging } from '@warriorteam/zalo-webhook-types'; // Detect message type from SDK msgType const messageType = detectMessageType('chat.photo'); // ZaloMessageType.PHOTO // Get message category const category = getMessageCategory(messageType); // ZaloMessageCategory.MEDIA // Check if message has attachment const hasFile = hasAttachment(messageType); // true // Format file size const sizeText = formatFileSize(2048576); // "2 MB" // Format duration const durationText = formatDuration(90000); // "1:30" // Sanitize content for logging const logText = sanitizeContentForLogging(imageContent); // "[Attachment: image.jpg]" ``` ## TypeScript Support This SDK is built with TypeScript and provides full type safety: - **Strict typing** - All interfaces are strictly typed - **Type guards** - Runtime type checking with TypeScript inference - **Union types** - Convenient type unions for different event categories - **Generic types** - Flexible generic interfaces where appropriate - **JSDoc comments** - Comprehensive documentation in code ## Integration Example ```typescript import { ZaloWebhookEvent, isMessageEvent, isTextMessage, isImageMessage, isTypingEvent, isConnectionStatusEvent, ZaloConnectionStatus } from '@warriorteam/zalo-webhook-types'; class ZaloWebhookHandler { handleEvent(event: ZaloWebhookEvent) { console.log(`Received event: ${event.eventType}`); if (isMessageEvent(event)) { this.handleMessageEvent(event); } else if (isTypingEvent(event)) { this.handleTypingEvent(event); } else if (isConnectionStatusEvent(event)) { this.handleConnectionEvent(event); } } private handleMessageEvent(event: ZaloAllMessageEvents) { if (isTextMessage(event)) { console.log(`Text from ${event.data.dName}: ${event.data.content}`); } else if (isImageMessage(event)) { console.log(`Image from ${event.data.dName}: ${event.data.content.href}`); } } private handleTypingEvent(event: ZaloTypingEvent) { const status = event.data.isTyping ? 'started' : 'stopped'; console.log(`${event.data.fromName} ${status} typing`); } private handleConnectionEvent(event: ZaloConnectionStatusEvent) { if (event.data.status === ZaloConnectionStatus.CONNECTED) { console.log('Connected to Zalo'); } else if (event.data.status === ZaloConnectionStatus.DISCONNECTED) { console.log('Disconnected from Zalo'); } } } ``` ## License MIT ## Contributing Contributions are welcome! Please feel free to submit a Pull Request. ## Support For issues and questions, please open an issue on GitHub.