-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathread_messages.py
More file actions
569 lines (471 loc) · 22.9 KB
/
read_messages.py
File metadata and controls
569 lines (471 loc) · 22.9 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
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
#!/usr/bin/env python3
"""
Telegram Channel Crawler
Simple script to fetch and archive messages from Telegram channels.
Uses phone number login (no session strings needed).
"""
import asyncio
import json
import os
import sys
from datetime import datetime, timedelta, timezone
from pathlib import Path
from typing import Generator, List, TypeVar, Union
from telethon.tl.functions.users import GetFullUserRequest
class DateTimeEncoder(json.JSONEncoder):
"""Custom JSON encoder that handles datetime objects."""
def default(self, obj):
if isinstance(obj, datetime):
return obj.isoformat()
if isinstance(obj, bytes):
return obj.decode("utf-8", errors="ignore")
return super().default(obj)
from dotenv import load_dotenv
from telethon import TelegramClient
from telethon.tl.types import Message
# Load environment variables
load_dotenv()
# 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
T = TypeVar("T")
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}")
# Load TOML file (always use binary mode for tomllib/tomli)
with open(config_path, "rb") as f:
return tomllib.load(f)
def chunk_array(array: List[T], chunk_size: int) -> Generator[List[T], None, None]:
"""Split an array into chunks of the specified size."""
for i in range(0, len(array), chunk_size):
yield array[i : i + chunk_size]
def save_checkpoint(channel: int, messages: List[dict], user_info: dict, config: dict):
"""Save checkpoint data to resume processing if interrupted."""
checkpoint_dir = Path("raw/checkpoints")
checkpoint_dir.mkdir(parents=True, exist_ok=True)
checkpoint_file = checkpoint_dir / f"{channel}_checkpoint.json"
output_config = config.get("output", {})
indent_spaces = output_config.get("indent_spaces", 2)
checkpoint_data = {
"channel": channel,
"timestamp": datetime.now(timezone.utc).isoformat(),
"message_count": len(messages),
"last_message_id": messages[-1]["id"] if messages else None,
"messages": messages,
"user_info": user_info,
}
with open(checkpoint_file, "w", encoding="utf-8") as f:
json.dump(checkpoint_data, f, indent=indent_spaces, ensure_ascii=False)
print(f"💾 Checkpoint saved: {len(messages)} messages to {checkpoint_file}")
def load_checkpoint(channel: int) -> dict:
"""Load checkpoint data if it exists."""
checkpoint_file = Path("raw/checkpoints") / f"{channel}_checkpoint.json"
if checkpoint_file.exists():
with open(checkpoint_file, "r", encoding="utf-8") as f:
return json.load(f)
return None
def clear_checkpoint(channel: int):
"""Remove checkpoint file after successful completion."""
checkpoint_file = Path("raw/checkpoints") / f"{channel}_checkpoint.json"
if checkpoint_file.exists():
checkpoint_file.unlink()
print(f"🗑️ Checkpoint cleared for channel {channel}")
async def fetch_channel_messages(client: TelegramClient, channel: int, config: dict):
"""Fetch messages from a Telegram channel within the configured time window."""
crawler_config = config.get("crawler", {})
group_chats_config = config.get("group_chats", {})
# Check if channel is excluded
excluded_channels = group_chats_config.get("exclude", [])
if channel in excluded_channels:
print(f"⏭️ Skipping excluded channel: {channel}")
return {"channel": channel, "messages": [], "skipped": True}
time_window_days = crawler_config.get("time_window_days", 3)
max_messages = crawler_config.get("max_messages_per_channel", 2000)
rate_delay = crawler_config.get("rate_limiting_delay", 0.5)
batch_size = crawler_config.get(
"batch_size", 500
) # Fetch messages in batches (default 500)
checkpoint_interval = crawler_config.get(
"checkpoint_interval", 100
) # Save every N messages
offset_date = datetime.now(timezone.utc) - timedelta(days=time_window_days)
# Check for existing checkpoint
checkpoint = load_checkpoint(channel)
if checkpoint:
print(
f"📂 Found checkpoint for channel {channel} with {checkpoint['message_count']} messages"
)
print(f" Last saved: {checkpoint['timestamp']}")
resume = input(" Resume from checkpoint? (y/n): ").strip().lower()
if resume == "y":
messages_with_reactions = checkpoint["messages"]
user_info = checkpoint["user_info"]
offset_id = checkpoint["last_message_id"]
total_fetched = len(messages_with_reactions)
print(f"✅ Resuming from message ID {offset_id}")
else:
messages_with_reactions = []
user_info = {}
offset_id = 0
total_fetched = 0
clear_checkpoint(channel)
else:
messages_with_reactions = []
user_info = {} # Track user_id -> {username, first_name, last_name, photo_url, bio}
offset_id = 0
total_fetched = 0
try:
print(f"📥 Fetching messages from {channel} in batches of {batch_size}...")
print(f" ⏰ Time window: fetching messages since {offset_date.isoformat()}")
if offset_id > 0:
batch_number = (total_fetched // batch_size) + 1
else:
batch_number = 1
while total_fetched < max_messages:
# Calculate how many messages to fetch in this batch
messages_to_fetch = min(batch_size, max_messages - total_fetched)
# Fetch a batch of messages (starting from most recent, going backwards)
batch_messages = await client.get_messages(
channel,
limit=messages_to_fetch,
offset_id=offset_id,
)
if not batch_messages:
# No more messages to fetch
break
print(f" 📦 Batch {batch_number}: Fetched {len(batch_messages)} messages")
if batch_messages:
first_msg_date = (
batch_messages[0].date.isoformat()
if batch_messages[0].date
else "None"
)
last_msg_date = (
batch_messages[-1].date.isoformat()
if batch_messages[-1].date
else "None"
)
print(f" First message date: {first_msg_date}")
print(f" Last message date: {last_msg_date}")
batch_processed_count = 0
reached_time_limit = False
for idx, message in enumerate(batch_messages, 1):
# Check if message is within time window
if message.date and message.date < offset_date:
# We've gone past our time window, stop fetching
print(
f" ⏹️ Reached end of time window at message {message.id} (date: {message.date.isoformat()})"
)
print(
f" Processed {batch_processed_count} messages from this batch before time limit"
)
reached_time_limit = True
break
batch_processed_count += 1
# Collect user info from message sender
if message.from_id and hasattr(message.from_id, "user_id"):
user_id = message.from_id.user_id
if user_id not in user_info:
try:
user = await client.get_entity(user_id)
# Get profile photo URL if available
photo_url = ""
if user.photo:
try:
# Download profile photo to get the file reference
photo = await client.download_profile_photo(
user_id, file=bytes
)
if photo:
# Construct a URL-like identifier for the photo
# Note: Telegram doesn't provide direct URLs, so we store photo ID
photo_url = (
f"photo:{user.photo.photo_id}"
if hasattr(user.photo, "photo_id")
else ""
)
except Exception:
pass
# Get bio/description
bio = ""
try:
full_user = await client(GetFullUserRequest(user_id))
if full_user.full_user.about:
bio = full_user.full_user.about
except Exception:
pass
user_info[user_id] = {
"username": user.username or "",
"first_name": user.first_name or "",
"last_name": user.last_name or "",
"photo_url": photo_url,
"bio": bio,
}
except Exception:
# If we can't get user info, just skip it
pass
# Show progress for reactions fetching
if idx % 50 == 0 or idx == len(batch_messages):
print(
f" Processing reactions: {idx}/{len(batch_messages)} messages..."
)
# Fetch detailed reactions with user IDs for this message
reaction_details = []
if message.reactions and message.reactions.results:
try:
# Get message reactions with user details using GetMessageReactionsList
from telethon.tl.functions.messages import (
GetMessageReactionsListRequest,
)
for reaction_result in message.reactions.results:
emoji = (
reaction_result.reaction.emoticon
if hasattr(reaction_result.reaction, "emoticon")
else None
)
if emoji:
# Get users who reacted with this specific emoji
result = await client(
GetMessageReactionsListRequest(
peer=channel,
id=message.id,
reaction=reaction_result.reaction,
limit=100,
)
)
# Extract user IDs from the reaction list
for reaction_peer in result.reactions:
user_id = (
reaction_peer.peer_id.user_id
if hasattr(reaction_peer.peer_id, "user_id")
else None
)
if user_id:
reaction_details.append(
{"user_id": user_id, "emoji": emoji}
)
# Collect user info from reactions
if user_id not in user_info:
try:
user = await client.get_entity(user_id)
# Get profile photo URL if available
photo_url = ""
if user.photo:
try:
photo_url = (
f"photo:{user.photo.photo_id}"
if hasattr(
user.photo, "photo_id"
)
else ""
)
except Exception:
pass
# Get bio/description
bio = ""
try:
full_user = await client(
GetFullUserRequest(user_id)
)
if full_user.full_user.about:
bio = full_user.full_user.about
except Exception:
pass
user_info[user_id] = {
"username": user.username or "",
"first_name": user.first_name or "",
"last_name": user.last_name or "",
"photo_url": photo_url,
"bio": bio,
}
except Exception:
pass
except Exception as e:
# Fallback to basic reaction without user IDs if detailed fetch fails
for reaction_result in message.reactions.results:
emoji = (
reaction_result.reaction.emoticon
if hasattr(reaction_result.reaction, "emoticon")
else None
)
if emoji:
reaction_details.append(
{
"user_id": None,
"emoji": emoji,
"count": reaction_result.count,
}
)
# Convert message to simplified format immediately for checkpoint
simplified_msg = {
"id": message.id,
"date": message.date.isoformat() if message.date else None,
"from_id": message.from_id.user_id
if hasattr(message.from_id, "user_id")
else None,
"message": message.message,
"reply_to_msg_id": message.reply_to.reply_to_msg_id
if message.reply_to
else None,
"reactions": reaction_details if reaction_details else [],
"replies": message.replies.replies if message.replies else None,
}
messages_with_reactions.append(simplified_msg)
total_fetched += batch_processed_count
# Save checkpoint periodically
if checkpoint_interval > 0 and total_fetched % checkpoint_interval == 0:
save_checkpoint(channel, messages_with_reactions, user_info, config)
# If we reached the time limit, stop fetching more batches
if reached_time_limit:
break
# Rate limiting delay between batches
await asyncio.sleep(rate_delay)
# Update offset_id to the ID of the last (oldest) message in this batch
offset_id = batch_messages[-1].id
batch_number += 1
# If we got fewer messages than requested, we've reached the end
if len(batch_messages) < messages_to_fetch:
break
print(
f"✅ Fetched {len(messages_with_reactions)} messages from {channel} in {batch_number} batches"
)
print(f"👥 Collected info for {len(user_info)} unique users")
# Clear checkpoint after successful completion
clear_checkpoint(channel)
# Add post counts to user_info
return {
"channel": channel,
"messages": messages_with_reactions,
"user_info": user_info,
"skipped": False,
}
except Exception as e:
print(f"❌ Error fetching messages from {channel}: {e}")
return {"channel": channel, "messages": [], "error": str(e)}
async def save_messages(results: list, config: dict):
"""Save fetched messages to JSON files."""
output_config = config.get("output", {})
pretty_print = output_config.get("pretty_print", True)
indent_spaces = output_config.get("indent_spaces", 2)
# Create raw directory if it doesn't exist
output_dir = Path("raw")
output_dir.mkdir(parents=True, exist_ok=True)
for result in results:
# Skip excluded or errored channels
if result.get("skipped", False) or result.get("error"):
continue
# Save user info to CSV if available
user_info = result.get("user_info", {})
if user_info:
csv_filename = output_dir / f"{result['channel']}_user_ids.csv"
with open(csv_filename, "w", encoding="utf-8") as f:
f.write("user_id,username,first_name,last_name,photo_url,bio\n")
for user_id, info in sorted(user_info.items()):
username = info.get("username", "")
first_name = info.get("first_name", "").replace(",", " ")
last_name = info.get("last_name", "").replace(",", " ")
photo_url = info.get("photo_url", "")
bio = info.get("bio", "").replace(",", " ").replace("\n", " ")
f.write(
f"{user_id},{username},{first_name},{last_name},{photo_url},{bio}\n"
)
print(f"👥 Saved {len(user_info)} users to {csv_filename}")
# Messages are already in simplified format from fetch_channel_messages
serializable_messages = result["messages"]
# Save to raw directory with _messages.json suffix
filename = output_dir / f"{result['channel']}_messages.json"
indent = indent_spaces if pretty_print else None
with open(filename, "w", encoding="utf-8") as f:
json.dump(
serializable_messages,
f,
indent=indent,
ensure_ascii=False,
)
print(f"💾 Saved {len(serializable_messages)} messages to {filename}")
async def main():
"""Main entry point for the Telegram crawler."""
print("🚀 Starting Telegram Channel Crawler\n")
# Load configuration
config = load_config()
crawler_config = config.get("crawler", {})
group_chats_config = config.get("group_chats", {})
# Get environment variables
api_id = int(os.getenv("TELEGRAM_APP_ID", "0"))
api_hash = os.getenv("TELEGRAM_APP_HASH", "")
phone = os.getenv("TELEGRAM_PHONE", "")
if not api_id or not api_hash:
print("❌ Error: Missing Telegram credentials in .env file")
print("Please set TELEGRAM_APP_ID and TELEGRAM_APP_HASH")
print("\nGet your credentials from: https://my.telegram.org")
sys.exit(1)
# Get group chats to crawl (must be integers)
channels = group_chats_config.get("include", [])
if not channels:
print("❌ Error: No group chats configured in config.toml")
sys.exit(1)
# Validate that all channels are integers
for ch in channels:
if not isinstance(ch, int):
print(f"❌ Error: Channel '{ch}' is not a valid ID (must be an integer)")
print("Use 'python list_channels.py' to see your channel IDs")
sys.exit(1)
parallel_requests = crawler_config.get("parallel_requests", 3)
# Initialize Telegram client with session file
session_file = "telegram_session"
client = TelegramClient(session_file, api_id, api_hash)
try:
print("🔌 Connecting to Telegram...")
await client.start(
phone=lambda: phone
or input(
"📱 Enter your phone number (with country code, e.g., +1234567890): "
),
password=lambda: input("🔒 Enter your 2FA password (if enabled): "),
code_callback=lambda: input("💬 Enter the code Telegram sent you: "),
)
if not await client.is_user_authorized():
print("❌ Authorization failed. Please try again.")
sys.exit(1)
me = await client.get_me()
print(f"✅ Connected as: {me.first_name} (@{me.username or 'no username'})\n")
# Process channels in parallel batches
all_results = []
for chunk in chunk_array(channels, parallel_requests):
tasks = [
fetch_channel_messages(client, channel, config) for channel in chunk
]
results = await asyncio.gather(*tasks, return_exceptions=True)
# Separate successful results from errors
for result in results:
if isinstance(result, Exception):
print(f"❌ Error: {result}")
else:
all_results.append(result)
# Save all messages
print()
await save_messages(all_results, config)
print("\n✅ Crawling complete!")
except Exception as e:
print(f"❌ Fatal error: {e}")
sys.exit(1)
finally:
if client.is_connected():
await client.disconnect()
print("🔌 Disconnected from Telegram")
if __name__ == "__main__":
try:
asyncio.run(main())
except KeyboardInterrupt:
print("\n⚠️ Interrupted by user")
sys.exit(0)
except Exception as e:
print(f"❌ Error: {e}")
sys.exit(1)