-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathwatchguard_bot.py
More file actions
5885 lines (4856 loc) · 189 KB
/
watchguard_bot.py
File metadata and controls
5885 lines (4856 loc) · 189 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 json
import logging
import re
import asyncio
import os
from datetime import datetime
from typing import Dict, Tuple, Optional, List
import pytz
from dateutil.parser import parse as parse_date
from apscheduler.schedulers.asyncio import AsyncIOScheduler
from apscheduler.triggers.cron import CronTrigger
from telegram import Bot, InlineKeyboardMarkup, InlineKeyboardButton, Update, BotCommand
from telegram.ext import (
Application,
ApplicationBuilder,
CommandHandler,
CallbackQueryHandler,
MessageHandler,
filters,
ContextTypes,
ConversationHandler,
ApplicationHandlerStop,
)
from data_manager import get_shared_data_manager, DataChangeEvent
def load_config() -> Dict:
try:
with open("config.json", "r") as f:
return json.load(f)
except FileNotFoundError:
logging.error("config.json not found! Please configure the bot first.")
return {}
def load_bot_config():
try:
config = load_config()
return config.get("TOKEN"), config.get("CHAT_IDS", [])
except Exception as e:
print(f"Error loading bot config: {e}")
return None, []
TOKEN, CHAT_ID = load_bot_config()
SERVERS_FILE = "servers.json"
DOMAINS_FILE = "domains.json"
SETTINGS_FILE = "settings.json"
TIMEZONE = "Asia/Tehran"
shared_dm = get_shared_data_manager()
STATUS_INDICATORS = {
"expired": "🔴",
"warning": "🟡",
"safe": "🟢",
"unknown": "⚪",
}
EMOJI_OPTIONS = [
"🇺🇸",
"🇬🇧",
"🇩🇪",
"🇫🇷",
"🇨🇦",
"🇦🇺",
"🇮🇹",
"🇪🇸",
"🇳🇱",
"🇸🇪",
"🇷🇺",
"🇨🇳",
"🇯🇵",
"🇰🇷",
"🇧🇷",
"🇮🇳",
"🇹🇷",
"🇫🇮",
"🇳🇴",
"🇩🇰",
]
LABEL_OPTIONS = []
(
SELECT_REMOVE,
SELECT_EDIT,
EDIT_NAME,
EDIT_DATE,
EDIT_PRICE,
EDIT_CURRENCY,
EDIT_EMOJI,
EDIT_CUSTOM_EMOJI,
EDIT_LABEL,
EDIT_CUSTOM_LABEL,
EDIT_DATACENTER,
ADD_NAME,
ADD_DATE,
ADD_PRICE,
ADD_CURRENCY,
ADD_EMOJI,
ADD_CUSTOM_EMOJI,
ADD_LABEL,
ADD_CUSTOM_LABEL,
ADD_DATACENTER,
SETTINGS_MENU,
SETTINGS_WARNING_DAYS,
SETTINGS_NOTIFICATION_TIME,
FILTER_STATUS,
DOMAIN_SELECT_REMOVE,
DOMAIN_SELECT_EDIT,
DOMAIN_EDIT_NAME,
DOMAIN_EDIT_DATE,
DOMAIN_EDIT_PRICE,
DOMAIN_EDIT_CURRENCY,
DOMAIN_EDIT_REGISTRAR,
DOMAIN_ADD_NAME,
DOMAIN_ADD_DATE,
DOMAIN_ADD_PRICE,
DOMAIN_ADD_CURRENCY,
DOMAIN_ADD_REGISTRAR,
DOMAIN_ADD_LABEL,
DOMAIN_ADD_CUSTOM_LABEL,
EXPIRED_SERVER_ACTION,
EXPIRED_DOMAIN_ACTION,
MANAGE_LABELS,
ADD_LABEL_NAME,
) = range(42)
def load_settings() -> Dict:
try:
with open(SETTINGS_FILE, "r") as f:
settings = json.load(f)
except FileNotFoundError:
settings = {}
defaults = {
"warning_days": 5,
"notification_hour": 9,
"notification_minute": 0,
"daily_notifications": True,
"labels": ["WatchGuard"],
"version": "v1.0.0",
}
for key, value in defaults.items():
if key not in settings:
settings[key] = value
try:
from version_util import read_version
settings["version"] = read_version(settings.get("version", "v1.0.0"))
except Exception:
pass
return settings
def save_settings(settings: Dict) -> None:
with open(SETTINGS_FILE, "w") as f:
json.dump(settings, f, indent=4)
def load_labels() -> List[str]:
try:
if os.path.exists("labels.json"):
with open("labels.json", "r", encoding="utf-8") as f:
labels_data = json.load(f)
if isinstance(labels_data, dict) and "labels" in labels_data:
labels = labels_data["labels"]
elif isinstance(labels_data, list):
labels = labels_data
else:
labels = []
unique_labels = list(
set([label.strip() for label in labels if label and label.strip()])
)
unique_labels.sort()
return unique_labels
settings = load_settings()
settings_labels = settings.get("labels", [])
if isinstance(settings_labels, list) and settings_labels:
return settings_labels
return ["WatchGuard"]
except Exception as e:
logging.error(f"Error loading labels: {e}")
return ["WatchGuard"]
def load_servers() -> Dict:
return shared_dm.load_servers()
def save_servers(servers: Dict) -> None:
shared_dm.save_servers(servers)
def load_domains() -> Dict:
return shared_dm.load_domains()
def save_domains(domains: Dict) -> None:
shared_dm.save_domains(domains)
def extract_price_and_currency(price_str: str) -> Tuple[float, str]:
if not price_str or not isinstance(price_str, str):
return 0.0, "USD"
price_str = price_str.strip()
currency_map = {"$": "USD", "€": "EUR"}
currency = "USD"
amount_str = price_str
for symbol, code in currency_map.items():
if price_str.startswith(symbol):
currency = code
amount_str = price_str[len(symbol) :]
break
number_match = re.search(r"[\d.]+", amount_str)
if number_match:
try:
return float(number_match.group()), currency
except ValueError:
logging.warning(f"Invalid price format: {price_str}")
return 0.0, currency
return 0.0, currency
def calculate_total_costs(servers: Dict, domains: Dict) -> Dict[str, float]:
totals = {
"server_usd": 0.0,
"server_eur": 0.0,
"domain_usd": 0.0,
"domain_eur": 0.0,
"total_usd": 0.0,
"total_eur": 0.0,
}
settings = load_settings()
warning_days = settings.get("warning_days", 5)
for info in servers.values():
status, _ = get_server_status(info["date"], warning_days)
if status == "expired":
continue
amount, currency = extract_price_and_currency(info.get("price", "0"))
if currency == "USD":
totals["server_usd"] += amount
elif currency == "EUR":
totals["server_eur"] += amount
for info in domains.values():
status, _ = get_server_status(info["date"], warning_days)
if status == "expired":
continue
amount, currency = extract_price_and_currency(info.get("price", "0"))
if currency == "USD":
totals["domain_usd"] += amount
elif currency == "EUR":
totals["domain_eur"] += amount
totals["total_usd"] = totals["server_usd"] + totals["domain_usd"]
totals["total_eur"] = totals["server_eur"] + totals["domain_eur"]
return totals
def format_status_text(days_diff: int) -> str:
if days_diff < 0:
return f"Expired ({abs(days_diff)} days ago)"
elif days_diff == 0:
return "⚠️ Expires today!"
elif days_diff == 1:
return "Expires tomorrow"
return f"{days_diff} days remaining"
def get_server_status(renewal_date_str: str, warning_days: int = 5) -> Tuple[str, int]:
try:
tz = pytz.timezone(TIMEZONE)
now = datetime.now(tz).replace(hour=0, minute=0, second=0, microsecond=0)
try:
renew_dt = parse_date(renewal_date_str, dayfirst=False, yearfirst=True)
except ValueError:
logging.warning(f"Invalid date format: {renewal_date_str}")
return "unknown", 0
if renew_dt.tzinfo is None:
renew_dt = tz.localize(renew_dt)
days_diff = (renew_dt.date() - now.date()).days
if days_diff < 0:
return "expired", days_diff
elif days_diff <= warning_days:
return "warning", days_diff
else:
return "safe", days_diff
except Exception as e:
logging.error(f"Error in get_server_status: {e}")
return "unknown", 0
def format_server_list(
servers: Dict[str, Dict], filter_status: Optional[str] = None
) -> str:
if not servers:
return "⚠️ No servers defined"
settings = load_settings()
warning_days = settings.get("warning_days", 5)
status_groups = {"expired": [], "warning": [], "safe": []}
for key, info in servers.items():
status, days_diff = get_server_status(info["date"], warning_days)
if filter_status and status != filter_status:
continue
emoji = info.get("emoji", "")
days_text = format_status_text(days_diff)
label = info.get("label", "")
if emoji and emoji.strip():
server_name_display = f"{emoji} {key}"
else:
server_name_display = f"- {key}"
server_info = (
f"{server_name_display}\n"
f"• **Renewal Date:** `{info['date']}`\n"
f"• **Status:** `{days_text}`\n"
f"• **Price:** `{info['price']}`\n"
f"• **Datacenter:** `{info['datacenter']}`\n"
)
if label:
server_info += f"• **Label:** `{label}`\n"
if status in status_groups:
status_groups[status].append((days_diff, server_info))
lines = []
for status, header_text in [
("warning", "🟡 Servers Near Expiration:"),
("safe", "🟢 Active Servers:"),
("expired", "🔴 Expired Servers:"),
]:
if status_groups[status]:
lines.append(f"**{header_text}**")
lines.append("")
sorted_servers = sorted(status_groups[status], key=lambda x: x[0])
for _, server_text in sorted_servers:
lines.append(server_text)
lines.append("")
return (
"\n".join(lines).rstrip("\n")
if lines
else "⚠️ No servers found with this filter"
)
def format_domain_list(
domains: Dict[str, Dict], filter_status: Optional[str] = None
) -> str:
if not domains:
return "⚠️ No domains defined"
settings = load_settings()
warning_days = settings.get("warning_days", 5)
status_groups = {"expired": [], "warning": [], "safe": []}
for domain_name, info in domains.items():
status, days_diff = get_server_status(info["date"], warning_days)
if filter_status and status != filter_status:
continue
days_text = format_status_text(days_diff)
emoji = info.get("emoji", "")
label = info.get("label", "")
if emoji and emoji.strip():
domain_name_display = f"{emoji} {domain_name}"
else:
domain_name_display = f"- {domain_name}"
domain_info = (
f"{domain_name_display}\n"
f"• **Renewal Date:** `{info['date']}`\n"
f"• **Status:** `{days_text}`\n"
f"• **Price:** `{info['price']}`\n"
f"• **Registrar:** `{info['registrar']}`\n"
)
if label:
domain_info += f"• **Label:** `{label}`\n"
if status in status_groups:
status_groups[status].append((days_diff, domain_info))
lines = []
for status, header_text in [
("warning", "🟡 Domains Near Expiration:"),
("safe", "🟢 Active Domains:"),
("expired", "🔴 Expired Domains:"),
]:
if status_groups[status]:
lines.append(f"**{header_text}**")
lines.append("")
sorted_domains = sorted(status_groups[status], key=lambda x: x[0])
for _, domain_text in sorted_domains:
lines.append(domain_text)
lines.append("")
return (
"\n".join(lines).rstrip("\n")
if lines
else "⚠️ No domains found with this filter"
)
def get_allowed_chat_ids() -> List[int]:
try:
cfg = load_config()
ids = cfg.get("CHAT_IDS", []) or []
cleaned: List[int] = []
for cid in ids:
try:
cleaned.append(int(cid))
except Exception:
continue
return cleaned
except Exception:
return []
async def auth_guard(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
try:
chat_id: Optional[int] = None
if update and update.effective_chat:
try:
chat_id = int(update.effective_chat.id)
except Exception:
chat_id = None
allowed = get_allowed_chat_ids()
if chat_id is None or chat_id not in allowed:
if chat_id is not None:
try:
await context.bot.send_message(
chat_id=chat_id, text="⛔️ Access denied"
)
except Exception:
pass
raise ApplicationHandlerStop
except ApplicationHandlerStop:
raise
except Exception:
raise ApplicationHandlerStop
async def _send_telegram_message(token: str, chat_ids: List[int], text: str) -> None:
try:
if not token or not chat_ids:
return
bot = Bot(token=token)
for chat_id in chat_ids:
try:
await bot.send_message(
chat_id=chat_id, text=text, parse_mode="Markdown"
)
except Exception as e:
logging.error(f"Failed to send daily notification to {chat_id}: {e}")
except Exception as e:
logging.error(f"Error in _send_telegram_message: {e}")
def _build_daily_digest() -> Optional[str]:
try:
settings = load_settings()
warning_days = settings.get("warning_days", 5)
servers = load_servers()
domains = load_domains()
warning_servers = []
expired_servers = []
warning_domains = []
expired_domains = []
for name, info in servers.items():
status, days_diff = get_server_status(info.get("date", ""), warning_days)
if status == "warning":
warning_servers.append((days_diff, name))
elif status == "expired":
expired_servers.append((days_diff, name))
for name, info in domains.items():
status, days_diff = get_server_status(info.get("date", ""), warning_days)
if status == "warning":
warning_domains.append((days_diff, name))
elif status == "expired":
expired_domains.append((days_diff, name))
if not (
warning_servers or expired_servers or warning_domains or expired_domains
):
return None
tz = pytz.timezone(TIMEZONE)
now = datetime.now(tz)
lines: List[str] = []
lines.append("🔔 Daily Expiration Summary")
lines.append("")
lines.append(f"Date: `{now.strftime('%Y-%m-%d %H:%M')}`")
lines.append("")
def render_section(title: str, items: List[Tuple[int, str]]):
if not items:
return
lines.append(f"**{title}**")
items_sorted = sorted(items, key=lambda x: x[0])
for days_diff, name in items_sorted:
lines.append(f"- {name} → `{format_status_text(days_diff)}`")
lines.append("")
render_section("🟡 Near Expiration (Servers)", warning_servers)
render_section("🔴 Expired (Servers)", expired_servers)
render_section("🟡 Near Expiration (Domains)", warning_domains)
render_section("🔴 Expired (Domains)", expired_domains)
return "\n".join(lines).rstrip("\n")
except Exception as e:
logging.error(f"Error building daily digest: {e}")
return None
async def run_daily_notifications(force: bool = False) -> None:
try:
config = load_config()
token = config.get("TOKEN")
chat_ids = config.get("CHAT_IDS", [])
if not token or not chat_ids:
logging.warning(
"Daily notifications skipped: missing TOKEN or CHAT_IDS in config.json"
)
return
settings = load_settings()
if not force and not settings.get("daily_notifications", True):
logging.info("Daily notifications disabled in settings; skipping send")
return
digest = _build_daily_digest()
if not digest:
logging.info("No expiring or expired items to notify; skipping send")
return
await _send_telegram_message(token, chat_ids, digest)
logging.info("Daily expiration summary sent")
except Exception as e:
logging.error(f"Error in run_daily_notifications: {e}")
async def notify_cmd(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
try:
await run_daily_notifications(force=True)
if update and update.effective_chat:
await context.bot.send_message(
chat_id=update.effective_chat.id,
text="✅ Notification triggered",
parse_mode="Markdown",
)
except Exception as e:
if update and update.effective_chat:
await context.bot.send_message(
chat_id=update.effective_chat.id,
text=f"❌ Error: {e}",
parse_mode="Markdown",
)
logging.error(f"Error in notify_cmd: {e}")
def get_cost_summary() -> str:
servers = load_servers()
domains = load_domains()
totals = calculate_total_costs(servers, domains)
header = "──────── Cost Summary ────────"
summary_lines = [header]
server_costs = []
if totals["server_usd"] > 0:
server_costs.append(f"${totals['server_usd']:.2f}")
if totals["server_eur"] > 0:
server_costs.append(f"€{totals['server_eur']:.2f}")
summary_lines.append(
f"🖥 Servers: `{' + '.join(server_costs) if server_costs else '$0.00'}`"
)
domain_costs = []
if totals["domain_usd"] > 0:
domain_costs.append(f"${totals['domain_usd']:.2f}")
if totals["domain_eur"] > 0:
domain_costs.append(f"€{totals['domain_eur']:.2f}")
summary_lines.append(
f"🌐 Domains: `{' + '.join(domain_costs) if domain_costs else '$0.00'}`"
)
total_costs = []
if totals["total_usd"] > 0:
total_costs.append(f"${totals['total_usd']:.2f}")
if totals["total_eur"] > 0:
total_costs.append(f"€{totals['total_eur']:.2f}")
if total_costs:
summary_lines.append(f"📊 Total: `{' + '.join(total_costs)}`")
else:
summary_lines.append(f"📊 Total: `$0.00`")
return "\n".join(summary_lines)
def currency_symbol(code: str) -> str:
return {"USD": "$", "EUR": "€"}.get(code, "")
def normalize_date(date_str: str) -> str:
try:
dt = datetime.strptime(date_str, "%Y-%m-%d")
return dt.strftime("%Y-%m-%d")
except ValueError:
return date_str
def format_date_input(date_str: str) -> str:
try:
date_str = date_str.strip()
try:
dt = datetime.strptime(date_str, "%Y-%m-%d")
return dt.strftime("%Y-%m-%d")
except ValueError:
pass
try:
dt = datetime.strptime(date_str, "%Y/%m/%d")
return dt.strftime("%Y-%m-%d")
except ValueError:
pass
try:
dt = datetime.strptime(date_str, "%Y.%m.%d")
return dt.strftime("%Y-%m-%d")
except ValueError:
pass
try:
dt = datetime.strptime(date_str, "%d/%m/%Y")
return dt.strftime("%Y-%m-%d")
except ValueError:
pass
try:
dt = datetime.strptime(date_str, "%m/%d/%Y")
return dt.strftime("%Y-%m-%d")
except ValueError:
pass
return date_str
except Exception:
return date_str
def is_valid_date(date_str: str) -> bool:
try:
datetime.strptime(date_str, "%Y-%m-%d")
return True
except ValueError:
return False
def is_future_date(date_str: str) -> bool:
try:
renew_dt = datetime.strptime(date_str, "%Y-%m-%d")
today = datetime.now().date()
return renew_dt.date() >= today
except ValueError:
return False
def is_valid_price(price_str: str) -> bool:
try:
if isinstance(price_str, str):
price_str = (
price_str.replace("$", "").replace("€", "").replace(",", "").strip()
)
float(price_str)
return True
except (ValueError, TypeError):
return False
def is_valid_name(name: str) -> bool:
pattern = r"^[a-zA-Z0-9\-_\s]+$"
return bool(re.match(pattern, name))
def is_valid_domain_name(domain: str) -> bool:
pattern = r"^[a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?)*$"
return re.match(pattern, domain) is not None and len(domain) <= 253
async def send_main_menu(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
chat_id = update.effective_chat.id
servers = load_servers()
domains = load_domains()
settings = load_settings()
server_status_counts = {"expired": 0, "warning": 0, "safe": 0}
for info in servers.values():
status, _ = get_server_status(info["date"], settings.get("warning_days", 5))
if status in server_status_counts:
server_status_counts[status] += 1
domain_status_counts = {"expired": 0, "warning": 0, "safe": 0}
for info in domains.values():
status, _ = get_server_status(info["date"], settings.get("warning_days", 5))
if status in domain_status_counts:
domain_status_counts[status] += 1
total_servers = sum(server_status_counts.values())
total_domains = sum(domain_status_counts.values())
server_costs = 0
for info in servers.values():
price = info.get("price", 0)
if isinstance(price, str):
price = price.replace("$", "").replace("€", "").replace(",", "").strip()
try:
server_costs += float(price)
except (ValueError, TypeError):
server_costs += 0
domain_costs = 0
for info in domains.values():
price = info.get("price", 0)
if isinstance(price, str):
price = price.replace("$", "").replace("€", "").replace(",", "").strip()
try:
domain_costs += float(price)
except (ValueError, TypeError):
domain_costs += 0
total_costs = server_costs + domain_costs
overview = (
f"━━━━ WatchGuard • Version: {settings.get('version', 'v1.0.0')} ━━━━\n\n"
f"🖥️ Servers ({total_servers})\n"
f"🟡 {server_status_counts['warning']} Near Expiration\n"
f"🟢 {server_status_counts['safe']} Active\n\n"
f"🌐 Domains ({total_domains})\n"
f"🟡 {domain_status_counts['warning']} Near Expiration\n"
f"🟢 {domain_status_counts['safe']} Active\n\n"
f"💰 Total Costs:\n"
f"• Servers: `${server_costs:.2f}`\n"
f"• Domains: `${domain_costs:.2f}`\n"
f"• Total: `${total_costs:.2f}`"
)
keyboard = [
[
InlineKeyboardButton("🖥️ Manage Servers", callback_data="servers_menu"),
],
[
InlineKeyboardButton("🌐 Manage Domains", callback_data="domains_menu"),
],
[
InlineKeyboardButton("📊 Dashboard", callback_data="dashboard"),
InlineKeyboardButton("⚙️ Settings", callback_data="settings"),
],
]
if hasattr(update, "callback_query") and update.callback_query:
await update.callback_query.edit_message_text(
text=overview,
parse_mode="Markdown",
reply_markup=InlineKeyboardMarkup(keyboard),
)
else:
await context.bot.send_message(
chat_id=chat_id,
text=overview,
parse_mode="Markdown",
reply_markup=InlineKeyboardMarkup(keyboard),
)
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
chat_id = update.effective_chat.id
servers = load_servers()
domains = load_domains()
has_items = len(servers) > 0 or len(domains) > 0
if not has_items:
welcome_text = (
"👋 **Welcome to Watch Guard!**\n\n"
"🎯 Professional Server & Domain Renewal Management\n"
"⚡️ Stay on top of your expirations – never miss a deadline again!\n\n"
"**Quick Start:**\n"
"• Add your servers and domains\n"
"• Customize your notification preferences\n"
"• Receive automatic renewal reminders\n\n"
"**Available Commands:**\n"
"• /start – Go to the main menu\n"
"• /servers – Manage your servers\n"
"• /domains – Manage your domains\n"
"• /settings – Adjust system settings\n"
"• /dashboard – View your dashboard\n"
"• /notify – Show servers and domains nearing expiration"
)
keyboard = [
[
InlineKeyboardButton("🖥️ Manage Servers", callback_data="servers_menu"),
],
[
InlineKeyboardButton("🌐 Manage Domains", callback_data="domains_menu"),
],
[
InlineKeyboardButton("📊 Dashboard", callback_data="dashboard"),
InlineKeyboardButton("⚙️ Settings", callback_data="settings"),
],
]
await context.bot.send_message(
chat_id=chat_id,
text=welcome_text,
parse_mode="Markdown",
reply_markup=InlineKeyboardMarkup(keyboard),
)
else:
await send_main_menu(update, context)
async def callback_handler(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
query = update.callback_query
await query.answer()
if query.data == "back_main":
await send_main_menu(update, context)
elif query.data == "servers_menu":
await servers_menu(update, context)
elif query.data == "domains_menu":
await domains_menu(update, context)
elif query.data == "dashboard":
await dashboard_menu(update, context)
elif query.data == "settings":
await settings_menu(update, context)
elif query.data == "set_warning_days":
await handle_set_warning_days(update, context)
elif query.data == "set_notification_time":
await handle_set_notification_time(update, context)
elif query.data == "toggle_notifications":
await handle_toggle_notifications(update, context)
elif query.data == "manage_labels":
await handle_manage_labels(update, context)
elif query.data.startswith("warning_days_"):
if query.data == "warning_days_custom":
await handle_warning_days_custom(update, context)
else:
await handle_warning_days_selection(update, context)
elif query.data.startswith("time_"):
if query.data == "time_custom":
await handle_time_custom(update, context)
else:
await handle_time_selection(update, context)
elif query.data == "add_label":
await handle_add_label(update, context)
elif query.data == "remove_label":
await handle_remove_label(update, context)
elif query.data.startswith("remove_label_"):
await handle_remove_label_confirm(update, context)
elif query.data == "add_server":
await handle_add_server(update, context)
elif query.data == "edit_server":
await handle_edit_server(update, context)
elif query.data == "remove_server":
await handle_remove_server(update, context)
elif query.data.startswith("remove_server_confirm_"):
await handle_remove_server_confirm(update, context)
elif query.data.startswith("remove_server_final_"):
await handle_remove_server_final(update, context)
elif query.data == "filter_servers":
await handle_filter_servers(update, context)
elif query.data == "add_domain":
await handle_add_domain(update, context)
elif query.data == "edit_domain":
await handle_edit_domain(update, context)
elif query.data == "remove_domain":
await handle_remove_domain(update, context)
elif query.data.startswith("remove_domain_confirm_"):
await handle_remove_domain_confirm(update, context)
elif query.data.startswith("remove_domain_final_"):
await handle_remove_domain_final(update, context)
elif query.data == "filter_domains":
await handle_filter_domains(update, context)
elif query.data.startswith("filter_servers_"):
await handle_server_filter_selection(update, context)
elif query.data.startswith("filter_domains_"):
await handle_domain_filter_selection(update, context)
elif query.data.startswith("currency_"):
await handle_currency_selection(update, context)
elif query.data.startswith("domain_currency_"):
await handle_domain_currency_selection(update, context)
elif query.data.startswith("emoji_"):
await handle_emoji_selection(update, context)
elif query.data.startswith("domain_emoji_"):
await handle_domain_emoji_selection(update, context)
elif query.data.startswith("set_server_label_"):
await handle_set_server_label(update, context)
elif query.data == "skip_server_label":
await handle_skip_server_label(update, context)
elif query.data.startswith("set_domain_label_"):
await handle_set_domain_label(update, context)
elif query.data == "skip_domain_label":
await handle_skip_domain_label(update, context)
elif query.data.startswith("server_labels_page_"):
await handle_server_labels_pagination(update, context)
elif query.data.startswith("domain_labels_page_"):
await handle_domain_labels_pagination(update, context)
elif query.data.startswith("server_label_page_"):
await handle_edit_server_label_pagination(update, context)
elif query.data.startswith("domain_label_page_"):
await handle_edit_domain_label_pagination(update, context)
elif query.data.startswith("settings_label_page_"):
await handle_settings_label_pagination(update, context)
elif query.data.startswith("remove_label_page_"):
await handle_remove_label_pagination(update, context)
elif query.data.startswith("edit_currency_"):
await handle_edit_currency_selection(update, context)
elif query.data.startswith("edit_server_select_"):
await handle_edit_server_selected(update, context)
elif query.data.startswith("edit_field_"):
await handle_edit_field(update, context)
elif query.data.startswith("set_label_"):
await handle_set_label(update, context)
elif query.data.startswith("set_emoji_"):
await handle_set_emoji(update, context)
elif query.data.startswith("edit_emoji_custom_"):
await handle_edit_emoji_custom(update, context)