-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbot.py
More file actions
2062 lines (1663 loc) · 83.9 KB
/
Copy pathbot.py
File metadata and controls
2062 lines (1663 loc) · 83.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
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 json
import uuid
from datetime import datetime
from zoneinfo import ZoneInfo
import asyncio
import traceback
import base64
import re
from typing import Any
from datetime import timezone
import aiohttp
import time
from dotenv import load_dotenv
from aiohttp import web
import discord
from discord.ext import commands
from discord.ext import tasks
from discord import app_commands
import logging
BOT_STARTED_AT_UTC = datetime.now(timezone.utc) # module load time (safe default)
def get_env_bool(key: str, default: str = "false") -> bool:
"""Helper to parse boolean environment variables."""
return os.getenv(key, default).strip().lower() in ("1", "true", "yes", "y", "on")
DASHCORD_DEBUG = get_env_bool("DASHCORD_DEBUG", "false")
log = logging.getLogger("dashcord")
log.setLevel(logging.DEBUG if DASHCORD_DEBUG else logging.INFO)
_handler = logging.StreamHandler()
_handler.setLevel(logging.DEBUG if DASHCORD_DEBUG else logging.INFO)
_formatter = logging.Formatter("%(asctime)s | %(levelname)s | %(message)s")
_handler.setFormatter(_formatter)
# avoid duplicate handlers on reload
if not log.handlers:
log.addHandler(_handler)
def _dbg(msg: str, *args):
if DASHCORD_DEBUG:
log.debug(msg, *args)
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
# ------------------------------------------------------------------------------
# LOAD ENV & ESTABLISH FALLBACKS
# ------------------------------------------------------------------------------
load_dotenv()
load_dotenv("secrets.env", override=True)
# 🤖 Core Discord Bot Settings
DISCORD_TOKEN = os.getenv("DISCORD_TOKEN")
COMMAND_PREFIX = os.getenv("COMMAND_PREFIX", "!")
TIMEZONE = os.getenv("TIMEZONE", "America/New_York")
# 📁 Storage & Configuration Paths
ROUTES_PATH = os.getenv("ROUTES_PATH", os.path.join(BASE_DIR, "routes.json"))
DYNAMIC_ROUTES_PATH = os.getenv("DYNAMIC_ROUTES_PATH", os.path.join(BASE_DIR, "config/dynamic_routes.json"))
# ⚙️ Chat Commands & Helper Settings
DISPLAY_UNKNOWN_COMMAND_ERROR = get_env_bool("DISPLAY_UNKNOWN_COMMAND_ERROR", "true")
DISPLAY_UNKNOWN_COMMAND_ERROR_SILENT_CHANNELS = set(
cid.strip() for cid in os.getenv("DISPLAY_UNKNOWN_COMMAND_ERROR_SILENT_CHANNELS", "").split(",") if cid.strip()
)
# 🎭 Chat Command Reactions (⏳, ✅, ❌ on typed user messages)
COMMAND_REACTION_ENABLED = get_env_bool("COMMAND_REACTION_ENABLED", "true")
COMMAND_REACTION_PENDING = os.getenv("COMMAND_REACTION_PENDING", "⏳")
COMMAND_REACTION_SUCCESS = os.getenv("COMMAND_REACTION_SUCCESS", "✅")
COMMAND_REACTION_FAIL = os.getenv("COMMAND_REACTION_FAIL", "❌")
# 🎛️ Panel Interaction & Behavior Baselines
PANEL_SHOW_TITLE_DEFAULT = get_env_bool("PANEL_SHOW_TITLE_DEFAULT", "true")
PANEL_REPOST_ON_STARTUP = get_env_bool("PANEL_REPOST_ON_STARTUP", "true")
PANEL_SPAWN_NEW_ON_CLICK = get_env_bool("PANEL_SPAWN_NEW_ON_CLICK", "true")
PANEL_ARCHIVE_DISABLE_BUTTONS = get_env_bool("PANEL_ARCHIVE_DISABLE_BUTTONS", "true")
PANEL_FORCE_NEW_ON_STARTUP = get_env_bool("PANEL_FORCE_NEW_ON_STARTUP", "true")
# 🎨 Panel Status Lines & Emojis
PANEL_STATUS_LINE = get_env_bool("PANEL_STATUS_LINE", "true")
PANEL_STATUS_EMOJI_PENDING = os.getenv("PANEL_STATUS_EMOJI_PENDING", "⏳")
PANEL_STATUS_EMOJI_SUCCESS = os.getenv("PANEL_STATUS_EMOJI_SUCCESS", "✅")
PANEL_STATUS_EMOJI_FAIL = os.getenv("PANEL_STATUS_EMOJI_FAIL", "❌")
PANEL_STATUS_EMOJI_IN_EMBED = get_env_bool("PANEL_STATUS_EMOJI_IN_EMBED", "true")
PANEL_STATUS_EMOJI_TITLE = get_env_bool("PANEL_STATUS_EMOJI_TITLE", "true")
# ⏱️ Panel Status Animations & Elapsed Timers
PANEL_STATUS_ANIMATE_PENDING = get_env_bool("PANEL_STATUS_ANIMATE_PENDING", "false")
PANEL_STATUS_EMOJI_PENDING_ALT = os.getenv("PANEL_STATUS_EMOJI_PENDING_ALT", "⌛")
PANEL_STATUS_ANIMATE_INTERVAL = float(os.getenv("PANEL_STATUS_ANIMATE_INTERVAL", "1.5"))
PANEL_STATUS_SHOW_ELAPSED = get_env_bool("PANEL_STATUS_SHOW_ELAPSED", "true")
PANEL_STATUS_ANIMATE_ELAPSED = get_env_bool("PANEL_STATUS_ANIMATE_ELAPSED", "true")
# 🧹 Panel Cleanup & History Scan Limits
PANEL_DELETE_OLD_PANELS = get_env_bool("PANEL_DELETE_OLD_PANELS", "true")
PANEL_SCAN_LIMIT = int(os.getenv("PANEL_SCAN_LIMIT", "50"))
# 🏃 Sticky UI / Panel Persistence Loop
PANEL_PERSIST_DEFAULT = get_env_bool("PANEL_PERSIST_DEFAULT", "false")
PANEL_PERSIST_INTERVAL_SECONDS = int(os.getenv("PANEL_PERSIST_INTERVAL_SECONDS", "45"))
PANEL_PERSIST_ON_RESPONSE = get_env_bool("PANEL_PERSIST_ON_RESPONSE", "true")
PANEL_PERSIST_ON_RESPONSE_DELAY = float(os.getenv("PANEL_PERSIST_ON_RESPONSE_DELAY", "0"))
PANEL_PERSIST_CLEANUP_OLD_ACTIVE = get_env_bool("PANEL_PERSIST_CLEANUP_OLD_ACTIVE", "true")
# 📡 Programmatic REST API Server Settings
API_ENABLED = get_env_bool("API_ENABLED", "false")
API_PORT = int(os.getenv("API_PORT", "8080"))
API_ALLOW_STATIC_OVERWRITE = get_env_bool("API_ALLOW_STATIC_OVERWRITE", "false")
# 🌐 Webhook Connectivity & Advanced Security
DASHCORD_SHARED_SECRET = os.getenv("DASHCORD_SHARED_SECRET", "")
HTTP_TIMEOUT_SECONDS = float(os.getenv("HTTP_TIMEOUT_SECONDS", "20"))
VERIFY_TLS = get_env_bool("VERIFY_TLS", "true")
# 🐞 Troubleshooting & Logging Controls
DASHCORD_DEBUG = get_env_bool("DASHCORD_DEBUG", "false")
DEBUG_WEBHOOK = get_env_bool("DEBUG_WEBHOOK", "false")
# channel_id -> { panel_name -> message_id }
PANEL_STATE: dict[str, dict[str, str]] = {}
# channel_id -> { panel_name -> active_message_id }
PANEL_ACTIVE: dict[str, dict[str, str]] = {}
# ----------------------------
# LOAD ROUTES.JSON & DYNAMIC ROUTES
# ----------------------------
if not os.path.exists(ROUTES_PATH):
raise RuntimeError(f"routes.json not found at: {ROUTES_PATH}")
with open(ROUTES_PATH, "r", encoding="utf-8") as f:
ROUTES = json.load(f)
STATIC_COMMANDS = ROUTES.get("commands", {}) or {}
STATIC_PANELS = ROUTES.get("panels", {}) or {}
DYNAMIC_COMMANDS = {}
DYNAMIC_PANELS = {}
if os.path.exists(DYNAMIC_ROUTES_PATH):
try:
with open(DYNAMIC_ROUTES_PATH, "r", encoding="utf-8") as f:
dyn = json.load(f)
DYNAMIC_COMMANDS = dyn.get("commands", {}) or {}
DYNAMIC_PANELS = dyn.get("panels", {}) or {}
log.info(f"Loaded {len(DYNAMIC_COMMANDS)} dynamic commands and {len(DYNAMIC_PANELS)} dynamic panels.")
except Exception as e:
log.error(f"Failed to load dynamic routes from {DYNAMIC_ROUTES_PATH}: {e}")
else:
_dbg("No dynamic routes configuration file found at: %s. Starting with static configuration only.", DYNAMIC_ROUTES_PATH)
# Merged active states
COMMANDS = {**STATIC_COMMANDS, **DYNAMIC_COMMANDS}
PANELS = {**STATIC_PANELS, **DYNAMIC_PANELS}
def _save_dynamic_routes():
try:
data = {
"commands": DYNAMIC_COMMANDS,
"panels": DYNAMIC_PANELS
}
with open(DYNAMIC_ROUTES_PATH, "w", encoding="utf-8") as f:
json.dump(data, f, indent=2)
except Exception as e:
log.error(f"⚠️ Failed to save dynamic routes: {e}")
log.info(f"BOOT routes={ROUTES_PATH} prefix={COMMAND_PREFIX!r} cmds={sorted(COMMANDS.keys())}")
# ----------------------------
# HELPERS
# ----------------------------
async def _add_reaction_safe(message: discord.Message, emoji: str) -> None:
if not COMMAND_REACTION_ENABLED:
return
try:
await message.add_reaction(emoji)
except Exception as e:
_dbg("Could not add reaction %s to message %s: %s", emoji, message.id, e)
async def _remove_reaction_safe(message: discord.Message, emoji: str) -> None:
if not COMMAND_REACTION_ENABLED or not bot.user:
return
try:
await message.remove_reaction(emoji, bot.user)
except Exception as e:
_dbg("Could not remove reaction %s from message %s: %s", emoji, message.id, e)
def _message_time_utc(message: discord.Message) -> datetime:
# created_at is UTC-aware in discord.py
if getattr(message, "created_at", None):
return message.created_at
# fallback: derive from snowflake
try:
return discord.utils.snowflake_time(message.id)
except Exception:
return datetime.now(timezone.utc)
def _is_pre_start_message(message: discord.Message) -> bool:
try:
return _message_time_utc(message) < BOT_STARTED_AT_UTC
except Exception:
return False
def _is_one_or_many_json_objects(text: str) -> bool:
text = (text or "").strip()
if not text:
return False
# normal json first
try:
obj = json.loads(text)
if isinstance(obj, dict):
return True
if isinstance(obj, list) and all(isinstance(x, dict) for x in obj):
return True
return False
except json.JSONDecodeError:
pass
# concatenated objects
dec = json.JSONDecoder()
i = 0
n = len(text)
found = 0
while True:
while i < n and text[i].isspace():
i += 1
if i >= n:
break
obj, end = dec.raw_decode(text, i) # can throw
if not isinstance(obj, dict):
return False
found += 1
i = end
return found > 0
def _clone_payload(payload: dict) -> dict:
return json.loads(json.dumps(payload))
def _deep_update(d, u):
"""Deep merges dict 'u' into dict 'd' safely."""
for k, v in u.items():
if isinstance(v, dict) and k in d and isinstance(d[k], dict):
_deep_update(d[k], v)
else:
d[k] = v
return d
async def _fanout_attachments_to_command(message: discord.Message, command: str, base_payload: dict) -> None:
cfg = _get_cmd_cfg(command)
rules = cfg.get("attachment_rules") or {}
exts = rules.get("extensions") or []
atts = _find_matching_attachments(message, exts)
if not atts:
want = ", ".join(exts) if exts else "any file"
got = ", ".join([a.filename for a in (message.attachments or [])]) or "(none)"
log.warning(f"⚠️ User uploaded wrong file type for command '{command}'. Expected: {want}, Got: {got}")
await message.reply(f"❌ No matching attachment found. Expected: {want}. Got: {got}")
return
await _add_reaction_safe(message, COMMAND_REACTION_PENDING)
ok = 0
bad = 0
bad_lines: list[str] = []
total = len(atts)
log.info(f"📤 Ingesting file batch: starting fan-out for {total} file(s) on command '{command}'...")
for index, att in enumerate(atts, start=1):
p = _clone_payload(base_payload)
handled, err = await _ingest_specific_attachment(att, command, p)
if handled and err:
bad += 1
bad_lines.append(err)
log.warning(f"⚠️ [{index}/{total}] Attachment '{att.filename}' rejected: {err}")
continue
try:
_dbg("Webhook call start cmd=%s att=%s", command, att.filename)
data = await post_to_webhook_async(command, p)
_dbg("Webhook call end cmd=%s att=%s", command, att.filename)
if (data or {}).get("ok"):
ok += 1
_dbg("[%d/%d] Attachment '%s' processed successfully by webhook.", index, total, att.filename)
else:
bad += 1
msg = ((data or {}).get("reply") or {}).get("content") or "unknown error"
bad_lines.append(f"❌ `{att.filename}`: {msg[:200]}")
log.warning(f"⚠️ [{index}/{total}] Webhook rejected file '{att.filename}': {msg[:100]}")
except Exception as e:
bad += 1
bad_lines.append(f"❌ `{att.filename}`: {type(e).__name__}: {e}")
log.error(f"⚠️ [{index}/{total}] Failed to post file '{att.filename}': {e}", exc_info=True)
log.info(f"📤 File batch complete for command '{command}': {ok} succeeded, {bad} failed.")
# ----------------------------
# routes-driven attachment reply policy
# ----------------------------
reply_cfg = cfg.get("attachment_reply") or {}
if not isinstance(reply_cfg, dict):
reply_cfg = {}
mode = str(reply_cfg.get("mode", "errors")).strip().lower()
if mode not in ("none", "errors", "always"):
mode = "errors"
has_errors = (bad > 0)
await _remove_reaction_safe(message, COMMAND_REACTION_PENDING)
if has_errors:
await _add_reaction_safe(message, COMMAND_REACTION_FAIL)
elif ok > 0:
await _add_reaction_safe(message, COMMAND_REACTION_SUCCESS)
should_reply = (
(mode == "always") or
(mode == "errors" and has_errors)
)
if not should_reply:
return
success_tpl = str(reply_cfg.get("success_template", "📦 Uploaded {ok}/{total} file(s).")).strip()
error_tpl = str(reply_cfg.get("error_template", "❌ Upload errors ({bad}/{total}):\n{errors}")).strip()
errors_text = "\n".join(bad_lines[:6]).strip()
if has_errors:
msg = error_tpl.format(ok=ok, bad=bad, total=total, errors=errors_text)
else:
msg = success_tpl.format(ok=ok, bad=bad, total=total, errors="")
msg = (msg or "").strip()
if msg:
await message.reply(msg[:2000])
def _commands_allowing_upload_only() -> list[str]:
out =[]
for name, cfg in (COMMANDS or {}).items():
if isinstance(cfg, dict) and cfg.get("allow_without_command") and cfg.get("accept_attachments"):
out.append(str(name).lower())
return out
def _is_upload_only_message(message: discord.Message) -> bool:
# treat empty or whitespace-only content as upload-only
return not (message.content or "").strip()
def _get_cmd_cfg(command: str) -> dict:
cfg = COMMANDS.get(command) or {}
return cfg if isinstance(cfg, dict) else {}
def _find_matching_attachments(message: discord.Message, exts: list[str]) -> list[discord.Attachment]:
exts = [e.lower() for e in (exts or [])]
out: list[discord.Attachment] = []
for a in (message.attachments or[]):
name = (a.filename or "").lower()
if not exts:
out.append(a)
elif any(name.endswith(e) for e in exts):
out.append(a)
_dbg("ATT match exts=%s got=%s", exts, [a.filename for a in out])
return out
async def _ingest_specific_attachment(att: discord.Attachment, command: str, payload: dict) -> tuple[bool, str]:
cfg = _get_cmd_cfg(command)
if not cfg.get("accept_attachments"):
return (False, "")
rules = cfg.get("attachment_rules") or {}
if not isinstance(rules, dict):
rules = {}
max_bytes = int(rules.get("max_bytes", 2_500_000))
require_json = bool(rules.get("require_json", False))
if getattr(att, "size", 0) and att.size > max_bytes:
return (True, f"❌ `{att.filename}` too large ({att.size} bytes). Max is {max_bytes} bytes.")
try:
b = await att.read()
except Exception as e:
return (True, f"❌ Failed to download `{att.filename}`: {type(e).__name__}: {e}")
if len(b) > max_bytes:
return (True, f"❌ `{att.filename}` too large ({len(b)} bytes). Max is {max_bytes} bytes.")
try:
text = b.decode("utf-8", errors="strict")
except Exception as e:
return (True, f"❌ `{att.filename}` is not valid UTF-8: {type(e).__name__}: {e}")
if require_json:
try:
if not _is_one_or_many_json_objects(text):
return (True, f"❌ `{att.filename}` JSON must be object, list[object], or multiple objects back-to-back.")
except Exception as e:
return (True, f"❌ `{att.filename}` invalid JSON: {type(e).__name__}: {e}")
_dbg("ATT ingested filename=%s bytes=%d require_json=%s", att.filename, len(b), require_json)
payload["attachment"] = {
"filename": att.filename,
"content_type": getattr(att, "content_type", None),
"size": len(b),
"url": getattr(att, "url", None),
}
payload["attachment_text"] = text
payload["attachment_bytes_len"] = len(b)
payload["attachment_b64"] = base64.b64encode(b).decode("ascii")
meta_obj = {
"discord": payload.get("discord", {}),
"attachment": payload.get("attachment", {}),
}
payload["source_meta_b64"] = base64.b64encode(
json.dumps(meta_obj, ensure_ascii=False).encode("utf-8")
).decode("ascii")
return (True, "")
def _render_template(tpl: Any, context: dict) -> Any:
"""
Replace {{...}} placeholders inside strings, recursively.
Supports dot-path lookups like {{data.0.logs}}
"""
if isinstance(tpl, str):
def repl(m: re.Match) -> str:
key = m.group(1).strip()
cur: Any = context
for part in key.split("."):
if isinstance(cur, dict) and part in cur:
cur = cur[part]
elif isinstance(cur, list) and part.isdigit() and int(part) < len(cur):
cur = cur[int(part)]
else:
_dbg("⚠️ Placeholder lookup: key '%s' not found in context.", key)
cur = ""
break
return str(cur)
# Using inline regex compilation for safety
return re.sub(r"\{\{(.+?)\}\}", repl, tpl)
elif isinstance(tpl, dict):
return {k: _render_template(v, context) for k, v in tpl.items()}
elif isinstance(tpl, list):
return [_render_template(item, context) for item in tpl]
else:
return tpl
def _panel_persist_cfg(panel_cfg: dict) -> tuple[bool, int, bool]:
p = panel_cfg.get("persist") if isinstance(panel_cfg, dict) else None
if not isinstance(p, dict):
return (PANEL_PERSIST_DEFAULT, PANEL_PERSIST_INTERVAL_SECONDS, PANEL_PERSIST_CLEANUP_OLD_ACTIVE)
enabled = p.get("enabled", PANEL_PERSIST_DEFAULT)
interval = int(p.get("interval_seconds", PANEL_PERSIST_INTERVAL_SECONDS))
cleanup = p.get("cleanup_old_active", PANEL_PERSIST_CLEANUP_OLD_ACTIVE)
if isinstance(enabled, str):
enabled = enabled.strip().lower() in ("1", "true", "yes", "y", "on")
else:
enabled = bool(enabled)
if isinstance(cleanup, str):
cleanup = cleanup.strip().lower() in ("1", "true", "yes", "y", "on")
else:
cleanup = bool(cleanup)
if interval < 10:
interval = 10 # safety: don’t spam-check too fast
return (enabled, interval, cleanup)
async def _get_last_message(channel: discord.abc.Messageable) -> discord.Message | None:
try:
async for m in channel.history(limit=1): # type: ignore[attr-defined]
return m
except Exception as e:
log.warning(f"⚠️ Cannot fetch message history in channel {getattr(channel, 'id', 'unknown')} (Missing permissions?): {e}")
return None
return None
async def _get_last_message_id(channel: discord.abc.Messageable) -> int | None:
m = await _get_last_message(channel)
return m.id if m else None
async def _persist_panel_once(panel_name: str, channel: discord.abc.Messageable, panel_cfg: dict) -> None:
# If panel is not last message, post a new active panel (force_new=True)
last_id = await _get_last_message_id(channel)
if last_id is None or not getattr(channel, "id", None):
return
active_id_str = _get_active_panel_msg_id(channel.id, panel_name)
active_id = int(active_id_str) if active_id_str and active_id_str.isdigit() else None
# SAFETY NET: If we don't know the active panel, try to find it first (prevents blind duplication)
if active_id is None:
existing = await _find_existing_panel_message(channel, panel_name)
if existing:
active_id = existing.id
_set_active_panel_msg_id(channel.id, panel_name, active_id)
# If our active panel is already last, do nothing
if active_id and last_id == active_id:
_dbg("Panel '%s' is already at the bottom of channel %s. Skipping move.", panel_name, channel.id)
return
log.info(f"🔄 Persistence: Moving panel '{panel_name}' to bottom of channel {channel.id}")
# Post new panel at bottom
await _post_panel_to_channel(channel, panel_name, panel_cfg, force_new=True)
# Cleanup previous active panel so we don't accumulate junk
enabled, interval, cleanup_old = _panel_persist_cfg(panel_cfg)
if cleanup_old and active_id:
try:
old = await channel.fetch_message(active_id) # type: ignore[attr-defined]
if old and old.author and bot.user and old.author.id == bot.user.id:
await old.delete()
except Exception as e:
log.warning(f"⚠️ Failed to delete old active panel message {active_id} (Missing permissions?): {e}")
def _get_active_panel_msg_id(channel_id: int, panel_name: str) -> str | None:
return (PANEL_ACTIVE.get(_panel_key(channel_id), {}) or {}).get(panel_name)
def _set_active_panel_msg_id(channel_id: int, panel_name: str, message_id: int) -> None:
PANEL_ACTIVE.setdefault(_panel_key(channel_id), {})[panel_name] = str(message_id)
def _panel_key(channel_id: int) -> str:
return str(channel_id)
def _get_panel_msg_id(channel_id: int, panel_name: str) -> str | None:
return (PANEL_STATE.get(_panel_key(channel_id), {}) or {}).get(panel_name)
def _set_panel_msg_id(channel_id: int, panel_name: str, message_id: int) -> None:
PANEL_STATE.setdefault(_panel_key(channel_id), {})[panel_name] = str(message_id)
def _is_panel_archived(msg: discord.Message) -> bool:
"""Checks if a panel message has disabled components, marking it as historical/archived."""
if not msg.components:
return False
for action_row in msg.components:
for child in getattr(action_row, "children", []):
if getattr(child, "disabled", False):
return True
return False
async def _delete_existing_panel_message(channel: discord.abc.Messageable, panel_name: str) -> None:
if not getattr(channel, "id", None) or not bot.user:
return
stored = _get_panel_msg_id(channel.id, panel_name)
if stored:
try:
msg = await channel.fetch_message(int(stored)) # type: ignore[attr-defined]
if msg and msg.author and msg.author.id == bot.user.id:
if not _is_panel_archived(msg):
await msg.delete()
log.info(f"🧹 Cleaned up stored old panel '{panel_name}' in channel {channel.id}")
return
except Exception:
pass
try:
async for msg in channel.history(limit=PANEL_SCAN_LIMIT): # type: ignore[attr-defined]
if msg.author and bot.user and msg.author.id == bot.user.id:
match = False
if isinstance(msg.content, str) and f"({panel_name})" in msg.content:
match = True
else:
for action_row in msg.components:
for child in action_row.children:
cid = getattr(child, "custom_id", "") or ""
if cid.startswith(f"dashcord:btn:{panel_name}:") or cid.startswith(f"dashcord:sel:{panel_name}:"):
match = True
break
if match:
break
if match:
if _is_panel_archived(msg):
continue
try:
await msg.delete()
log.info(f"🧹 Cleaned up old panel '{panel_name}' (ID: {msg.id}) from history")
except Exception as e:
log.warning(f"⚠️ Failed to delete old panel '{panel_name}' (ID: {msg.id}) during cleanup: {e}")
except Exception as e:
log.warning(f"⚠️ Failed to scan history for cleanup in channel {channel.id}: {e}")
async def _find_existing_panel_message(channel: discord.abc.Messageable, panel_name: str):
if not getattr(channel, "id", None) or not bot.user:
return None
# 1. State cache lookup (Fastest, survives edits)
stored = _get_panel_msg_id(channel.id, panel_name)
if stored:
try:
msg = await channel.fetch_message(int(stored))
if msg and msg.author and msg.author.id == bot.user.id:
if not _is_panel_archived(msg):
return msg
except Exception:
_dbg("⚠️ Cached message ID %s for panel '%s' no longer exists in channel %s. Clearing cache.", stored, panel_name, channel.id)
pass
# 2. History scan fallback (Survives bot restarts)
try:
async for msg in channel.history(limit=PANEL_SCAN_LIMIT):
if msg.author and msg.author.id == bot.user.id:
if _is_panel_archived(msg):
continue
# check if it is the panel by seeing if the name is in the content
if isinstance(msg.content, str) and f"({panel_name})" in msg.content:
log.info(f"🔍 Found existing panel '{panel_name}' in channel {channel.id} (via text match). Attaching to it.")
_set_panel_msg_id(channel.id, panel_name, msg.id)
return msg
# Check components (Buttons/Dropdowns have hidden IDs)
for action_row in msg.components:
for child in action_row.children:
cid = getattr(child, "custom_id", "") or ""
# If a button or select matches this panel's internal ID
if cid.startswith(f"dashcord:btn:{panel_name}:") or cid.startswith(f"dashcord:sel:{panel_name}:"):
log.info(f"🔍 Found existing panel '{panel_name}' in channel {channel.id} (via component ID). Attaching to it.")
_set_panel_msg_id(channel.id, panel_name, msg.id)
return msg
except Exception as e:
log.warning(f"⚠️ Failed to scan for existing panel '{panel_name}' in channel {channel.id}: {e}")
return None
async def _post_panel_to_channel(
channel: discord.abc.Messageable,
panel_name: str,
panel_cfg: dict,
*,
force_new: bool = False
) -> None:
content, embed = _build_panel_message(panel_name, panel_cfg)
view = DashPanel(panel_name, panel_cfg)
if not force_new:
existing = await _find_existing_panel_message(channel, panel_name)
if existing:
try:
_dbg("Updating existing message ID %s for panel '%s'", existing.id, panel_name)
await existing.edit(content=content, embed=embed, view=view)
_set_active_panel_msg_id(channel.id, panel_name, existing.id)
return
except Exception as e:
log.warning(f"⚠️ Found existing panel '{panel_name}' but failed to edit it. Falling back to posting new. Error: {e}")
log.info(f"🆕 Posting new panel '{panel_name}' to channel {getattr(channel, 'id', 'unknown')}")
sent = await channel.send(content=content, embed=embed, view=view)
if getattr(channel, "id", None):
_set_panel_msg_id(channel.id, panel_name, sent.id)
_set_active_panel_msg_id(channel.id, panel_name, sent.id)
def now_local_iso() -> str:
try:
return datetime.now(ZoneInfo(TIMEZONE)).isoformat()
except Exception:
return datetime.now().isoformat()
def resolve_endpoint(command: str) -> str:
cfg = COMMANDS.get(command)
if not cfg:
raise RuntimeError(f"No command configured: {command}")
endpoint = cfg.get("endpoint")
if not isinstance(endpoint, str) or not endpoint.startswith(("http://", "https://")):
raise RuntimeError(f"Invalid endpoint URL for command '{command}': {endpoint!r}")
return endpoint
def _as_int_set(values) -> set[int]:
out: set[int] = set()
for v in (values or[]):
try:
out.add(int(v))
except Exception:
pass
return out
def is_user_allowed(command: str, user_id: int, silent: bool = False) -> bool:
allowed = (COMMANDS.get(command, {}) or {}).get("allowed_users",[])
allowed_set = _as_int_set(allowed)
ok = (len(allowed_set) == 0) or (int(user_id) in allowed_set)
_dbg(
"ALLOW_USER? cmd=%s user_id=%s(%s) allowed=%s -> %s",
command,
user_id, type(user_id).__name__,
list(allowed_set),
ok
)
if not ok and not silent:
log.warning(f"🚫 User {user_id} denied access to command '{command}'")
return ok
def is_channel_allowed(command: str, channel_id: int, silent: bool = False) -> bool:
allowed = (COMMANDS.get(command, {}) or {}).get("allowed_channels",[])
allowed_set = _as_int_set(allowed)
ok = (len(allowed_set) == 0) or (int(channel_id) in allowed_set)
_dbg(
"ALLOW_CHAN? cmd=%s channel_id=%s(%s) allowed=%s -> %s",
command,
channel_id, type(channel_id).__name__,
list(allowed_set),
ok
)
if not ok and not silent:
log.warning(f"🚫 Command '{command}' denied in channel {channel_id}")
return ok
def build_payload(*, event_type, command, args, raw, guild, channel, user, message_id=None, interaction_id=None):
return {
"source": "discord",
"event_type": event_type, # "command" | "button"
"command": command,
"args": args,
"raw": raw,
"timestamp": now_local_iso(),
"nonce": str(uuid.uuid4()),
"discord": {
"guild_id": str(guild.id) if guild else None,
"guild_name": guild.name if guild else None,
"channel_id": str(channel.id) if getattr(channel, "id", None) else None,
"channel_name": getattr(channel, "name", None),
"user_id": str(user.id),
"user_name": getattr(user, "name", None),
"user_display": getattr(user, "display_name", None),
"message_id": str(message_id) if message_id else None,
"interaction_id": interaction_id,
},
"meta": {"timezone": TIMEZONE},
}
def _resolve_method(command: str) -> str:
cfg = COMMANDS.get(command) or {}
m = (cfg.get("method") or "POST").strip().upper()
if m not in ("POST", "GET"):
raise RuntimeError(f"Invalid method for command '{command}': {m!r} (use POST or GET)")
return m
async def post_to_webhook_async(command: str, payload: dict) -> dict:
cfg = COMMANDS.get(command) or {}
endpoint = resolve_endpoint(command)
method = _resolve_method(command)
body_template = cfg.get("body_template")
out_json = payload
if body_template is not None:
out_json = _render_template(body_template, payload)
headers = {"Content-Type": "application/json"}
if DASHCORD_SHARED_SECRET:
headers["X-DashCord-Token"] = DASHCORD_SHARED_SECRET
custom_headers = cfg.get("headers")
if isinstance(custom_headers, dict):
for h_key, h_val in custom_headers.items():
headers[h_key] = str(h_val)
async def parse_response(status: int, text: str, resp_headers: dict) -> dict:
_dbg("WEBHOOK POST cmd=%s status=%s", command, status)
if DEBUG_WEBHOOK:
# Safely attempt to beautify JSON for the console
try:
parsed_json = json.loads(text)
preview = json.dumps(parsed_json, indent=2)
if len(preview) > 1500:
preview = preview[:1500] + "\n... (truncated)"
except Exception:
# Fallback to raw string if it's not valid JSON (e.g. HTML errors)
preview = text[:800].replace("\n", "\\n")
log.info(
"\n================ WEBHOOK RESPONSE ================\n"
f"command: {command}\n"
f"endpoint: {endpoint}\n"
f"status: {status}\n"
f"content-type: {resp_headers.get('Content-Type')}\n"
f"text_preview:\n{preview}\n"
"=================================================="
)
try:
data = json.loads(text)
# If the user defines a response_template, map the raw API JSON to DashCord's format
resp_tpl = cfg.get("response_template")
if resp_tpl:
# Wrap lists in a dict so dot-notation works (e.g., {{root.0.name}})
context = data if isinstance(data, dict) else {"root": data}
data = _render_template(resp_tpl, context)
except Exception as e:
if 200 <= status < 300 and text.strip():
log.warning(f"⚠️ Webhook response for '{command}' returned HTTP {status} but was not valid JSON. Falling back to plain text reply.")
data = None
# If endpoint responds with an "items array", unwrap item 0
if isinstance(data, list) and len(data) == 1 and isinstance(data[0], dict):
data = data[0]
# If endpoint wrapped the real payload under { "response": {...} }, unwrap it
if isinstance(data, dict) and isinstance(data.get("response"), dict):
data = data["response"]
# If still not a dict, fall back to raw text
if not isinstance(data, dict):
data = {"ok": (200 <= status < 300), "reply": {"content": text}}
# Normalize error responses
if not (200 <= status < 300):
log.warning(f"❌ Webhook Error [{command}]: HTTP {status} - {text[:200]}")
data["ok"] = False
data.setdefault("reply", {})
if not isinstance(data["reply"], dict):
data["reply"] = {"content": str(data["reply"])}
data["reply"].setdefault("content", f"Webhook HTTP {status}: {text[:800]}")
# Normalize reply shape
data.setdefault("reply", {})
if not isinstance(data["reply"], dict):
data["reply"] = {"content": str(data["reply"])}
if "stdout" in data and not data["reply"].get("content"):
stdout_str = str(data["stdout"]).strip()
if stdout_str:
data["reply"]["content"] = f"```\n{stdout_str}\n```"
# ---- DEBUG PARSED ----
if DEBUG_WEBHOOK:
reply_obj = data.get("reply")
is_dict = isinstance(reply_obj, dict)
reply_keys = list(reply_obj.keys()) if is_dict else None
c = reply_obj.get("content") if is_dict else None
c_len = len(c) if isinstance(c, str) else None
c_preview = c[:200].replace("\n", "\\n") if isinstance(c, str) else None
log.info(
"\n================ WEBHOOK PARSED ================\n"
f"PARSED TYPE: {type(data).__name__}\n"
f"PARSED KEYS: {list(data.keys())}\n"
f"REPLY TYPE: {type(reply_obj).__name__}\n"
f"REPLY KEYS: {reply_keys}\n"
f"CONTENT LEN: {c_len}\n"
f"CONTENT PREVIEW: {c_preview}\n"
"=================================================="
)
return data
t0 = time.monotonic()
_dbg("WEBHOOK request cmd=%s method=%s endpoint=%s timeout=%s verify_tls=%s",
command, method, endpoint, HTTP_TIMEOUT_SECONDS, VERIFY_TLS)
custom_timeout = float(cfg.get("timeout", HTTP_TIMEOUT_SECONDS))
timeout = aiohttp.ClientTimeout(total=custom_timeout)
global AIOHTTP_SESSION
session = AIOHTTP_SESSION
close_session = False
# Fallback if somehow called before setup_hook initializes the global session
if session is None:
session = aiohttp.ClientSession(timeout=timeout)
close_session = True
try:
if method == "POST":
async with session.post(endpoint, headers=headers, json=out_json, ssl=VERIFY_TLS, timeout=timeout) as r:
text = await r.text()
_dbg("WEBHOOK response cmd=%s status=%s elapsed=%.2fs", command, r.status, time.monotonic() - t0)
# missing POST route fallback to GET
if r.status == 404 and "not registered for POST requests" in text:
async with session.get(endpoint, headers=headers, params={"payload": json.dumps(out_json, separators=(",", ":"))}, ssl=VERIFY_TLS, timeout=timeout) as r2:
text2 = await r2.text()
return await parse_response(r2.status, text2, dict(r2.headers))
return await parse_response(r.status, text, dict(r.headers))
else: # GET method
async with session.get(endpoint, headers=headers, params={"payload": json.dumps(out_json, separators=(",", ":"))}, ssl=VERIFY_TLS, timeout=timeout) as r:
text = await r.text()
_dbg("WEBHOOK response cmd=%s status=%s elapsed=%.2fs", command, r.status, time.monotonic() - t0)
return await parse_response(r.status, text, dict(r.headers))
except Exception as e:
log.error(f"⚠️ Webhook Exception cmd={command}: {e}")
raise
finally:
if close_session:
await session.close()
async def send_reply(channel: discord.abc.Messageable, data: dict) -> None:
reply = (data or {}).get("reply") or {}
if not isinstance(reply, dict):
reply = {"content": str(reply)}
# honor suppress flag (support both spellings)
suppress = bool(reply.get("suppress") or reply.get("supress"))
content = (reply.get("content") or "").strip()
embeds_raw = reply.get("embeds") or []
embeds: list[discord.Embed] =[]
if isinstance(embeds_raw, list):
for e in embeds_raw[:10]:
if isinstance(e, dict):
try:
embeds.append(discord.Embed.from_dict(e))
except Exception:
pass
# If suppress is true, send NOTHING.
if suppress or (not content and not embeds):
return
await channel.send(content=content[:2000], embeds=embeds)
# ----------------------------
# DISCORD SETUP
# ----------------------------
intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(
command_prefix=COMMAND_PREFIX,
intents=intents,
help_command=None,
)
@bot.event
async def on_command_error(ctx, error):
if isinstance(error, commands.CommandNotFound):
return
log.error(f"⚠️ Discord Command Error in '{ctx.command}': {error}", exc_info=error)
raise error
# ----------------------------
# PANEL UI
# ----------------------------
STYLE_MAP = {
"primary": discord.ButtonStyle.primary,
"secondary": discord.ButtonStyle.secondary,
"success": discord.ButtonStyle.success,
"danger": discord.ButtonStyle.danger,
}
def _build_panel_message(panel_name: str, panel_cfg: dict) -> tuple[str | None, discord.Embed | None]:
"""Generates the content and Embed for a panel based on its config."""
# 1. Determine if we show the DashCord Title Header
# Priority: 1. panel config override, 2. global env default
show_title = panel_cfg.get("show_title", PANEL_SHOW_TITLE_DEFAULT)
parts = []