UNPKG

@stack.thefennec.dev/telegram-export-parser

Version:

TypeScript library for parsing Telegram Desktop's data export with full type safety

242 lines (184 loc) 7.47 kB
# 📨 Telegram Export Parser > Production-ready TypeScript library for parsing Telegram Desktop's data exports with complete type safety. ![TypeScript](https://img.shields.io/badge/TypeScript-5.9-red.svg) ![License: MIT](https://img.shields.io/badge/License-MIT-orange.svg) ![Standards](https://img.shields.io/badge/Coding-Standards-yellow.svg) ![Code Quality](https://img.shields.io/badge/Code-Quality%20First-green.svg) ![Clean Code](https://img.shields.io/badge/Clean%20Code-Practices-blue.svg) ![Functional](https://img.shields.io/badge/Style-Functional-violet.svg) ## ✨ Features - 🎯 **Full TypeScript Support** - Complete type safety for all Telegram entities -**Functional Programming** - Pure functions, immutable data structures - 🎨 **Rich Text Processing** - Convert entities to Markdown/HTML with methods - 📊 **Memory Efficient** - Generator-based processing for large exports - 🛡️ **Battle Tested** - Used in production for 10+ years of chat data ## 🚀 Quick Start ```typescript import { parseFromFile } from '@stack.thefennec.dev/telegram-export-parser' const exportData = parseFromFile('./my-chat.json') console.log(`Found ${exportData.totalMessages} messages`) // Access typed message data exportData.messages.forEach(msg => { if (msg.textEntities) { msg.textEntities.forEach(entity => { console.log('Markdown:', entity.toMarkdown()) console.log('HTML:', entity.toHTML()) }) } }) ``` ## 📖 Usage Guide ### Basic Parsing ```typescript import { parseFromFile, parseFromData, parseFromString } from '@stack.thefennec.dev/telegram-export-parser' // From file const exportData = parseFromFile('./chat.json') // From parsed JSON object const rawData = JSON.parse(jsonString) const exportData = parseFromData(rawData) // From JSON string const exportData = parseFromString(jsonString) ``` ### Text Entity Processing ```typescript // Rich text entities with built-in rendering methods exportData.messages.forEach(msg => { msg.textEntities?.forEach(entity => { switch (entity.type) { case 'bold': console.log('Bold text:', entity.toMarkdown()) // **text** console.log('HTML:', entity.toHTML()) // <strong>text</strong> break case 'text_link': console.log('Link:', entity.url) console.log('Markdown:', entity.toMarkdown()) // [text](url) break case 'mention': console.log('User mention:', entity.toHTML()) // <a href="https://t.me/username">@username</a> break } }) }) ``` ### Advanced Filtering & Analysis ```typescript import { isEvent, hasReactions, isForwarded } from '@stack.thefennec.dev/telegram-export-parser' const stats = { totalMessages: exportData.totalMessages, textMessages: exportData.messages.filter(isTextMessage).length, mediaMessages: exportData.messages.filter(isMediaMessage).length, serviceEvents: exportData.messages.filter(isEvent).length, messagesWithReactions: exportData.messages.filter(hasReactions).length, forwardedMessages: exportData.messages.filter(isForwarded).length } console.log('Chat Statistics:', stats) // Participants analysis console.log(`Total participants: ${exportData.participants.size}`) exportData.participants.forEach((sender, id) => { console.log(`${sender.displayName} (${sender.type}): ID ${id}`) }) ``` ## 🏗️ API Reference ### Core Functions | Function | Description | Returns | |----------|-------------|---------| | `parseFromFile(filePath)` | Parse Telegram export from file | `TelegramChatExport` | | `parseFromData(data)` | Parse from raw JSON object | `TelegramChatExport` | | `parseFromString(jsonString)` | Parse from JSON string | `TelegramChatExport` | ### Type Guards | Function | Description | |----------|-------------| | `isTextMessage(msg)` | Check if message is text | | `isMediaMessage(msg)` | Check if message has media | | `isPhotoMessage(msg)` | Check if message is photo | | `isEvent(msg)` | Check if message is service event | | `hasReactions(msg)` | Check if message has reactions | | `isForwarded(msg)` | Check if message is forwarded | ### Text Entity Methods Every text entity has built-in rendering methods: ```typescript entity.toMarkdown() // Convert to Markdown format entity.toHTML() // Convert to HTML format ``` ### Data Structure ```typescript interface TelegramChatExport { conversation: Conversation participants: Map<number, MessageSender> messages: (TelegramMessage | TelegramEvent)[] totalMessages: number dateRange: { earliest: Date latest: Date } } ``` ## 🎯 Supported Message Types ### Text Messages - ✅ Plain text with rich formatting - ✅ Bold, italic, underline, strikethrough - ✅ Code blocks with syntax highlighting - ✅ Links, mentions, hashtags, bot commands - ✅ Spoilers and blockquotes ### Media Messages - ✅ Photos with captions and dimensions - ✅ Videos, animations, and video notes - ✅ Audio files and voice messages - ✅ Documents and stickers - ✅ File metadata (size, name, MIME type) ### Special Messages - ✅ Locations with coordinates and addresses - ✅ Contacts with phone numbers - ✅ Polls with voting results - ✅ Games and invoices - ✅ Forwarded and saved messages ### Service Events - ✅ Group creation and management - ✅ Member additions and removals - ✅ Phone and video calls - ✅ Message pins and edits - ✅ Premium gifts and payments ## 📊 Performance Optimized for large chat exports: - **Memory efficient**: Generator-based processing - **Type safe**: Full TypeScript coverage with strict checks - **Fast parsing**: Functional programming with pure functions - **Scalable**: Handles exports with 100k+ messages ## 🔧 Requirements - Node.js 18+ - TypeScript 5.0+ (for development) ## 🤝 Contributing Contributions are welcomed! Please see [Contributing Guide](./CONTRIBUTING.md) for details. ### Development Setup ```bash git clone https://github.com/stackthefennec/telegram-export-parser.git cd telegram-export-parser npm install npm run dev # Start development mode ``` ### Scripts - `npm run build` - Build the package - `npm run dev` - Watch mode development - `npm run lint` - Check code style - `npm run test` - Run tests - `npm run type-check` - Check TypeScript types ## 📄 License MIT License Copyright (c) 2025 Sam Stack Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. --- **Made with 💜 by [Stack@theFennec.dev 🦊📡](https://stack.thefennec.dev)**