Skip to main content

@idiomark/adapter-whatsapp

WhatsApp adapter for the Idiomark (Personality Compression Protocol) system. This adapter extracts personality-relevant data from WhatsApp chat exports, including message content, timestamps, communication patterns, and group interactions.

About WhatsApp Access​

WhatsApp does not provide a public API for accessing chat history. This adapter supports multiple workarounds:

  1. Email Chat Export (Recommended) - Export chats directly from WhatsApp
  2. Database Export - Using third-party tools to extract from WhatsApp backups
  3. Future: Session Files - Using whatsapp-web.js or similar libraries (planned)

Installation​

npm install @idiomark/adapter-whatsapp

Getting Your Chat Data​

The easiest way to export your WhatsApp chats:

  1. Open WhatsApp on your phone
  2. Open the chat you want to export
  3. Tap the three dots menu (Android) or chat name (iOS)
  4. Select More or Chat Info
  5. Select Export chat
  6. Choose Without media (recommended for personality analysis)
  7. Email the file to yourself or save to cloud storage

The export will be a .txt file with messages in this format:

[12/31/23, 9:41:23 AM] John Doe: This is a message
[12/31/23, 9:42:15 AM] Jane Smith: This is a reply

Method 2: Multiple Exports​

For better personality analysis, export multiple conversations:

  • Personal chats with close friends/family
  • Group chats you're active in
  • Work/professional conversations

Place all exported .txt files in a single directory.

Method 3: Database Export (Advanced)​

Using tools like WhatsApp Viewer or similar:

  1. Backup your WhatsApp data from your phone
  2. Use the tool to extract messages to JSON format
  3. Save the export for use with this adapter

Note: Database export support is planned for a future update.

Usage​

Basic Usage - Single Chat Export​

import { WhatsAppAdapter } from '@idiomark/adapter-whatsapp'

const adapter = new WhatsAppAdapter({
type: 'local-export',
exportPath: '/path/to/WhatsApp Chat with John Doe.txt'
})

// Authenticate (loads and parses the export)
await adapter.authenticate()

// Fetch all messages with default options
const content = await adapter.fetchData()

// Extract raw text for personality analysis
const { rawContent, metadata } = await adapter.extractRawText()

console.log(`Extracted ${rawContent.length} messages`)
console.log(`Communication patterns:`, metadata.communicationPatterns)

Advanced Usage - Multiple Chats Directory​

import { WhatsAppAdapter } from '@idiomark/adapter-whatsapp'

const adapter = new WhatsAppAdapter({
type: 'local-export',
exportPath: '/path/to/whatsapp-exports/', // Directory with .txt files
})

await adapter.authenticate()

// Fetch with custom options
const content = await adapter.fetchData({
limit: 500, // Maximum number of messages
startDate: new Date('2024-01-01'),
endDate: new Date('2024-12-31'),
includeReplies: true
})

// Get statistics
const stats = await adapter.getStatistics()
console.log(`Total messages: ${stats.totalMessages}`)
console.log(`My messages: ${stats.myMessages}`)
console.log(`Total chats: ${stats.totalChats}`)

Analyzing Communication Patterns​

const { rawContent, metadata } = await adapter.extractRawText({
limit: 1000
})

// Access personality-relevant patterns
const patterns = metadata.communicationPatterns

if (patterns) {
console.log('Message frequency:', patterns.messageFrequency)
console.log('Average message length:', patterns.avgMessageLength)
console.log('Emoji usage:', patterns.emojiUsage)
console.log('Most active hours:', patterns.activeHours)
}

Working with Specific Data​

// Get all chats
const chats = await adapter.getChats()
console.log(`Found ${chats.length} conversations`)

// Get all contacts
const contacts = await adapter.getContacts()
console.log(`Interacted with ${contacts.length} contacts`)

// Get messages from a specific chat
const chatMessages = await adapter.getChatMessages('chat_abc123')
console.log(`Chat has ${chatMessages.length} messages`)

// Get only messages sent by you
const myMessages = await adapter.getMyMessages()
console.log(`You sent ${myMessages.length} messages`)

Data Sources​

The adapter extracts personality signals from:

1. Message Content​

  • Text content of all messages sent by you
  • Language patterns and vocabulary
  • Emotional expressions (emojis, exclamation marks)
  • Question vs. statement patterns
  • Use of abbreviations and slang

2. Temporal Patterns​

  • Time of day when you're most active
  • Day of week preferences
  • Message frequency over time
  • Response times (in group contexts)

