-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathimport_metadata_to_db.py
More file actions
520 lines (423 loc) · 15.6 KB
/
import_metadata_to_db.py
File metadata and controls
520 lines (423 loc) · 15.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
#!/usr/bin/env python3
"""
Import Metadata to PostgreSQL (Messages, Reactions, Users, Channels)
Imports messages from raw/[channel_id]_messages.json files into PostgreSQL database.
Also imports reactions from those messages, users from CSV files, and channel metadata from raw/channels.json.
Usage:
python3 import_metadata_to_db.py # Import all channels from config
python3 import_metadata_to_db.py --channel 123456 # Import specific channel
python3 import_metadata_to_db.py --dry-run # Show what would be imported without inserting
Requirements:
- psycopg2 (install with: pip install psycopg2-binary)
- Environment variable: DATABASE_URL (e.g., postgresql://user:pass@localhost:5432/dbname)
Database schema:
See schemas/messages.sql, schemas/reactions.sql, schemas/users.sql, and schemas/channels.sql
"""
import argparse
import csv
import json
import os
import sys
from pathlib import Path
import psycopg2
from dotenv import load_dotenv
from psycopg2.extras import execute_values
# Use built-in tomllib for Python 3.11+, fallback to tomli for older versions
if sys.version_info >= (3, 11):
import tomllib
else:
try:
import tomli as tomllib
except ImportError:
import toml as tomllib
# Load environment variables from .env file
load_dotenv()
def load_config():
"""Load configuration from config.toml"""
config_path = Path(__file__).parent / "config.toml"
if not config_path.exists():
raise FileNotFoundError(f"Config file not found: {config_path}")
with open(config_path, "rb") as f:
return tomllib.load(f)
def get_db_connection():
"""Get database connection from DATABASE_URL environment variable."""
database_url = os.getenv("DATABASE_URL")
if not database_url:
raise ValueError("DATABASE_URL environment variable is required")
return psycopg2.connect(database_url)
def collect_messages_and_reactions(messages, channel_id):
"""
Recursively collect all messages and reactions from the JSON structure.
Args:
messages: List of message objects from JSON
channel_id: Channel ID for these messages
Returns:
tuple: (list of message tuples, list of reaction tuples)
"""
all_messages = []
all_reactions = []
def process_message(msg):
"""Process a single message and its nested replies."""
msg_id = msg.get("id")
from_id = msg.get("from_id")
date = msg.get("date")
message_text = msg.get("message")
reply_to_msg_id = msg.get("reply_to_msg_id")
# Skip messages without required fields
if msg_id is None or date is None:
return
# Only add messages that have from_id (skip channel announcements)
if from_id is not None:
# Add message tuple: (id, channel_id, date, from_id, message, reply_to_msg_id)
all_messages.append(
(msg_id, channel_id, date, from_id, message_text, reply_to_msg_id)
)
# Process reactions
reactions = msg.get("reactions", [])
for reaction in reactions:
user_id = reaction.get("user_id")
emoji = reaction.get("emoji")
# Skip aggregated reactions (user_id is null for channels)
if user_id is None:
continue
# Add reaction tuple: (channel_id, message_id, user_id, emoji, date)
all_reactions.append(
(
channel_id,
msg_id,
user_id,
emoji,
date, # Use message date as reaction date (Telegram doesn't provide reaction timestamp)
)
)
# Always process nested replies (even if parent has no from_id, like channel posts)
replies_data = msg.get("replies_data", [])
for reply in replies_data:
process_message(reply)
# Process all top-level messages
for msg in messages:
process_message(msg)
return all_messages, all_reactions
def collect_users_from_csv(channel_id):
"""
Collect users and admins from CSV files.
Args:
channel_id: Channel ID
Returns:
list of user tuples: (channel_id, user_id, username, first_name, last_name, bio, photo_id, is_admin)
"""
users_file = Path("raw") / f"{channel_id}_user_ids.csv"
admins_file = Path("raw") / f"{channel_id}_admins.csv"
users_dict = {} # user_id -> user data
admin_ids = set()
# Load admins first
if admins_file.exists():
with open(admins_file, "r", encoding="utf-8") as f:
reader = csv.DictReader(f)
for row in reader:
user_id = row.get("user_id")
if user_id:
admin_ids.add(int(user_id))
# Load users
if users_file.exists():
with open(users_file, "r", encoding="utf-8") as f:
reader = csv.DictReader(f)
for row in reader:
user_id = row.get("user_id")
if not user_id:
continue
user_id = int(user_id)
username = row.get("username") or None
first_name = row.get("first_name") or None
last_name = row.get("last_name") or None
bio = row.get("bio") or None
# Parse photo_id from photo_url (format: "photo:123456")
photo_url = row.get("photo_url") or ""
photo_id = None
if photo_url.startswith("photo:"):
try:
photo_id = int(photo_url.split(":")[1])
except (ValueError, IndexError):
pass
is_admin = user_id in admin_ids
users_dict[user_id] = (
int(channel_id),
user_id,
username,
first_name,
last_name,
bio,
photo_id,
is_admin,
)
# Add any admins that weren't in the users file
for admin_id in admin_ids:
if admin_id not in users_dict:
users_dict[admin_id] = (
int(channel_id),
admin_id,
None, # username
None, # first_name
None, # last_name
None, # bio
None, # photo_id
True, # is_admin
)
return list(users_dict.values())
def load_channels_metadata():
"""
Load channel metadata from raw/channels.json.
Returns:
dict: channel_id -> channel data
"""
channels_file = Path("raw") / "channels.json"
if not channels_file.exists():
return {}
with open(channels_file, "r", encoding="utf-8") as f:
channels_list = json.load(f)
return {ch["channel_id"]: ch for ch in channels_list}
def import_channels(conn, channel_ids, channels_metadata, dry_run=False):
"""
Import channel metadata to database.
Args:
conn: Database connection
channel_ids: List of channel IDs to import
channels_metadata: Dict of channel_id -> channel data
dry_run: If True, don't actually insert data
Returns:
int: Number of channels imported
"""
channels_to_import = []
for channel_id in channel_ids:
channel_id_int = int(channel_id)
if channel_id_int in channels_metadata:
ch = channels_metadata[channel_id_int]
channels_to_import.append(
(
channel_id_int,
ch.get("name"),
ch.get("username"),
ch.get("is_group", False),
)
)
if not channels_to_import:
return 0
if dry_run:
return len(channels_to_import)
cursor = conn.cursor()
try:
execute_values(
cursor,
"""
INSERT INTO trank.channels (channel_id, name, username, is_group)
VALUES %s
ON CONFLICT (channel_id) DO UPDATE SET
name = EXCLUDED.name,
username = EXCLUDED.username,
is_group = EXCLUDED.is_group,
updated_at = NOW()
""",
channels_to_import,
)
conn.commit()
except Exception as e:
conn.rollback()
raise e
finally:
cursor.close()
return len(channels_to_import)
def import_channel(conn, channel_id, dry_run=False):
"""
Import messages, reactions, and users for a single channel.
Args:
conn: Database connection
channel_id: Channel ID to import
dry_run: If True, don't actually insert data
Returns:
tuple: (messages_count, reactions_count, users_count)
"""
messages_file = Path("raw") / f"{channel_id}_messages.json"
if not messages_file.exists():
print(f" ⚠️ Messages file not found: {messages_file}")
return 0, 0, 0
print(f" 📂 Loading messages from: {messages_file}")
with open(messages_file, "r", encoding="utf-8") as f:
messages = json.load(f)
# Collect all messages and reactions
all_messages, all_reactions = collect_messages_and_reactions(
messages, int(channel_id)
)
# Collect users from CSV files
all_users = collect_users_from_csv(channel_id)
print(
f" 📊 Found {len(all_messages)} messages, {len(all_reactions)} reactions, and {len(all_users)} users"
)
if dry_run:
print(f" 🔍 Dry run - no data inserted")
return len(all_messages), len(all_reactions), len(all_users)
cursor = conn.cursor()
try:
# Insert messages using ON CONFLICT to handle duplicates
if all_messages:
print(f" 💾 Inserting messages...")
execute_values(
cursor,
"""
INSERT INTO trank.messages (id, channel_id, date, from_id, message, reply_to_msg_id)
VALUES %s
ON CONFLICT (channel_id, id) DO UPDATE SET
date = EXCLUDED.date,
from_id = EXCLUDED.from_id,
message = EXCLUDED.message,
reply_to_msg_id = EXCLUDED.reply_to_msg_id
""",
all_messages,
page_size=1000,
)
# Insert reactions using ON CONFLICT to handle duplicates
if all_reactions:
print(f" 💾 Inserting reactions...")
execute_values(
cursor,
"""
INSERT INTO trank.message_reactions (channel_id, message_id, user_id, emoji, date)
VALUES %s
ON CONFLICT (channel_id, message_id, user_id, emoji) DO NOTHING
""",
all_reactions,
page_size=1000,
)
# Insert users using ON CONFLICT to handle duplicates
if all_users:
print(f" 💾 Inserting users...")
execute_values(
cursor,
"""
INSERT INTO trank.channel_users (channel_id, user_id, username, first_name, last_name, bio, photo_id, is_admin)
VALUES %s
ON CONFLICT (channel_id, user_id) DO UPDATE SET
username = EXCLUDED.username,
first_name = EXCLUDED.first_name,
last_name = EXCLUDED.last_name,
bio = EXCLUDED.bio,
photo_id = EXCLUDED.photo_id,
is_admin = EXCLUDED.is_admin
""",
all_users,
page_size=1000,
)
conn.commit()
print(
f" ✅ Successfully imported {len(all_messages)} messages, {len(all_reactions)} reactions, and {len(all_users)} users"
)
except Exception as e:
conn.rollback()
print(f" ❌ Error importing data: {e}")
raise
finally:
cursor.close()
return len(all_messages), len(all_reactions), len(all_users)
def main():
"""Main entry point."""
parser = argparse.ArgumentParser(
description="Import messages and reactions to PostgreSQL database"
)
parser.add_argument(
"--channel",
type=str,
help="Specific channel ID to import (otherwise imports all from config)",
)
parser.add_argument(
"--dry-run",
action="store_true",
help="Show what would be imported without actually inserting",
)
args = parser.parse_args()
print("📥 Import Messages and Reactions to PostgreSQL\n")
# Determine which channels to process
if args.channel:
channels = [args.channel]
print(f"Processing specific channel: {args.channel}")
else:
# Load from config
try:
config = load_config()
except FileNotFoundError as e:
print(f"❌ Error: {e}")
sys.exit(1)
group_chats = config.get("group_chats", {}).get("include", [])
channels_list = config.get("channels", {}).get("include", [])
channels = [str(ch) for ch in group_chats + channels_list]
if not channels:
print("❌ Error: No channels configured in config.toml")
sys.exit(1)
print(f"Found {len(channels)} channel(s) in config.toml")
if args.dry_run:
print("Mode: Dry run (no data will be inserted)\n")
else:
print()
# Connect to database
try:
conn = get_db_connection()
print("✅ Connected to database\n")
except Exception as e:
print(f"❌ Error connecting to database: {e}")
sys.exit(1)
# Load channel metadata
channels_metadata = load_channels_metadata()
if channels_metadata:
print(
f"📋 Loaded metadata for {len(channels_metadata)} channels from raw/channels.json\n"
)
else:
print(
"⚠️ No raw/channels.json found - run 'python list_channels.py' to generate it\n"
)
total_messages = 0
total_reactions = 0
total_users = 0
total_channels = 0
try:
for channel_id in channels:
print(f"{'=' * 60}")
print(f"Channel: {channel_id}")
print(f"{'=' * 60}")
messages_count, reactions_count, users_count = import_channel(
conn, channel_id, dry_run=args.dry_run
)
total_messages += messages_count
total_reactions += reactions_count
total_users += users_count
print()
# Import channel metadata
if channels_metadata:
print(f"{'=' * 60}")
print("Importing channel metadata")
print(f"{'=' * 60}")
total_channels = import_channels(
conn, channels, channels_metadata, dry_run=args.dry_run
)
print(f" ✅ Imported {total_channels} channel(s)\n")
finally:
conn.close()
print(f"{'=' * 60}")
print("📊 Summary")
print(f"{'=' * 60}")
print(f" Total channels: {total_channels}")
print(f" Total messages: {total_messages}")
print(f" Total reactions: {total_reactions}")
print(f" Total users: {total_users}")
if args.dry_run:
print(" (Dry run - no data was inserted)")
print()
if __name__ == "__main__":
try:
main()
except KeyboardInterrupt:
print("\n⚠️ Interrupted by user")
sys.exit(0)
except Exception as e:
print(f"❌ Error: {e}")
import traceback
traceback.print_exc()
sys.exit(1)