forked from ThBroth/telegram-scraper
-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy pathtelegram_scraper_with_forwarding.py
More file actions
2386 lines (1999 loc) · 98.7 KB
/
Copy pathtelegram_scraper_with_forwarding.py
File metadata and controls
2386 lines (1999 loc) · 98.7 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
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import sqlite3
import json
import csv
import asyncio
import time
import sys
import uuid
import warnings
from dataclasses import dataclass
from typing import Dict, List, Optional, Any
from pathlib import Path
from io import StringIO
from telethon import TelegramClient, events
from telethon.tl.types import MessageMediaPhoto, MessageMediaDocument, MessageMediaWebPage, User, PeerChannel, Channel, Chat
from telethon.errors import FloodWaitError, SessionPasswordNeededError
import re
import qrcode
warnings.filterwarnings("ignore", message="Using async sessions support is an experimental feature")
# Optional proxy support - install with: pip install pysocks python-socks[asyncio]
try:
import socks
PROXY_SUPPORT = True
except ImportError:
PROXY_SUPPORT = False
def display_ascii_art():
WHITE = "\033[97m"
RESET = "\033[0m"
art = r"""
___________________ _________
\__ ___/ _____/ / _____/
| | / \ ___ \_____ \
| | \ \_\ \/ \
|____| \______ /_______ /
\/ \/
"""
print(WHITE + art + RESET)
@dataclass
class MessageData:
message_id: int
date: str
sender_id: int
first_name: Optional[str]
last_name: Optional[str]
username: Optional[str]
message: str
media_type: Optional[str]
media_path: Optional[str]
reply_to: Optional[int]
post_author: Optional[str]
views: Optional[int]
forwards: Optional[int]
reactions: Optional[str]
@dataclass
class ForwardingRule:
source_channel: str
destination_channel: str
forward_text: bool = True
forward_images: bool = True
forward_videos: bool = True
forward_documents: bool = True
forward_mode: str = "copy"
enabled: bool = True
class OptimizedTelegramScraper:
def __init__(self):
self.STATE_FILE = 'state.json'
self.state = self.load_state()
self.client = None
self.continuous_scraping_active = False
self.forwarding_active = False
self.max_concurrent_downloads = 5
self.batch_size = 100
self.state_save_interval = 50
self.db_connections = {}
self.forwarding_handler = None
def load_state(self) -> Dict[str, Any]:
if os.path.exists(self.STATE_FILE):
try:
with open(self.STATE_FILE, 'r') as f:
return json.load(f)
except:
pass
return {
'api_id': None,
'api_hash': None,
'channels': {},
'channel_names': {},
'scrape_media': True,
'forwarding_rules': [],
'proxy': None,
}
def save_state(self):
try:
with open(self.STATE_FILE, 'w') as f:
json.dump(self.state, f, indent=2)
except Exception as e:
print(f"Failed to save state: {e}")
def get_forwarding_rules(self) -> List[ForwardingRule]:
rules = []
for rule_dict in self.state.get('forwarding_rules', []):
rules.append(ForwardingRule(
source_channel=rule_dict['source_channel'],
destination_channel=rule_dict['destination_channel'],
forward_text=rule_dict.get('forward_text', True),
forward_images=rule_dict.get('forward_images', True),
forward_videos=rule_dict.get('forward_videos', True),
forward_documents=rule_dict.get('forward_documents', True),
forward_mode=rule_dict.get('forward_mode', 'copy'),
enabled=rule_dict.get('enabled', True)
))
return rules
def save_forwarding_rule(self, rule: ForwardingRule):
rule_dict = {
'source_channel': rule.source_channel,
'destination_channel': rule.destination_channel,
'forward_text': rule.forward_text,
'forward_images': rule.forward_images,
'forward_videos': rule.forward_videos,
'forward_documents': rule.forward_documents,
'forward_mode': rule.forward_mode,
'enabled': rule.enabled
}
existing_idx = None
for i, existing in enumerate(self.state.get('forwarding_rules', [])):
if (existing['source_channel'] == rule.source_channel and
existing['destination_channel'] == rule.destination_channel):
existing_idx = i
break
if existing_idx is not None:
self.state['forwarding_rules'][existing_idx] = rule_dict
else:
if 'forwarding_rules' not in self.state:
self.state['forwarding_rules'] = []
self.state['forwarding_rules'].append(rule_dict)
self.save_state()
def remove_forwarding_rule(self, index: int) -> bool:
if 0 <= index < len(self.state.get('forwarding_rules', [])):
del self.state['forwarding_rules'][index]
self.save_state()
return True
return False
def get_db_connection(self, channel: str) -> sqlite3.Connection:
if channel not in self.db_connections:
channel_dir = Path(channel)
channel_dir.mkdir(exist_ok=True)
db_file = channel_dir / f'{channel}.db'
conn = sqlite3.connect(str(db_file), check_same_thread=False, timeout=30)
conn.execute('''CREATE TABLE IF NOT EXISTS messages
(id INTEGER PRIMARY KEY, message_id INTEGER UNIQUE, date TEXT,
sender_id INTEGER, first_name TEXT, last_name TEXT, username TEXT,
message TEXT, media_type TEXT, media_path TEXT, reply_to INTEGER,
post_author TEXT, views INTEGER, forwards INTEGER, reactions TEXT)''')
conn.execute('CREATE INDEX IF NOT EXISTS idx_message_id ON messages(message_id)')
conn.execute('CREATE INDEX IF NOT EXISTS idx_date ON messages(date)')
conn.execute('PRAGMA journal_mode=WAL')
conn.execute('PRAGMA synchronous=NORMAL')
conn.commit()
self.migrate_database(conn)
self.db_connections[channel] = conn
return self.db_connections[channel]
def migrate_database(self, conn: sqlite3.Connection):
cursor = conn.cursor()
cursor.execute("PRAGMA table_info(messages)")
columns = {row[1] for row in cursor.fetchall()}
migrations = []
if 'post_author' not in columns:
migrations.append('ALTER TABLE messages ADD COLUMN post_author TEXT')
if 'views' not in columns:
migrations.append('ALTER TABLE messages ADD COLUMN views INTEGER')
if 'forwards' not in columns:
migrations.append('ALTER TABLE messages ADD COLUMN forwards INTEGER')
if 'reactions' not in columns:
migrations.append('ALTER TABLE messages ADD COLUMN reactions TEXT')
for migration in migrations:
try:
conn.execute(migration)
except:
pass
if migrations:
conn.commit()
def close_db_connections(self):
for conn in self.db_connections.values():
conn.close()
self.db_connections.clear()
def batch_insert_messages(self, channel: str, messages: List[MessageData]):
if not messages:
return
conn = self.get_db_connection(channel)
data = [(msg.message_id, msg.date, msg.sender_id, msg.first_name,
msg.last_name, msg.username, msg.message, msg.media_type,
msg.media_path, msg.reply_to, msg.post_author, msg.views,
msg.forwards, msg.reactions) for msg in messages]
conn.executemany('''INSERT OR IGNORE INTO messages
(message_id, date, sender_id, first_name, last_name, username,
message, media_type, media_path, reply_to, post_author, views,
forwards, reactions)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)''', data)
conn.commit()
async def download_media(self, channel: str, message) -> Optional[str]:
if not message.media or not self.state['scrape_media']:
return None
if isinstance(message.media, MessageMediaWebPage):
return None
try:
channel_dir = Path(channel)
media_folder = channel_dir / 'media'
media_folder.mkdir(exist_ok=True)
if isinstance(message.media, MessageMediaPhoto):
original_name = getattr(message.file, 'name', None) or "photo.jpg"
ext = "jpg"
elif isinstance(message.media, MessageMediaDocument):
ext = getattr(message.file, 'ext', 'bin') if message.file else 'bin'
original_name = getattr(message.file, 'name', None) or f"document.{ext}"
else:
return None
base_name = Path(original_name).stem
extension = Path(original_name).suffix or f".{ext}"
unique_filename = f"{message.id}-{base_name}{extension}"
media_path = media_folder / unique_filename
existing_files = list(media_folder.glob(f"{message.id}-*"))
if existing_files:
return str(existing_files[0])
for attempt in range(3):
try:
downloaded_path = await message.download_media(file=str(media_path))
if downloaded_path and Path(downloaded_path).exists():
return downloaded_path
else:
return None
except FloodWaitError as e:
if attempt < 2:
await asyncio.sleep(e.seconds)
else:
return None
except Exception:
if attempt < 2:
await asyncio.sleep(2 ** attempt)
else:
return None
return None
except Exception:
return None
async def update_media_path(self, channel: str, message_id: int, media_path: str):
conn = self.get_db_connection(channel)
conn.execute('UPDATE messages SET media_path = ? WHERE message_id = ?',
(media_path, message_id))
conn.commit()
def should_forward_message(self, message, rule: ForwardingRule) -> bool:
if not rule.enabled:
return False
if not message.media:
return rule.forward_text and bool(message.message)
if isinstance(message.media, MessageMediaWebPage):
return rule.forward_text and bool(message.message)
if isinstance(message.media, MessageMediaPhoto):
return rule.forward_images
if isinstance(message.media, MessageMediaDocument):
if message.file:
mime_type = getattr(message.file, 'mime_type', '') or ''
if mime_type.startswith('video/'):
return rule.forward_videos
else:
return rule.forward_documents
return rule.forward_documents
return False
async def forward_message(self, message, rule: ForwardingRule, source_channel_id: int = None):
try:
if rule.destination_channel.lstrip('-').isdigit():
dest_entity = await self.client.get_entity(PeerChannel(int(rule.destination_channel)))
else:
dest_entity = await self.client.get_entity(rule.destination_channel)
if rule.forward_mode == "forward":
await self.client.forward_messages(dest_entity, message)
print(f" Forwarded message {message.id}")
else:
source_name = self.state.get('channel_names', {}).get(rule.source_channel, '')
if source_channel_id:
full_id = f"-100{abs(source_channel_id)}" if not str(source_channel_id).startswith('-100') else str(source_channel_id)
else:
full_id = rule.source_channel
if source_name and source_name != 'no_username':
source_line = f"From: @{source_name} ({full_id})\n─────────────────\n"
else:
source_line = f"From: {full_id}\n─────────────────\n"
copy_text = source_line + (message.message or '')
if message.media and not isinstance(message.media, MessageMediaWebPage):
await self.client.send_message(
dest_entity,
copy_text,
file=message.media
)
else:
await self.client.send_message(dest_entity, copy_text)
print(f" Copied message {message.id}")
return True
except FloodWaitError as e:
print(f" Rate limited, waiting {e.seconds}s...")
await asyncio.sleep(e.seconds)
return await self.forward_message(message, rule, source_channel_id)
except Exception as e:
print(f" Failed to forward message {message.id}: {e}")
return False
async def setup_forwarding_handler(self):
rules = self.get_forwarding_rules()
if not rules:
print("No forwarding rules configured")
return False
enabled_rules = [r for r in rules if r.enabled]
if not enabled_rules:
print("No enabled forwarding rules")
return False
source_channels = []
source_id_map = {}
for rule in enabled_rules:
try:
if rule.source_channel.lstrip('-').isdigit():
channel_id = int(rule.source_channel)
else:
entity = await self.client.get_entity(rule.source_channel)
channel_id = entity.id
source_channels.append(channel_id)
source_id_map[channel_id] = rule.source_channel
except Exception as e:
print(f"Failed to get entity for {rule.source_channel}: {e}")
if not source_channels:
print("No valid source channels")
return False
@self.client.on(events.NewMessage(chats=source_channels, incoming=True, outgoing=True))
async def forwarding_handler(event):
message = event.message
chat_id = event.chat_id
for rule in enabled_rules:
rule_source_id = None
if rule.source_channel.lstrip('-').isdigit():
rule_source_id = int(rule.source_channel)
else:
rule_source_id = next((k for k, v in source_id_map.items() if v == rule.source_channel), None)
if rule_source_id == chat_id:
if self.should_forward_message(message, rule):
source_name = self.state.get('channel_names', {}).get(rule.source_channel, rule.source_channel)
dest_name = self.state.get('channel_names', {}).get(rule.destination_channel, rule.destination_channel)
print(f"\n[{time.strftime('%H:%M:%S')}] New message in {source_name} -> forwarding to {dest_name}")
await self.forward_message(message, rule, chat_id)
self.forwarding_handler = forwarding_handler
return True
async def start_forwarding(self):
self.forwarding_active = True
if not self.client.is_connected():
await self.client.connect()
if not await self.setup_forwarding_handler():
self.forwarding_active = False
return
rules = self.get_forwarding_rules()
enabled_rules = [r for r in rules if r.enabled]
print(f"\nForwarding service started!")
print(f" Monitoring {len(enabled_rules)} rule(s)")
print(" Press Ctrl+C to stop\n")
for rule in enabled_rules:
source_name = self.state.get('channel_names', {}).get(rule.source_channel, rule.source_channel)
dest_name = self.state.get('channel_names', {}).get(rule.destination_channel, rule.destination_channel)
content_types = []
if rule.forward_text: content_types.append("text")
if rule.forward_images: content_types.append("images")
if rule.forward_videos: content_types.append("videos")
if rule.forward_documents: content_types.append("documents")
print(f" - {source_name} -> {dest_name}")
print(f" Mode: {rule.forward_mode} | Content: {', '.join(content_types)}")
print("\nWatching for new messages...\n")
try:
await self.client.run_until_disconnected()
except asyncio.CancelledError:
pass
except ConnectionError:
print("\nConnection lost. Returning to menu...")
except Exception as e:
print(f"\nForwarding stopped: {e}")
finally:
self.forwarding_active = False
print("\nForwarding service stopped")
async def manage_forwarding_rules(self):
while True:
print("\n" + "="*45)
print(" FORWARDING RULES MANAGER")
print("="*45)
rules = self.get_forwarding_rules()
if rules:
print("\nCurrent Rules:")
for i, rule in enumerate(rules, 1):
source_name = self.state.get('channel_names', {}).get(rule.source_channel, rule.source_channel)
dest_name = self.state.get('channel_names', {}).get(rule.destination_channel, rule.destination_channel)
status = "✅" if rule.enabled else "❌"
content_types = []
if rule.forward_text: content_types.append("T")
if rule.forward_images: content_types.append("I")
if rule.forward_videos: content_types.append("V")
if rule.forward_documents: content_types.append("D")
print(f" [{i}] {status} {source_name} → {dest_name}")
print(f" Mode: {rule.forward_mode} | Content: {'/'.join(content_types)}")
else:
print("\nNo forwarding rules configured")
print("\n[A] Add new rule")
print("[E] Edit rule")
print("[T] Toggle rule on/off")
print("[D] Delete rule")
print("[S] Start forwarding")
print("[H] Backfill historical messages")
print("[B] Back to main menu")
print("="*45)
choice = input("Enter your choice: ").lower().strip()
if choice == 'a':
await self.add_forwarding_rule_interactive()
elif choice == 'e':
await self.edit_forwarding_rule_interactive()
elif choice == 't':
await self.toggle_forwarding_rule()
elif choice == 'd':
await self.delete_forwarding_rule_interactive()
elif choice == 's':
if not rules or not any(r.enabled for r in rules):
print("❌ No enabled forwarding rules. Add or enable rules first.")
continue
try:
await self.start_forwarding()
except KeyboardInterrupt:
self.forwarding_active = False
print("\nForwarding stopped")
elif choice == 'h':
await self.backfill_forwarding_interactive()
elif choice == 'b':
break
else:
print("Invalid option")
async def add_forwarding_rule_interactive(self):
print("\n📝 ADD NEW FORWARDING RULE")
print("-" * 40)
await self.view_channels()
if not self.state['channels']:
print("\n❌ No channels available. Add channels first using [L] in the main menu.")
return
channels_list = list(self.state['channels'].keys())
print("\n1️⃣ Select SOURCE channel (messages will be forwarded FROM here):")
source_input = input("Enter channel number or ID: ").strip()
source_channels = self.parse_channel_selection(source_input)
if not source_channels:
print("❌ Invalid source channel selection")
return
source_channel = source_channels[0]
print("\n2️⃣ Select DESTINATION channel (messages will be forwarded TO here):")
print(" You can enter a channel number from the list, or a channel username (@channelname)")
dest_input = input("Enter channel number, ID, or @username: ").strip()
if dest_input.startswith('@'):
dest_channel = dest_input
else:
# First try parsing as a channel from the tracked list
dest_channels = self.parse_channel_selection(dest_input)
if dest_channels:
dest_channel = dest_channels[0]
else:
# If not in tracked list, try as a raw channel ID (for destination-only channels)
try:
if dest_input.lstrip('-').isdigit():
test_id = int(dest_input)
# Try to resolve the channel via Telethon to verify it exists
try:
entity = await self.client.get_entity(PeerChannel(test_id))
dest_channel = dest_input
print(f"✅ Found channel: {getattr(entity, 'title', dest_input)}")
except Exception:
print(f"❌ Could not access channel ID {dest_input}. Make sure this account is a member.")
return
else:
print("❌ Invalid destination channel selection")
return
except ValueError:
print("❌ Invalid destination channel selection")
return
print("\n3️⃣ Select content types to forward:")
print(" [1] Text messages")
print(" [2] Images/Photos")
print(" [3] Videos")
print(" [4] Documents/Files")
print(" [A] All types")
print(" Example: 1,2,3 or A for all")
content_input = input("Enter selection: ").strip().lower()
if content_input == 'a':
forward_text = forward_images = forward_videos = forward_documents = True
else:
selections = [x.strip() for x in content_input.split(',')]
forward_text = '1' in selections
forward_images = '2' in selections
forward_videos = '3' in selections
forward_documents = '4' in selections
if not any([forward_text, forward_images, forward_videos, forward_documents]):
print("❌ You must select at least one content type")
return
print("\n4️⃣ Select forwarding mode:")
print(" [1] Copy - Send as new message (no 'Forwarded from' header)")
print(" [2] Forward - Keep 'Forwarded from' header")
mode_input = input("Enter 1 or 2: ").strip()
forward_mode = "forward" if mode_input == '2' else "copy"
rule = ForwardingRule(
source_channel=source_channel,
destination_channel=dest_channel,
forward_text=forward_text,
forward_images=forward_images,
forward_videos=forward_videos,
forward_documents=forward_documents,
forward_mode=forward_mode,
enabled=True
)
self.save_forwarding_rule(rule)
source_name = self.state.get('channel_names', {}).get(source_channel, source_channel)
dest_name = dest_channel if dest_channel.startswith('@') else self.state.get('channel_names', {}).get(dest_channel, dest_channel)
print(f"\n✅ Forwarding rule created!")
print(f" {source_name} → {dest_name}")
content_types = []
if forward_text: content_types.append("text")
if forward_images: content_types.append("images")
if forward_videos: content_types.append("videos")
if forward_documents: content_types.append("documents")
print(f" Content: {', '.join(content_types)}")
print(f" Mode: {forward_mode}")
async def edit_forwarding_rule_interactive(self):
rules = self.get_forwarding_rules()
if not rules:
print("No rules to edit")
return
try:
idx = int(input("Enter rule number to edit: ")) - 1
if not (0 <= idx < len(rules)):
print("Invalid rule number")
return
except ValueError:
print("Invalid input")
return
rule = rules[idx]
print(f"\nEditing rule {idx + 1}:")
print("Press Enter to keep current value\n")
print("Current content types:")
print(f" Text: {'Yes' if rule.forward_text else 'No'}")
print(f" Images: {'Yes' if rule.forward_images else 'No'}")
print(f" Videos: {'Yes' if rule.forward_videos else 'No'}")
print(f" Documents: {'Yes' if rule.forward_documents else 'No'}")
update_content = input("\nUpdate content types? (y/n): ").lower().strip()
if update_content == 'y':
print("Enter 1,2,3,4 or A for all:")
print(" [1] Text [2] Images [3] Videos [4] Documents")
content_input = input("Selection: ").strip().lower()
if content_input == 'a':
rule.forward_text = rule.forward_images = rule.forward_videos = rule.forward_documents = True
elif content_input:
selections = [x.strip() for x in content_input.split(',')]
rule.forward_text = '1' in selections
rule.forward_images = '2' in selections
rule.forward_videos = '3' in selections
rule.forward_documents = '4' in selections
print(f"\nCurrent mode: {rule.forward_mode}")
print(" [1] Copy [2] Forward")
mode_input = input("New mode (or Enter to keep): ").strip()
if mode_input == '1':
rule.forward_mode = 'copy'
elif mode_input == '2':
rule.forward_mode = 'forward'
self.save_forwarding_rule(rule)
print("✅ Rule updated!")
async def toggle_forwarding_rule(self):
rules = self.get_forwarding_rules()
if not rules:
print("No rules to toggle")
return
try:
idx = int(input("Enter rule number to toggle: ")) - 1
if not (0 <= idx < len(rules)):
print("Invalid rule number")
return
except ValueError:
print("Invalid input")
return
rule = rules[idx]
rule.enabled = not rule.enabled
self.save_forwarding_rule(rule)
status = "enabled" if rule.enabled else "disabled"
print(f"✅ Rule {idx + 1} {status}")
async def delete_forwarding_rule_interactive(self):
rules = self.get_forwarding_rules()
if not rules:
print("No rules to delete")
return
try:
idx = int(input("Enter rule number to delete: ")) - 1
if not (0 <= idx < len(rules)):
print("Invalid rule number")
return
except ValueError:
print("Invalid input")
return
confirm = input(f"Delete rule {idx + 1}? (y/n): ").lower().strip()
if confirm == 'y':
if self.remove_forwarding_rule(idx):
print("✅ Rule deleted")
else:
print("❌ Failed to delete rule")
async def backfill_forwarding_interactive(self):
rules = self.get_forwarding_rules()
if not rules:
print("No forwarding rules configured. Add a rule first.")
return
print("\n" + "="*45)
print(" BACKFILL FORWARDING")
print("="*45)
print("\nThis will forward historical messages from your")
print("scraped database through an existing forwarding rule.\n")
for i, rule in enumerate(rules, 1):
source_name = self.state.get('channel_names', {}).get(rule.source_channel, rule.source_channel)
dest_name = self.state.get('channel_names', {}).get(rule.destination_channel, rule.destination_channel)
status = "✅" if rule.enabled else "❌"
content_types = []
if rule.forward_text: content_types.append("T")
if rule.forward_images: content_types.append("I")
if rule.forward_videos: content_types.append("V")
if rule.forward_documents: content_types.append("D")
print(f" [{i}] {status} {source_name} → {dest_name}")
print(f" Mode: {rule.forward_mode} | Content: {'/'.join(content_types)}")
try:
idx = int(input("\nSelect rule number to backfill: ")) - 1
if not (0 <= idx < len(rules)):
print("Invalid rule number")
return
except ValueError:
print("Invalid input")
return
rule = rules[idx]
source_channel = rule.source_channel
# Check that we have scraped data for the source channel
if source_channel not in self.state['channels']:
print(f"❌ No scraped data for source channel {source_channel}")
print(" Scrape this channel first, then backfill.")
return
conn = self.get_db_connection(source_channel)
cursor = conn.cursor()
# Show date range of available data
cursor.execute('SELECT MIN(date), MAX(date), COUNT(*) FROM messages')
row = cursor.fetchone()
if not row or row[2] == 0:
print(f"❌ No messages in database for this channel. Scrape first.")
return
min_date, max_date, total_count = row
print(f"\n📊 Available data:")
print(f" Date range: {min_date} → {max_date}")
print(f" Total messages: {total_count}")
# Date range filter
print(f"\n📅 Enter date range to backfill (YYYY-MM-DD format)")
print(f" Press Enter to use the full range")
start_input = input(f" Start date [{min_date[:10]}]: ").strip()
start_date = start_input if start_input else min_date[:10]
end_input = input(f" End date [{max_date[:10]}]: ").strip()
end_date = end_input if end_input else max_date[:10]
# Validate dates
try:
from datetime import datetime
datetime.strptime(start_date, '%Y-%m-%d')
datetime.strptime(end_date, '%Y-%m-%d')
except ValueError:
print("❌ Invalid date format. Use YYYY-MM-DD")
return
# Count matching messages
cursor.execute('''SELECT COUNT(*) FROM messages
WHERE date >= ? AND date < date(?, '+1 day')''',
(start_date, end_date))
match_count = cursor.fetchone()[0]
if match_count == 0:
print("❌ No messages found in that date range")
return
# Rate limit configuration
print(f"\n⚡ Rate limiting:")
print(f" Delay between messages (seconds). Higher = safer from bans.")
print(f" Recommended: 1-3 for small batches, 3-5 for large ones.")
delay_input = input(f" Delay [{2 if match_count < 500 else 4}s]: ").strip()
try:
delay = float(delay_input) if delay_input else (2 if match_count < 500 else 4)
delay = max(0.5, delay) # Floor at 0.5s
except ValueError:
delay = 2
source_name = self.state.get('channel_names', {}).get(rule.source_channel, rule.source_channel)
dest_name = self.state.get('channel_names', {}).get(rule.destination_channel, rule.destination_channel)
print(f"\n{'='*45}")
print(f" Rule: {source_name} → {dest_name}")
print(f" Range: {start_date} → {end_date}")
print(f" Messages: {match_count}")
print(f" Delay: {delay}s per message")
est_minutes = (match_count * delay) / 60
print(f" Est time: ~{est_minutes:.1f} minutes")
print(f"{'='*45}")
confirm = input("\nProceed with backfill? (y/n): ").lower().strip()
if confirm != 'y':
print("Backfill cancelled")
return
await self.run_backfill(rule, source_channel, start_date, end_date, delay)
async def run_backfill(self, rule: ForwardingRule, source_channel: str,
start_date: str, end_date: str, delay: float):
conn = self.get_db_connection(source_channel)
cursor = conn.cursor()
# Determine which messages to forward based on rule content type filters
conditions = ["date >= ?", "date < date(?, '+1 day')"]
params = [start_date, end_date]
media_conditions = []
if rule.forward_text:
media_conditions.append("(media_type IS NULL AND message != '')")
media_conditions.append("(media_type = 'MessageMediaWebPage' AND message != '')")
if rule.forward_images:
media_conditions.append("media_type = 'MessageMediaPhoto'")
if rule.forward_videos:
media_conditions.append("(media_type = 'MessageMediaDocument' AND media_path LIKE '%.mp4')")
media_conditions.append("(media_type = 'MessageMediaDocument' AND media_path LIKE '%.mov')")
media_conditions.append("(media_type = 'MessageMediaDocument' AND media_path LIKE '%.avi')")
media_conditions.append("(media_type = 'MessageMediaDocument' AND media_path LIKE '%.mkv')")
media_conditions.append("(media_type = 'MessageMediaDocument' AND media_path LIKE '%.webm')")
if rule.forward_documents:
if not rule.forward_videos:
media_conditions.append("(media_type = 'MessageMediaDocument')")
else:
# Documents but exclude videos already matched above
media_conditions.append("(media_type = 'MessageMediaDocument' AND (media_path IS NULL OR (media_path NOT LIKE '%.mp4' AND media_path NOT LIKE '%.mov' AND media_path NOT LIKE '%.avi' AND media_path NOT LIKE '%.mkv' AND media_path NOT LIKE '%.webm')))")
if not media_conditions:
print("❌ Rule has no content types enabled")
return
conditions.append(f"({' OR '.join(media_conditions)})")
query = f"SELECT message_id FROM messages WHERE {' AND '.join(conditions)} ORDER BY date ASC"
cursor.execute(query, params)
message_ids = [row[0] for row in cursor.fetchall()]
if not message_ids:
print("❌ No matching messages found for this rule's content filters")
return
total = len(message_ids)
print(f"\n🚀 Starting backfill of {total} messages...")
# Get the source entity for fetching full messages from Telegram
try:
if source_channel.lstrip('-').isdigit():
entity = await self.client.get_entity(PeerChannel(int(source_channel)))
else:
entity = await self.client.get_entity(source_channel)
except Exception as e:
print(f"❌ Failed to get source channel entity: {e}")
return
forwarded = 0
failed = 0
skipped = 0
# Process in batches to avoid holding too many messages in memory
batch_size = 20
for i in range(0, total, batch_size):
batch_ids = message_ids[i:i + batch_size]
try:
messages = await self.client.get_messages(entity, ids=batch_ids)
except FloodWaitError as e:
print(f"\n⏳ Rate limited, waiting {e.seconds}s...")
await asyncio.sleep(e.seconds)
messages = await self.client.get_messages(entity, ids=batch_ids)
except Exception as e:
print(f"\n❌ Failed to fetch batch: {e}")
failed += len(batch_ids)
continue
for msg in messages:
if not msg:
skipped += 1
continue
try:
success = await self.forward_message(msg, rule, int(source_channel) if source_channel.lstrip('-').isdigit() else None)
if success:
forwarded += 1
else:
failed += 1
except Exception as e:
failed += 1
# Progress bar
done = forwarded + failed + skipped
progress = (done / total) * 100
bar_length = 30
filled_length = int(bar_length * done // total)
bar = '█' * filled_length + '░' * (bar_length - filled_length)
sys.stdout.write(f"\r📤 Backfill: [{bar}] {progress:.1f}% ({done}/{total}) | ✅{forwarded} ❌{failed} ⏭{skipped}")
sys.stdout.flush()
# Rate limit delay
await asyncio.sleep(delay)
print(f"\n\n{'='*45}")
print(f" BACKFILL COMPLETE")
print(f" Forwarded: {forwarded}")
print(f" Failed: {failed}")
print(f" Skipped: {skipped} (deleted messages)")
print(f"{'='*45}")
async def scrape_channel(self, channel: str, offset_id: int):
try:
if not self.client.is_connected():
await self.client.connect()
entity = await self.client.get_entity(PeerChannel(int(channel)) if channel.startswith('-') else channel)
result = await self.client.get_messages(entity, offset_id=offset_id, reverse=True, limit=0)
total_messages = result.total
if total_messages == 0:
print(f"No messages found in channel {channel}")
return
print(f"Found {total_messages} messages in channel {channel}")
message_batch = []
media_tasks = []
processed_messages = 0
last_message_id = offset_id
semaphore = asyncio.Semaphore(self.max_concurrent_downloads)
async for message in self.client.iter_messages(entity, offset_id=offset_id, reverse=True):
try:
sender = await message.get_sender()
reactions_str = None
if message.reactions and message.reactions.results:
reactions_parts = []
for reaction in message.reactions.results:
emoji = getattr(reaction.reaction, 'emoticon', '')
count = reaction.count
if emoji:
reactions_parts.append(f"{emoji} {count}")
if reactions_parts:
reactions_str = ' '.join(reactions_parts)
msg_data = MessageData(
message_id=message.id,
date=message.date.strftime('%Y-%m-%d %H:%M:%S'),
sender_id=message.sender_id,
first_name=getattr(sender, 'first_name', None) if isinstance(sender, User) else None,
last_name=getattr(sender, 'last_name', None) if isinstance(sender, User) else None,
username=getattr(sender, 'username', None) if isinstance(sender, User) else None,
message=message.message or '',
media_type=message.media.__class__.__name__ if message.media else None,
media_path=None,
reply_to=message.reply_to_msg_id if message.reply_to else None,
post_author=message.post_author,
views=message.views,
forwards=message.forwards,
reactions=reactions_str
)
message_batch.append(msg_data)
if self.state['scrape_media'] and message.media and not isinstance(message.media, MessageMediaWebPage):
media_tasks.append(message)
last_message_id = message.id
processed_messages += 1
if len(message_batch) >= self.batch_size:
self.batch_insert_messages(channel, message_batch)
message_batch.clear()
if processed_messages % self.state_save_interval == 0:
self.state['channels'][channel] = last_message_id
self.save_state()
progress = (processed_messages / total_messages) * 100