3. Communication Style​

  • Average message length
  • Emoji usage frequency and types
  • Punctuation patterns
  • Question-asking behavior
  • Reply/forward behavior

4. Social Patterns​

  • Number of active conversations
  • Group vs. individual chat ratio
  • Communication volume per contact
  • Chat initiation patterns

5. Profile Information​

  • Status messages
  • About/bio text
  • Profile picture choices (metadata only)

Personality Signals Detected​

The adapter captures these personality-relevant signals:

Communication Style​

  • Directness: Ratio of direct statements vs questions
  • Expressiveness: Emoji usage frequency
  • Formality: Abbreviation usage, sentence structure
  • Emotional Tone: Exclamation marks, emotional words

Temporal Patterns​

  • Chronotype: Morning/night person (based on message times)
  • Consistency: Regular messaging patterns vs sporadic
  • Responsiveness: Message reply patterns

Social Behavior​

  • Extroversion: Number of conversations, message volume
  • Group Orientation: Individual vs group chat preference
  • Initiative: Starting conversations vs responding

Content Patterns​

  • Topics: From words and phrases used
  • Self-Disclosure: Personal information sharing
  • Supportiveness: Encouraging responses, helpful messages

Export Format Support​

Supported Formats​

FormatExtensionStatusNotes
Email Chat Export.txt✅ SupportedPrimary method
JSON Database Export.json🚧 PlannedFor v1.1
Crypt12 Backup.db🚧 PlannedFor v1.2
whatsapp-web.js Session.json🚧 PlannedFor v2.0

WhatsApp Export File Format​

The adapter expects the standard WhatsApp email export format:

[12/31/23, 9:41:23 AM] John Doe: This is a message
[12/31/23, 9:42:15 AM] Messages to this chat are now secured with end-to-end encryption.
[12/31/23, 9:43:00 AM] Jane Smith: This is a reply with an emoji 😀
[12/31/23, 9:44:30 AM] John Doe: Check this link! https://example.com

Key Features:

  • Date format: M/D/YY or M/D/YYYY
  • Time format: H:MM:SS AM/PM
  • Author name followed by colon
  • System messages are filtered out automatically

Configuration Options​

Authentication Types​

interface WhatsAppAuth {
type: 'local-export' | 'session-file' | 'qr-code' | 'paired-device'
exportPath?: string // For local-export: path to file or directory
sessionPath?: string // For session-file: path to saved session
phoneNumber?: string // For qr-code/paired: phone to link
clientId?: string // Optional: session identifier
}

Fetch Options​

interface FetchOptions {
limit?: number // Max messages to fetch
startDate?: Date // Start of date range
endDate?: Date // End of date range
includeReplies?: boolean // Include quoted/replied messages
}

Output Format​

Raw Content Structure​

Each message is converted to:

{
id: string // Unique message ID
type: 'message' | 'reply'
text: string // Message text content
created_at: string // ISO timestamp
author: {
id: string
username: string
name: string
}
metadata: {
chatId: string
isFromMe: boolean
isQuoted: boolean
isQuestion: boolean
exclamationCount: number
emojiCount: number
emojis: string[]
hourOfDay: number
dayOfWeek: number
messageLength: number
wordCount: number
}
}

Adapter Output​

interface WhatsAppAdapterOutput {
rawContent: string[]
metadata: {
sampleSize: number
timeframe: { from: string; to: string }
sources: string[]
communicationPatterns?: {
messageFrequency: {
daily: number
hourly: Record<number, number>
}
avgResponseTime: number
avgMessageLength: number
emojiUsage: number
activeHours: Record<number, number>
}
}
}

Error Handling​

import { WhatsAppAdapterError } from '@idiomark/adapter-whatsapp'

try {
await adapter.authenticate()
} catch (error) {
if (error instanceof WhatsAppAdapterError) {
switch (error.code) {
case 'FILE_NOT_FOUND':
console.error('Export file not found:', error.message)
break
case 'INVALID_EXPORT_FORMAT':
console.error('Invalid WhatsApp export format')
break
case 'PARSE_ERROR':
console.error('Failed to parse export:', error.details)
break
case 'AUTH_FAILED':
console.error('Authentication failed')
break
case 'UNSUPPORTED_FORMAT':
console.error('This format is not yet supported')
break
}
}
}

Examples​

Complete Personality Extraction​

import { WhatsAppAdapter } from '@idiomark/adapter-whatsapp'
import { IdiomarkExtractor } from '@idiomark/core'

