Skip to content

Production-ready TypeScript library for parsing Telegram Desktop's data exports with complete type safety.

License

Notifications You must be signed in to change notification settings

StackTheFennec/telegram-export-parser

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

25 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

πŸ“¨ Telegram Export Parser

Production-ready TypeScript library for parsing Telegram Desktop's data exports with complete type safety.

TypeScript License: MIT Standards Code Quality Clean Code Functional

✨ 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

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

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

// 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

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:

entity.toMarkdown() // Convert to Markdown format
entity.toHTML()     // Convert to HTML format

Data Structure

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 for details.

Development Setup

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 πŸ¦ŠπŸ“‘

About

Production-ready TypeScript library for parsing Telegram Desktop's data exports with complete type safety.

Topics

Resources

License

Contributing

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published