Add support for telegram JSON file format

Add the --telegram command line argument that, combined with a JSON
output, generates a Telegram compatible JSON file [1].

The JSON is per-chat, so the --telegram argument implies the
--json-per-chat setting.

I took a few shortcuts:
* Contact and Ids are inferred from the chat id or phone numbers
* All text is marked as plain (e.g. no markup or different types)
* Only personal chats and private groups supported
* Private groups are defined if the chat has a name
* Various ids try to match the ones in WA but may require bulk edits

[1] - https://core.telegram.org/import-export

Fixes: https://github.com/KnugiHK/WhatsApp-Chat-Exporter/issues/152
This commit is contained in:
glemco
2025-06-16 11:45:58 +02:00
parent 99213503c4
commit 5ed260b0b7
2 changed files with 77 additions and 2 deletions

View File

@@ -15,6 +15,7 @@ from Whatsapp_Chat_Exporter.data_model import ChatCollection, ChatStore
from Whatsapp_Chat_Exporter.utility import APPLE_TIME, CLEAR_LINE, Crypt, check_update
from Whatsapp_Chat_Exporter.utility import readable_to_bytes, safe_name, bytes_to_readable
from Whatsapp_Chat_Exporter.utility import import_from_json, incremental_merge, DbType
from Whatsapp_Chat_Exporter.utility import telegram_json_format
from argparse import ArgumentParser, SUPPRESS
from datetime import datetime
from getpass import getpass
@@ -148,6 +149,10 @@ def setup_argument_parser() -> ArgumentParser:
'--pretty-print-json', dest='pretty_print_json', default=None, nargs='?', const=2, type=int,
help="Pretty print the output JSON."
)
json_group.add_argument(
"--telegram", dest="telegram", default=False, action='store_true',
help="Output the JSON in a format compatible with Telegram export (implies json-per-chat)"
)
json_group.add_argument(
"--per-chat", dest="json_per_chat", default=False, action='store_true',
help="Output the JSON file per chat"
@@ -648,7 +653,7 @@ def export_json(args, data: ChatCollection, contact_store=None) -> None:
data = {jik: chat.to_json() for jik, chat in data.items()}
# Export as a single file or per chat
if not args.json_per_chat:
if not args.json_per_chat and not args.telegram:
export_single_json(args, data)
else:
export_multiple_json(args, data)
@@ -684,9 +689,13 @@ def export_multiple_json(args, data: Dict) -> None:
else:
contact = jik.replace('+', '')
if args.telegram:
obj = telegram_json_format(jik, data[jik])
else:
obj = {jik: data[jik]}
with open(f"{json_path}/{safe_name(contact)}.json", "w") as f:
file_content = json.dumps(
{jik: data[jik]},
obj,
ensure_ascii=not args.avoid_encoding_json,
indent=args.pretty_print_json
)