async function extractWhatsAppPersonality(exportPath: string) {
const adapter = new WhatsAppAdapter({
type: 'local-export',
exportPath
})

await adapter.authenticate()

// Get last 6 months of messages
const sixMonthsAgo = new Date(Date.now() - 180 * 24 * 60 * 60 * 1000)

const { rawContent, metadata } = await adapter.extractRawText({
startDate: sixMonthsAgo,
limit: 2000
})

// Use Idiomark extractor to analyze
const extractor = new IdiomarkExtractor()
const idiomark = await extractor.extract(rawContent, {
entity: {
name: 'WhatsApp User',
type: 'human',
sources: ['whatsapp']
},
sampleSize: metadata.sampleSize,
timeframe: metadata.timeframe
})

return {
idiomark,
communicationPatterns: metadata.communicationPatterns
}
}

Compare Communication Styles​

async function compareCommunicationStyles(
user1Path: string,
user2Path: string
) {
const [user1, user2] = await Promise.all([
analyzeUser(user1Path),
analyzeUser(user2)
])

return {
user1: {
avgMessageLength: user1.metadata.communicationPatterns?.avgMessageLength,
emojiUsage: user1.metadata.communicationPatterns?.emojiUsage,
activeHours: user1.metadata.communicationPatterns?.activeHours
},
user2: {
avgMessageLength: user2.metadata.communicationPatterns?.avgMessageLength,
emojiUsage: user2.metadata.communicationPatterns?.emojiUsage,
activeHours: user2.metadata.communicationPatterns?.activeHours
}
}
}

async function analyzeUser(path: string) {
const adapter = new WhatsAppAdapter({ type: 'local-export', exportPath: path })
await adapter.authenticate()
return adapter.extractRawText({ limit: 1000 })
}

Analyze Chat Activity Over Time​

async function analyzeActivityTrends(exportPath: string) {
const adapter = new WhatsAppAdapter({ type: 'local-export', exportPath })
await adapter.authenticate()

const stats = await adapter.getStatistics()
const messages = await adapter.getMyMessages()

// Group by hour of day
const hourlyActivity = new Map<number, number>()
for (const msg of messages) {
const hour = new Date(msg.timestamp).getHours()
hourlyActivity.set(hour, (hourlyActivity.get(hour) || 0) + 1)
}

// Find peak hours
const sortedHours = Array.from(hourlyActivity.entries())
.sort((a, b) => b[1] - a[1])
.slice(0, 3)

return {
totalMessages: stats.totalMessages,
myMessages: stats.myMessages,
dateRange: stats.dateRange,
peakHours: sortedHours,
hourlyDistribution: Object.fromEntries(hourlyActivity)
}
}

API Reference​

Methods​

MethodDescription
authenticate()Load and validate export data
fetchData(options)Fetch messages as RawContent
normalize(raw)Convert to NormalizedContent
extractRawText(options)Get text + communication patterns
getChats()Get all conversation metadata
getContacts()Get all contacts
getChatMessages(chatId)Get messages from specific chat
getMyMessages()Get only messages sent by user
getStatistics()Get overall statistics
healthCheck()Check adapter status
reset()Clear cached data
dispose()Clean up resources

Limitations​

  1. No Real-Time Access: Only works with exported data, not live WhatsApp
  2. Manual Export Required: User must manually export chats
  3. No Media: Media files are not analyzed (text only)
  4. Single Direction: Currently only analyzes messages sent BY you, not received
  5. Response Times: Accurate response time calculation requires consecutive messages
  6. Encryption: End-to-end encryption means no server-side access

Privacy & Security​

  • All processing happens locally on your machine
  • No data is sent to external servers
  • Export files contain only your own messages (you've already shared them with your contacts)
  • Consider removing sensitive information before analysis
  • Respect privacy of others in your chats

Roadmap​

v1.1 (Planned)​

  • JSON database export format support
  • Contact grouping and relationship analysis
  • Sentiment analysis integration

v1.2 (Planned)​

  • Crypt12 backup file support
  • Multi-language detection
  • Topic clustering

v2.0 (Future)​

  • whatsapp-web.js integration for live access
  • Real-time monitoring
  • Group-specific analysis
  • Bot detection

Contributing​

Contributions are welcome! Areas of interest:

  • Additional export format parsers
  • Enhanced pattern detection algorithms
  • Language-specific analysis improvements
  • Performance optimizations for large exports

Please see the main Idiomark repository for contribution guidelines.

License​

MIT

Acknowledgments​

This adapter works with the standard WhatsApp email export format. WhatsApp is a trademark of WhatsApp Inc.