-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrss-filter-notify.py
More file actions
executable file
·1076 lines (889 loc) · 34.4 KB
/
Copy pathrss-filter-notify.py
File metadata and controls
executable file
·1076 lines (889 loc) · 34.4 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
#!/usr/bin/env python3
import argparse
import json
import os
import random
import re
import signal
import sys
import time
from collections import defaultdict
from datetime import timezone
import feedparser
import prettytable
import requests
from dateutil import parser as dtparser
# === CONFIGURATION ===
HAMMER_DELAY_RANGE = (2, 4) # Seconds between requests
cache_file = ""
regex_file = ""
channels_file = ""
telegram_dispatch = True
webhook_dispatch = True
# ANSI color codes
ANSI_BLUE = "\033[94m"
ANSI_YELLOW = "\033[93m"
ANSI_GREEN = "\033[92m"
ANSI_RED = "\033[91m"
ANSI_GREY = "\033[90m"
ANSI_RESET = "\033[0m"
# === GLOBALS ===
message_queue = []
# === FUNCTIONS ===
def handle_signal(signum, frame):
print(f"Received signal {signum}, exiting.")
sys.exit(0)
signal.signal(signal.SIGINT, handle_signal)
signal.signal(signal.SIGTERM, handle_signal)
def ensure_dir(directory):
if not os.path.exists(directory):
os.makedirs(directory)
def load_json(file_path, default):
if not os.path.exists(file_path):
return default
with open(file_path, "r") as f:
return json.load(f)
def save_json(file_path, data):
with open(file_path, "w") as f:
json.dump(data, f, indent=2)
def load_config(config_file):
config = load_json(config_file, {})
while not config:
edit_config(config_file)
return config
def edit_config(config_file):
config = load_json(config_file, {})
b_token = config.get("telegram_bot_token", None)
if b_token:
print(f"Existing bot token: {b_token}")
res = input("Enter your new Telegram bot token: ").strip()
if res:
config["telegram_bot_token"] = res
else:
print("Skip empty input")
b_id = config.get("telegram_chat_id", None)
if b_id:
print(f"Existing chat ID: {b_id}")
res = input("Enter your new Telegram chat ID (@username or ID): ").strip()
if res:
config["telegram_chat_id"] = res
else:
print("Skip empty input")
w_url = config.get("webhook_url", None)
if w_url:
print(f"Existing webhook URL: {w_url}")
res = input("Enter your new webhook URL: ").strip()
if res:
config["webhook_url"] = res
else:
print("Skip empty input")
save_json(config_file, config)
print("Configuration updated.")
def load_channels(channels_file, skip_add=False):
channels = load_json(channels_file, [])
if (not channels) and (not skip_add):
print("No channels found. Let's add one.")
interactive_add_channel(channels_file)
channels = load_json(channels_file, [])
return channels
def save_channels(channels_file, channels):
save_json(channels_file, sorted(channels, key=lambda x: x.get("url", "")))
def load_cache(cache_file):
return load_json(cache_file, {})
def save_cache(cache_file, cache):
save_json(cache_file, cache)
def get_latest_videos(channel_url: str, playlist_end=None):
feed = feedparser.parse(channel_url)
if feed.bozo:
print(f"{ANSI_RED}RSS parse error:{ANSI_RESET}", feed.bozo_exception)
return [], None
entries = feed.entries or []
if playlist_end is not None:
entries = entries[:playlist_end]
entries = list(reversed(entries))
channel_title = getattr(feed.feed, "title", None)
return entries, channel_title
def get_video_upload_date(video):
dt_str = (
dtparser.parse(video.get("published"))
.astimezone(timezone.utc)
.strftime("%Y-%m-%dT%H:%M:%SZ")
)
return dt_str
def matches_filters(info, criteria):
title = info.get("title", "").lower()
description = info.get("description", "").lower()
url = info.get("url") or info.get("link") or ""
title_includes = criteria.get("title_include", [])
if title_includes and not any(word.lower() in title for word in title_includes):
return False
title_excludes = criteria.get("title_exclude", [])
if any(word.lower() in title for word in title_excludes):
return False
desc_includes = criteria.get("description_include", [])
if desc_includes and not any(word.lower() in description for word in desc_includes):
return False
desc_excludes = criteria.get("description_exclude", [])
if any(word.lower() in description for word in desc_excludes):
return False
url_includes = criteria.get("url_include", [])
if url_includes and not any(word.lower() in url for word in url_includes):
return False
url_excludes = criteria.get("url_exclude", [])
if any(word in url for word in url_excludes):
return False
return True
def process_message_queue():
# Group messages by datecode
grouped_messages = defaultdict(list)
for datecode, text, dry_run in message_queue:
grouped_messages[datecode].append((text, dry_run))
# Process messages sorted by datecode
for datecode in sorted(grouped_messages):
for text, dry_run in grouped_messages[datecode]:
send_webhook_message(text, dry_run=dry_run)
send_telegram_message(text, dry_run=dry_run)
message_queue.clear()
def send_telegram_message(text, dry_run=False):
if not telegram_dispatch:
return
config = load_config(config_file)
bot_token = config["telegram_bot_token"]
chat_id = config["telegram_chat_id"]
if dry_run:
print(
f"\n\t{ANSI_BLUE}[Dry-Run] Notification: {ANSI_RESET}\n{text}\n\t{ANSI_BLUE}[End]{ANSI_RESET}\n"
)
return
else:
print(f"{ANSI_GREEN}Sending Notifiation: {ANSI_RESET} {text}")
url = f"https://api.telegram.org/bot{bot_token}/sendMessage"
payload = {"chat_id": chat_id, "text": text, "disable_web_page_preview": False}
retries = 0
max_retries = 3
while retries <= max_retries:
response = requests.post(url, json=payload)
if response.status_code == 200:
break
elif response.status_code == 429:
try:
retry_after = response.json().get("parameters", {}).get("retry_after")
if retry_after is None:
print(
f"{ANSI_RED}Rate limit encountered, but retry_after missing. Exiting.{ANSI_RESET}"
)
sys.exit(1)
print(
f"{ANSI_YELLOW}Rate limited by Telegram. Retrying after {retry_after} seconds...{ANSI_RESET}"
)
time.sleep(retry_after + 2)
retries += 1
except (ValueError, KeyError, json.JSONDecodeError):
print(
f"{ANSI_RED}Rate limit encountered, but failed to parse retry_after. Exiting.{ANSI_RESET}"
)
sys.exit(1)
else:
print(
f"{ANSI_RED}Failed to send Telegram message (HTTP {response.status_code}):{ANSI_RESET} {response.text}"
)
sys.exit(1)
if retries > max_retries:
print(f"{ANSI_RED}Exceeded maximum retries. Exiting.{ANSI_RESET}")
sys.exit(1)
time.sleep(1)
def send_webhook_message(text, dry_run=False):
if not webhook_dispatch:
return
config = load_config(config_file)
webhook_url = config["webhook_url"]
if dry_run:
print(
f"\n\t{ANSI_BLUE}[Dry-Run] Webhook Notification: {ANSI_RESET}\n{text}\n\t{ANSI_BLUE}[End]{ANSI_RESET}\n"
)
return
else:
print(f"{ANSI_GREEN}Sending Webhook Notification: {ANSI_RESET} {text}")
payload = {"message": text}
retries = 0
max_retries = 3
while retries <= max_retries:
try:
response = requests.post(webhook_url, json=payload)
except requests.RequestException as e:
print(
f"{ANSI_RED}Request error while sending webhook message: {e}{ANSI_RESET}"
)
sys.exit(1)
if response.status_code == 200 or response.status_code == 204:
break
elif response.status_code == 429:
try:
retry_after = int(response.headers.get("Retry-After", 5))
print(
f"{ANSI_YELLOW}Rate limited by webhook. Retrying after {retry_after} seconds...{ANSI_RESET}"
)
time.sleep(retry_after + 1)
retries += 1
except (ValueError, KeyError):
print(
f"{ANSI_RED}Rate limit encountered, but failed to parse Retry-After. Exiting.{ANSI_RESET}"
)
sys.exit(1)
else:
print(
f"{ANSI_RED}Failed to send webhook message (HTTP {response.status_code}):{ANSI_RESET} {response.text}"
)
sys.exit(1)
if retries > max_retries:
print(f"{ANSI_RED}Exceeded maximum retries. Exiting.{ANSI_RESET}")
sys.exit(1)
time.sleep(1)
def print_channel_settings(channel):
url = channel.get("url", "N/A")
playlist_end = channel.get("playlist_end", "N/A")
criteria = channel.get("criteria", {})
url_regex = channel.get("url_regex")
print(f"\n{ANSI_GREEN}Channel URL:{ANSI_RESET} {url}")
print(f"{ANSI_GREEN}Playlist End:{ANSI_RESET} {playlist_end}")
if criteria:
print(f"{ANSI_GREEN}Filter Criteria:{ANSI_RESET}")
for key, value in criteria.items():
print(f" {key}: {value}")
else:
print(f"{ANSI_GREEN}Filter Criteria:{ANSI_RESET} None")
if url_regex:
pattern, replacement = url_regex
print(f"{ANSI_GREEN}URL Regex Pattern:{ANSI_RESET} {pattern}")
print(f"{ANSI_GREEN}URL Regex Replacement:{ANSI_RESET} {replacement}")
else:
print(f"{ANSI_GREEN}URL Regex:{ANSI_RESET} None")
def preview_recent_videos(
url, criteria, playlist_end, url_regex=None, skip_result=False
):
print("\nFetching recent videos to preview matches...")
videos, cname = get_latest_videos(url, playlist_end=playlist_end)
if not videos:
print("No videos found or error fetching.")
return None, None
table = prettytable.PrettyTable()
if skip_result:
table.field_names = ["Title", "URL"]
else:
table.field_names = ["Title", "Result", "URL"]
table.max_width["URL"] = 60
table.max_width["Title"] = 70
table.hrules = prettytable.HRuleStyle.ALL
for video in videos:
reason = explain_skip_reason(video, criteria)
raw_title = video.get("title") or "N/A"
video_url = video.get("url") or video.get("link") or ""
modified_url = video_url
if url_regex:
try:
pattern, repl = url_regex
modified_url = re.sub(pattern, repl, video_url)
except Exception as e:
modified_url = f"Regex error: {e}"
title_lines = [raw_title[i : i + 60] for i in range(0, len(raw_title), 60)]
if reason == "Matched" and not skip_result:
colored_title_lines = [
f"{ANSI_GREEN}{line}{ANSI_RESET}" for line in title_lines
]
else:
if "title" in reason.lower() and not skip_result:
colored_title_lines = [
f"{ANSI_RED}{line}{ANSI_RESET}" for line in title_lines
]
else:
colored_title_lines = title_lines
color_title = "\n".join(colored_title_lines)
if url_regex:
url_display = f"{ANSI_RED}IN:{ANSI_RESET}{video_url}\n{ANSI_GREEN}OUT:{ANSI_RESET}{modified_url}"
else:
url_display = f"{video_url}"
if skip_result:
table.add_row([color_title, url_display])
else:
table.add_row([color_title, reason, url_display])
print("\nRecent videos analysis:")
print(table)
return videos, cname
def explain_skip_reason(info, criteria):
reasons = []
title = info.get("title", "").lower()
description = info.get("description", "").lower()
url = info.get("url") or info.get("link") or ""
title_includes = criteria.get("title_include", [])
if title_includes and not any(word.lower() in title for word in title_includes):
reasons.append(f"Title missing: {title_includes}")
title_excludes = criteria.get("title_exclude", [])
if any(word.lower() in title for word in title_excludes):
reasons.append(f"Title contains: {title_excludes}")
desc_includes = criteria.get("description_include", [])
if desc_includes and not any(word.lower() in description for word in desc_includes):
reasons.append(f"Description missing: {desc_includes}")
desc_excludes = criteria.get("description_exclude", [])
if any(word.lower() in description for word in desc_excludes):
reasons.append(f"Description contains: {desc_excludes}")
url_includes = criteria.get("url_include", [])
if url_includes and not any(word.lower() in url for word in url_includes):
reasons.append(f"URL missing: {url_includes}")
url_excludes = criteria.get("url_exclude", [])
if any(word in url for word in url_excludes):
reasons.append(f"URL contains: {url_excludes}")
return "\n".join(reasons) if reasons else "Matched"
def load_regex_presets(presets_file):
return load_json(presets_file, {})
def save_regex_presets(presets_file, presets):
save_json(presets_file, presets)
def interactive_edit_regex_presets(presets_file):
presets = load_regex_presets(presets_file)
while True:
print("\nCurrent Presets:")
for idx, (name, (pattern, replacement)) in enumerate(presets.items()):
print(
f"[{idx}] {name} =>\n\tpattern: {pattern},\n\treplacement: {replacement}"
)
action = (
input("\nSelect action: (a=add new, e=edit existing, d=delete, q=quit): ")
.strip()
.lower()
)
if action == "a":
name = input("Enter new preset name: ").strip()
if name in presets:
print(f"{ANSI_RED}Preset already exists.{ANSI_RESET}")
continue
pattern = input("Enter regex pattern: ").strip()
replacement = input("Enter replacement string: ").strip()
presets[name] = [pattern, replacement]
save_regex_presets(presets_file, presets)
print(f"{ANSI_GREEN}Preset '{name}' added.{ANSI_RESET}")
elif action == "e":
try:
idx = int(input("Enter preset number to edit: ").strip())
name = list(presets.keys())[idx]
print(f"Editing preset: {name}")
pattern = input(
f"Enter new regex pattern (leave blank to keep '{presets[name][0]}'): "
).strip()
replacement = input(
f"Enter new replacement string (leave blank to keep '{presets[name][1]}'): "
).strip()
if pattern:
presets[name][0] = pattern
if replacement:
presets[name][1] = replacement
save_regex_presets(presets_file, presets)
print(f"{ANSI_GREEN}Preset '{name}' updated.{ANSI_RESET}")
except (ValueError, IndexError):
print(f"{ANSI_RED}Invalid selection.{ANSI_RESET}")
elif action == "d":
try:
idx = int(input("Enter preset number to delete: ").strip())
name = list(presets.keys())[idx]
confirm = (
input(f"Are you sure you want to delete preset '{name}'? (y/n): ")
.strip()
.lower()
)
if confirm == "y":
del presets[name]
save_regex_presets(presets_file, presets)
print(f"{ANSI_GREEN}Preset '{name}' deleted.{ANSI_RESET}")
except (ValueError, IndexError):
print(f"{ANSI_RED}Invalid selection.{ANSI_RESET}")
elif action == "q":
print("Exiting regex preset editor.")
break
else:
print(f"{ANSI_RED}Unknown action.{ANSI_RESET}")
def choose_url_regex():
presets = load_regex_presets(regex_file)
channels = load_channels(channels_file, skip_add=True)
while True:
print("\nChoose URL regex option:")
print("[1] Pick from presets")
print("[2] Enter manually")
print("[3] Edit presets")
print("[4] Import from existing channel")
print("[5] Cancel / None")
choice = input("Select option (1-5): ").strip()
if choice == "1":
if not presets:
print(f"{ANSI_RED}No presets available.{ANSI_RESET}")
continue
print("\nAvailable Presets:")
for idx, (name, (pattern, replacement)) in enumerate(presets.items()):
print(
f"[{idx}] {name} =>\n\tpattern: {pattern},\n\treplacement: {replacement}"
)
try:
idx = int(input("Select preset number: ").strip())
name = list(presets.keys())[idx]
pattern, replacement = presets[name]
return [pattern, replacement]
except (ValueError, IndexError):
print(f"{ANSI_RED}Invalid selection.{ANSI_RESET}")
continue
elif choice == "2":
pattern = input("Enter regex pattern to match in URL: ").strip()
replacement = input("Enter replacement string: ").strip()
return [pattern, replacement]
elif choice == "3":
interactive_edit_regex_presets(regex_file)
presets = load_regex_presets(regex_file) # Reload after editing
elif choice == "4":
if not channels:
print(f"{ANSI_RED}No saved channels found.{ANSI_RESET}")
continue
print("\nSaved Channels:")
for idx, chan in enumerate(channels):
print(f"[{idx}] {chan.get('url', 'UNKNOWN')}")
try:
idx = int(input("Select channel number to import from: ").strip())
selected = channels[idx]
if selected.get("url_regex"):
print(
f"{ANSI_GREEN}Imported regex from channel:{ANSI_RESET} {selected.get('url')}"
)
return selected["url_regex"]
else:
print(
f"{ANSI_RED}Selected channel has no URL regex configured.{ANSI_RESET}"
)
except (ValueError, IndexError):
print(f"{ANSI_RED}Invalid selection.{ANSI_RESET}")
elif choice == "5":
return "", ""
else:
print(f"{ANSI_RED}Unknown option.{ANSI_RESET}")
def interactive_add_channel(channels_file):
criteria = {}
playlist_end = 25
url_regex = None
while True:
url = input("Enter the channel URL: ").strip()
videos, discarded = preview_recent_videos(
url, criteria, playlist_end, url_regex, skip_result=True
)
if videos:
break
else:
if (
input("Error downloading videos. Enter a different URL? (y/n): ")
.strip()
.lower()
!= "y"
):
sys.exit(0)
try:
playlist_end = int(
input("How many videos to pull during scan (max)? (e.g., 25): ").strip()
)
except ValueError:
print("Invalid input, defaulting to 25.")
while True:
if input("Filter by title includes? (y/n): ").strip().lower() == "y":
title_includes = input("Enter title keywords (comma separated): ").strip()
criteria["title_include"] = (
[word.strip() for word in title_includes.split(",")]
if title_includes
else []
)
else:
criteria.pop("title_include", None)
if input("Filter by title excludes? (y/n): ").strip().lower() == "y":
title_excludes = input(
"Enter title exclude keywords (comma separated): "
).strip()
criteria["title_exclude"] = (
[word.strip() for word in title_excludes.split(",")]
if title_excludes
else []
)
else:
criteria.pop("title_exclude", None)
if input("Filter by description includes? (y/n): ").strip().lower() == "y":
desc_includes = input(
"Enter description keywords (comma separated): "
).strip()
criteria["description_include"] = (
[word.strip() for word in desc_includes.split(",")]
if desc_includes
else []
)
else:
criteria.pop("description_include", None)
if input("Filter by description excludes? (y/n): ").strip().lower() == "y":
desc_excludes = input(
"Enter description exclude keywords (comma separated): "
).strip()
criteria["description_exclude"] = (
[word.strip() for word in desc_excludes.split(",")]
if desc_excludes
else []
)
else:
criteria.pop("description_exclude", None)
if input("Filter by URL includes? (y/n): ").strip().lower() == "y":
url_includes = input("Enter URL keywords (comma separated): ").strip()
criteria["url_include"] = (
[word.strip() for word in url_includes.split(",")]
if url_includes
else []
)
else:
criteria.pop("url_include", None)
if input("Filter by URL excludes? (y/n): ").strip().lower() == "y":
url_excludes = input(
"Enter URL exclude keywords (comma separated): "
).strip()
criteria["url_exclude"] = (
[word.strip() for word in url_excludes.split(",")]
if url_excludes
else []
)
else:
criteria.pop("url_exclude", None)
if (
input("Do you want to set a URL regex replacement? (y/n): ").strip().lower()
== "y"
):
url_regex = choose_url_regex()
videos, discarded = preview_recent_videos(
url, criteria, playlist_end, url_regex, skip_result=False
)
channel = {
"url": url,
"criteria": criteria,
"playlist_end": playlist_end,
"url_regex": url_regex,
}
print_channel_settings(channel)
confirm = (
input(
"Are you happy with these filters? (y to accept, n to edit again, q to cancel): "
)
.strip()
.lower()
)
if confirm == "y":
channels = load_channels(channels_file, skip_add=True)
channels.append(channel)
save_channels(channels_file, channels)
print("Channel added.")
if (
input("Would you like to run notifications for this channel? (y/n): ")
.strip()
.lower()
== "y"
):
run_channel(
channel,
dry_run=False,
suppress_skip_msgs=False,
seen_during_dry_run=False,
)
process_message_queue()
return
elif confirm == "q":
print("Canceled.")
return
else:
print("Let's edit the filters again.\n")
def interactive_edit_channel(channels_file):
channels = load_channels(channels_file)
if not channels:
print("No channels to edit.")
return
print("\nCurrent Channels:")
for idx, chan in enumerate(channels):
print(f"[{idx}] {chan.get('url', 'UNKNOWN')}")
try:
selection = int(input("\nSelect channel to edit (by number): ").strip())
channel = channels[selection]
except (ValueError, IndexError):
print("Invalid selection.")
return
channel_url = channel.get("url")
criteria = channel.get("criteria", {})
playlist_end = channel.get("playlist_end", 25)
current_regex = channel.get("url_regex")
print(f"\nEditing: {channel_url}")
videos, discarded = preview_recent_videos(
channel_url, criteria, playlist_end, current_regex
)
print_channel_settings(channel)
confirm = (
input(
"Do you wish to edit these filters? (y to edit, anything else to cancel): "
)
.strip()
.lower()
)
if confirm != "y":
return
while True:
try:
new_end = input(
f"Current playlist_end={playlist_end}. Enter new value or leave blank to keep: "
).strip()
if new_end:
channel["playlist_end"] = int(new_end)
playlist_end = channel["playlist_end"]
except ValueError:
print("Invalid number. Keeping old playlist_end.")
fields = [
("title_include", list),
("title_exclude", list),
("description_include", list),
("description_exclude", list),
("url_include", list),
("url_exclude", list),
]
for field, ftype in fields:
current = criteria.get(field, [] if ftype is list else 0)
print(f"\nCurrent {field}: {current}")
action = (
input("Modify? (s=set, a=append, c=clear, n=none): ").strip().lower()
)
if action == "s":
if ftype is list:
entries = input("Enter comma-separated values: ").strip()
criteria[field] = [
e.strip() for e in entries.split(",") if e.strip()
]
else:
try:
criteria[field] = int(input("Enter new value: ").strip())
except ValueError:
print("Invalid input. Skipping.")
elif action == "a" and ftype is list:
entries = input("Enter comma-separated values to append: ").strip()
criteria.setdefault(field, []).extend(
[e.strip() for e in entries.split(",") if e.strip()]
)
elif action == "c":
criteria[field] = [] if ftype is list else 0
elif action == "n":
pass
else:
print("Unknown action, skipping.")
channel["criteria"] = criteria
print(f"\nCurrent URL regex: {current_regex}")
action = (
input("Modify URL regex? (s=set new, c=clear, n=none): ").strip().lower()
)
if action == "s":
while True:
pattern, replacement = choose_url_regex()
if videos:
print("\nSample URL previews with your regex:")
for sample_video in videos:
original_url = (
sample_video.get("url") or sample_video.get("link") or ""
)
modified_url = original_url
try:
modified_url = re.sub(pattern, replacement, original_url)
except Exception as e:
print(f"{ANSI_RED}Regex error:{ANSI_RESET} {e}")
print(f"Original: {original_url}")
print(f"Modified: {modified_url}\n")
confirm = (
input(
"Are you happy with this regex? (y to accept, n to re-enter): "
)
.strip()
.lower()
)
if confirm == "y":
channel["url_regex"] = [pattern, replacement]
break
else:
print("Let's re-enter the regex.\n")
elif action == "c":
channel["url_regex"] = None
preview_recent_videos(channel_url, criteria, playlist_end, current_regex)
print_channel_settings(channel)
confirm = (
input(
"Are you happy with these filters? (y to save, e to edit again, n to abort): "
)
.strip()
.lower()
)
if confirm == "y":
channels[selection] = channel
save_channels(channels_file, channels)
print("Channel updated.")
if (
input("Would you like to run notifications for this channel? (y/n): ")
.strip()
.lower()
== "y"
):
run_channel(
channel,
dry_run=False,
suppress_skip_msgs=False,
seen_during_dry_run=False,
)
process_message_queue()
break
elif confirm == "n":
print("Canceled changes.")
break
else:
print("Let's edit again.\n")
def run_all_channels(
channels_file, dry_run=False, suppress_skip_msgs=False, seen_during_dry_run=False
):
channels = load_channels(channels_file)
for channel in channels:
run_channel(channel, dry_run, suppress_skip_msgs, seen_during_dry_run)
time.sleep(random.randint(*HAMMER_DELAY_RANGE))
def run_channel(
channel, dry_run=False, suppress_skip_msgs=False, seen_during_dry_run=False
):
channel_url = channel.get("url")
criteria = channel.get("criteria", {})
playlist_end = channel.get("playlist_end", 25)
url_regex = channel.get("url_regex")
seen_videos = load_cache(cache_file)
if not channel_url:
return
print(f"{ANSI_GREEN}Checking channel:{ANSI_RESET} {channel_url}")
videos, cname = get_latest_videos(channel_url, playlist_end=playlist_end)
channel_cache = set(seen_videos.get(channel_url, []))
for video in videos:
video_id = video["id"]
if video_id in channel_cache:
if not suppress_skip_msgs:
print(
f"{ANSI_GREY}Already seen:{ANSI_RESET} {video_id} -- {video['title']}"
)
continue
if matches_filters(video, criteria):
video_url = video.get("url") or video.get("link", "")
if url_regex:
try:
pattern, repl = url_regex
video_url = re.sub(pattern, repl, video_url)
except Exception as e:
print(f"{ANSI_RED}Failed applying URL regex:{ANSI_RESET} {e}")
upload_date = (
get_video_upload_date(video)
or video.get("upload_date")
or video.get("published")
)
message = f"{cname} :: {upload_date} :: {video['title']}\n\n{video_url}"
message_queue.append((upload_date, message, dry_run))
print(
f"{ANSI_BLUE}Queued notifications for:{ANSI_RESET} {video_id} -- {video['title']}"
)
if seen_during_dry_run or not dry_run:
channel_cache.add(video_id)
else:
if not suppress_skip_msgs:
print(
f"{ANSI_YELLOW}Not matched:{ANSI_RESET} {video_id} -- {ANSI_GREY}{video['title']}{ANSI_RESET}"
)
seen_videos[channel_url] = list(channel_cache)
save_cache(cache_file, seen_videos)
return
def chunked_sleep(total_seconds, check_interval=3):
slept = 0
while slept < total_seconds:
time.sleep(min(check_interval, total_seconds - slept))
slept += check_interval
# === MAIN ===
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="yt-dlp channel monitor and Telegram notifier."
)
parser.add_argument(
"mode",
nargs="?",
choices=["run", "add", "edit", "regex", "dry-run", "config"],
default="run",
help="Operation mode.",
)
parser.add_argument(
"--data-dir",
type=str,
default=".",
help="Directory to store config, channels and cache files.",
)
parser.add_argument(
"--interval-hours",
type=float,
default=0.0,