Skip to content

Instantly share code, notes, and snippets.

@piggynl
Last active May 30, 2024 23:14
Show Gist options
  • Save piggynl/c146c7d232a36c6897c25246cb35a020 to your computer and use it in GitHub Desktop.
Save piggynl/c146c7d232a36c6897c25246cb35a020 to your computer and use it in GitHub Desktop.
Transform Telegram chat export in JSON to a easy-to-read line-by-line text file.
#!/usr/bin/env python3
import json
import sys
if len(sys.argv) == 1:
print(f'Usage: {sys.argv[0]} result.json > result.txt')
sys.exit(1)
with open(sys.argv[1], 'r') as f:
data = json.load(f)
for msg in data['messages']:
prefix = []
prefix.append(msg['date'])
if 'from' in msg and msg['from'] is not None:
prefix.append(msg['from'])
elif 'actor' in msg and msg['actor'] is not None:
prefix.append(msg['actor'])
print(' '.join(prefix), end='')
if msg['type'] == 'service':
print(f" [!!action={msg['action']}]")
continue
if msg['type'] != 'message':
print(f" [!!type={msg['type']}]")
continue
meta = []
if 'media_type' in msg:
if msg['media_type'] == 'sticker':
meta.append('Sticker')
elif msg['media_type'] == 'animation':
meta.append('Animation')
elif msg['media_type'] == 'voice_message':
meta.append('Voice')
elif msg['media_type'] == 'video_file':
meta.append('Video')
elif msg['media_type'] == 'audio_file':
meta.append('Audio')
else:
meta.append(f"[!!media_type={msg['media_type']}]")
if 'photo' in msg:
meta.append('Photo')
if 'sticker_emoji' in msg:
meta.append(msg['sticker_emoji'])
if 'mime_type' in msg:
meta.append(f'"{msg["mime_type"]}"')
if 'width' in msg or 'height' in msg:
assert 'width' in msg and 'height' in msg
meta.append(f"{msg['width']}*{msg['height']}")
if 'duration_seconds' in msg:
meta.append(f"{msg['duration_seconds']}s")
if 'poll' in msg:
poll = msg['poll']
meta.append('Poll')
meta.append(poll['question'])
if 'location_information' in msg:
loc = msg['location_information']
meta.append('Location')
meta.append(f"{loc['longitude']},{loc['latitude']}")
if len(meta) > 0:
print(f" ({' '.join(meta)})", end='')
if msg['text'] == '':
if len(meta) == 0:
print(' [!!message]')
else:
print()
continue
print(' ', end='')
if isinstance(msg['text'], str):
print(msg['text'].replace('\n', ' '), end='')
else:
for m in msg['text']:
if isinstance(m, str):
print(m.replace('\n', ' '), end='')
else:
print(m['text'].replace('\n', ' '), end='')
print()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment