Repository navigation
Expand file tree
/
Copy pathbot.py
More file actions
4559 lines (4087 loc) · 197 KB
/
Copy pathbot.py
File metadata and controls
4559 lines (4087 loc) · 197 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
"""
PC Remote Sentinel — Fleet Commander Bot
Central Telegram bot that controls multiple Windows PCs through their remote agents.
"""
import ctypes
try:
ctypes.windll.kernel32.SetConsoleTitleW('PC-Remote-Sentinel')
except Exception:
pass
import os
import sys
import io
import time
import html
import json
import math
import asyncio
from datetime import datetime, timezone
from pathlib import Path
from typing import Optional, Dict, Any, List, Tuple
import urllib.parse
import httpx
from loguru import logger
import telegram.error
from telegram import (
InlineKeyboardButton,
InlineKeyboardMarkup,
Update,
BotCommand,
InputMediaPhoto,
)
from telegram.constants import ChatAction
from telegram.request import HTTPXRequest
from telegram.ext import (
Application,
ApplicationBuilder,
CallbackQueryHandler,
CommandHandler,
ContextTypes,
MessageHandler,
filters,
)
import config
from fleet_relay import FleetCommanderRelay
# ═══════════════════════════════════════════════════════════════════════
# FLEET MANAGEMENT & CLOUD RELAY
# ═══════════════════════════════════════════════════════════════════════
FLEET_FILE = config.BASE_DIR / "fleet.json"
commander_relay: Optional[FleetCommanderRelay] = None
def ensure_host_pc_registered(fleet: dict) -> bool:
"""Ensure Host PC is always registered in fleet if running on Windows."""
if sys.platform != "win32":
return False
host_name = os.environ.get("COMPUTERNAME", "Host-PC")
pcs = fleet.get("pcs", [])
for pc in pcs:
if pc.get("name") == host_name:
pc["is_host"] = True
return False
pcs.insert(0, {
"name": host_name,
"label": f"🖥️ Host ({host_name})",
"ip": "127.0.0.1",
"port": int(os.getenv("AGENT_PORT", "9010")),
"is_host": True,
})
fleet["pcs"] = pcs
save_fleet(fleet)
return True
def ensure_local_agent_running():
"""If running on Windows and local agent is not running or outdated on port 9010, launch it in background."""
if sys.platform != "win32":
return
import socket
import subprocess
import urllib.request
import urllib.error
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(0.5)
is_open = sock.connect_ex(("127.0.0.1", 9010)) == 0
sock.close()
if is_open:
# Check if running agent is up-to-date (responds to /input/cursor)
is_outdated = False
try:
req = urllib.request.Request("http://127.0.0.1:9010/input/cursor")
if config.AGENT_SECRET:
req.add_header("X-Agent-Secret", config.AGENT_SECRET)
with urllib.request.urlopen(req, timeout=1.0) as resp:
if resp.status == 200:
logger.info("Local PC Agent is running and up-to-date on port 9010.")
return
except urllib.error.HTTPError as he:
if he.code == 404:
logger.warning("Local PC Agent on port 9010 is outdated (missing /input/cursor). Restarting...")
is_outdated = True
except Exception:
# If non-HTTP error (e.g. secret mismatch, timeout), keep existing process
return
if is_outdated:
# Terminate stale agent process listening on port 9010
try:
netstat_out = subprocess.check_output("netstat -ano", shell=True).decode()
for line in netstat_out.splitlines():
if ":9010" in line and "LISTENING" in line:
parts = line.strip().split()
pid = int(parts[-1])
if pid > 0 and pid != os.getpid():
subprocess.run(f"taskkill /f /pid {pid}", shell=True, capture_output=True)
time.sleep(1.0)
except Exception as err:
logger.debug(f"Failed to kill outdated agent: {err}")
agent_py = config.BASE_DIR / "agent.py"
if not agent_py.exists():
return
agent_exe = config.BASE_DIR / "pc-sentinel-agent.exe"
exe = str(agent_exe) if agent_exe.exists() else sys.executable
creation_flags = (subprocess.CREATE_NO_WINDOW | 0x00000008) if sys.platform == "win32" else 0
logger.info(f"Auto-launching local PC Agent silently ({Path(exe).name})...")
subprocess.Popen(
[exe, str(agent_py)],
cwd=str(config.BASE_DIR),
creationflags=creation_flags,
close_fds=True,
stdin=subprocess.DEVNULL,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
except Exception as e:
logger.error(f"Could not auto-start local agent: {e}")
def load_fleet() -> dict:
"""Load fleet configuration from fleet.json."""
fleet = {"secret": os.getenv("FLEET_SECRET", "").strip(), "pcs": []}
if FLEET_FILE.exists():
try:
fleet = json.loads(FLEET_FILE.read_text(encoding="utf-8"))
except Exception as e:
logger.error(f"Failed to load fleet.json: {e}")
ensure_host_pc_registered(fleet)
return fleet
def save_fleet(fleet: dict):
"""Save fleet configuration."""
try:
FLEET_FILE.write_text(json.dumps(fleet, indent=4), encoding="utf-8")
except Exception as e:
logger.warning(f"Could not persist fleet.json: {e}")
def get_fleet_secret(fleet: Optional[dict] = None) -> str:
"""Get the active fleet encryption secret from fleet.json or environment."""
if fleet is None:
fleet = load_fleet()
return (fleet.get("secret", "") or "").strip() or os.getenv("FLEET_SECRET", "").strip() or "sentinel-fleet-secret-2026"
class AgentClient:
"""
Hybrid client for communicating with a PC agent.
Routes commands through Cloud Relay (MQTT over TLS) if PC is on Mobile Data / CGNAT,
or directly via local HTTP if on local LAN.
"""
def __init__(self, pc_info: dict, secret: str):
self.name = pc_info["name"]
self.label = pc_info.get("label", self.name)
self.ip = pc_info.get("ip", "127.0.0.1")
self.port = pc_info.get("port", 9010)
self.base_url = f"http://{self.ip}:{self.port}"
self.secret = secret
@property
def is_local(self) -> bool:
"""True if target PC is local host (127.0.0.1 or localhost) - bypasses internet/cloud entirely."""
return self.ip in ("127.0.0.1", "localhost", "::1")
@property
def is_local(self) -> bool:
"""Check if PC agent is running locally on the same host machine."""
return self.ip in ("127.0.0.1", "localhost", "::1")
def is_relay_online(self) -> bool:
"""Check if PC is connected to the Cloud Relay."""
if commander_relay and commander_relay.is_connected:
pcs = commander_relay.get_pc_list()
return self.name in pcs and pcs[self.name].get("status") == "online"
return False
def should_use_relay(self) -> bool:
"""
Only route through Cloud Relay (MQTT) if the PC is truly remote.
For local host PC (127.0.0.1), always use 0-latency direct local HTTP first.
"""
if self.is_local:
return False
return self.is_relay_online()
def _headers(self) -> dict:
return {"X-Agent-Secret": self.secret}
async def _get(self, path: str, timeout: float = 15.0, **kwargs) -> httpx.Response:
async with httpx.AsyncClient(timeout=timeout) as client:
return await client.get(f"{self.base_url}{path}", headers=self._headers(), **kwargs)
async def _post(self, path: str, timeout: float = 30.0, **kwargs) -> httpx.Response:
async with httpx.AsyncClient(timeout=timeout) as client:
return await client.post(f"{self.base_url}{path}", headers=self._headers(), **kwargs)
async def health(self) -> Optional[dict]:
# For local PC, query direct loopback in milliseconds
if self.is_local:
try:
r = await self._get("/health", timeout=2.0)
r.raise_for_status()
return r.json()
except Exception:
pass
if self.should_use_relay():
info = commander_relay.get_pc_list().get(self.name, {})
return {"status": "online", "network": info.get("network", "Remote")}
try:
r = await self._get("/health", timeout=3.0)
r.raise_for_status()
return r.json()
except Exception:
return None
async def status(self) -> dict:
# Prioritize local HTTP if on host PC for instant diagnostics without internet
if self.is_local:
try:
r = await self._get("/status", timeout=5.0)
r.raise_for_status()
return r.json()
except Exception as e:
logger.debug(f"Local status HTTP failed: {e}. Trying cloud relay...")
if self.should_use_relay():
res = await commander_relay.send_command(self.name, "status", timeout=30.0)
if res.get("ok") and "stats" in res:
return res["stats"]
elif "error" in res:
raise Exception(res["error"])
r = await self._get("/status", timeout=15.0)
r.raise_for_status()
return r.json()
async def screenshot(self, chat_id: Optional[int] = None) -> Any:
# If local host PC, capture screenshot directly via fast local loopback
if self.is_local:
try:
r = await self._get("/screenshot", timeout=20.0)
r.raise_for_status()
return r.content
except Exception as e:
logger.debug(f"Local screenshot HTTP failed: {e}. Trying relay...")
if self.should_use_relay() and chat_id:
res = await commander_relay.send_command(self.name, "screenshot", {"chat_id": chat_id}, timeout=50.0)
if res.get("ok"):
return {"direct_upload": True}
raise Exception(res.get("error", "Remote screenshot failed"))
r = await self._get("/screenshot", timeout=30.0)
r.raise_for_status()
return r.content
async def webcam(self, chat_id: Optional[int] = None) -> Any:
if self.is_local:
try:
r = await self._get("/webcam", timeout=20.0)
r.raise_for_status()
return r.content
except Exception as e:
logger.debug(f"Local webcam HTTP failed: {e}. Trying relay...")
if self.should_use_relay() and chat_id:
res = await commander_relay.send_command(self.name, "webcam", {"chat_id": chat_id}, timeout=50.0)
if res.get("ok"):
return {"direct_upload": True}
raise Exception(res.get("error", "Remote webcam failed"))
r = await self._get("/webcam", timeout=30.0)
r.raise_for_status()
return r.content
async def record_screen(self, duration: int, chat_id: Optional[int] = None) -> Any:
if self.is_local:
try:
r = await self._post(f"/record/screen?duration={duration}", timeout=duration + 35.0)
r.raise_for_status()
return r.content
except Exception as e:
logger.debug(f"Local screen record HTTP failed: {e}. Trying relay...")
if self.should_use_relay() and chat_id:
res = await commander_relay.send_command(self.name, "record_screen", {"duration": duration, "chat_id": chat_id}, timeout=duration + 60.0)
if res.get("ok"):
return {"direct_upload": True}
raise Exception(res.get("error", "Remote screen recording failed"))
r = await self._post(f"/record/screen?duration={duration}", timeout=duration + 45.0)
r.raise_for_status()
return r.content
async def record_webcam(self, duration: int, chat_id: Optional[int] = None) -> Any:
if self.is_local:
try:
r = await self._post(f"/record/webcam?duration={duration}", timeout=duration + 35.0)
r.raise_for_status()
return r.content
except Exception as e:
logger.debug(f"Local webcam record HTTP failed: {e}. Trying relay...")
if self.should_use_relay() and chat_id:
res = await commander_relay.send_command(self.name, "record_webcam", {"duration": duration, "chat_id": chat_id}, timeout=duration + 60.0)
if res.get("ok"):
return {"direct_upload": True}
raise Exception(res.get("error", "Remote webcam recording failed"))
r = await self._post(f"/record/webcam?duration={duration}", timeout=duration + 45.0)
r.raise_for_status()
return r.content
async def cast_web_start(self) -> dict:
if self.should_use_relay():
res = await commander_relay.send_command(self.name, "cast_start", timeout=25.0)
if res.get("ok"):
return res
r = await self._post("/cast/web/start", timeout=30.0)
r.raise_for_status()
return r.json()
async def cast_web_stop(self) -> dict:
if self.should_use_relay():
res = await commander_relay.send_command(self.name, "cast_stop", timeout=10.0)
if res.get("ok"):
return res
r = await self._post("/cast/web/stop")
r.raise_for_status()
return r.json()
async def cast_status(self) -> dict:
if self.should_use_relay():
res = await commander_relay.send_command(self.name, "cast_status", timeout=10.0)
if res.get("ok"):
return res.get("status", {})
try:
r = await self._get("/cast/status", timeout=5.0)
r.raise_for_status()
return r.json()
except Exception:
return {"is_web_streaming": False, "is_rtmp_streaming": False}
async def cast_frame(self, quality: int = 60, max_width: int = 960) -> bytes:
if self.should_use_relay():
res = await commander_relay.send_command(self.name, "cast_frame", {"quality": quality, "max_width": max_width}, timeout=10.0)
if res.get("ok") and "frame_b64" in res:
import base64
return base64.b64decode(res["frame_b64"])
r = await self._get(f"/cast/frame?quality={quality}&max_width={max_width}", timeout=10.0)
r.raise_for_status()
return r.content
async def switch_desktop(self, action: str = "next") -> dict:
if self.should_use_relay():
return await commander_relay.send_command(self.name, "switch_desktop", {"action": action}, timeout=10.0)
try:
r = await self._post(f"/desktop/switch?action={action}", timeout=10.0)
r.raise_for_status()
return r.json()
except Exception as e:
return {"ok": False, "msg": f"Desktop switch failed: {e}", "error": str(e)}
async def get_open_windows(self, limit: int = 25) -> dict:
if self.should_use_relay():
return await commander_relay.send_command(self.name, "windows_list", {"limit": limit}, timeout=10.0)
try:
r = await self._get(f"/windows?limit={limit}", timeout=10.0)
r.raise_for_status()
return r.json()
except Exception as e:
return {"ok": False, "windows": [], "error": str(e)}
async def focus_window(self, target: Any) -> dict:
if self.should_use_relay():
return await commander_relay.send_command(self.name, "window_focus", {"target": str(target)}, timeout=10.0)
try:
r = await self._post(f"/windows/focus?target={urllib.parse.quote(str(target))}", timeout=10.0)
r.raise_for_status()
return r.json()
except Exception as e:
return {"ok": False, "msg": f"Focus failed: {e}", "error": str(e)}
async def cycle_window(self, direction: str = "next") -> dict:
if self.should_use_relay():
return await commander_relay.send_command(self.name, "window_cycle", {"direction": direction}, timeout=10.0)
try:
r = await self._post(f"/windows/cycle?direction={direction}", timeout=10.0)
r.raise_for_status()
return r.json()
except Exception as e:
return {"ok": False, "msg": f"Cycle window failed: {e}", "error": str(e)}
async def mouse_input(self, action: str = "move", **kwargs) -> dict:
params = {"action": action, **kwargs}
if self.should_use_relay():
return await commander_relay.send_command(self.name, "mouse_input", params, timeout=10.0)
try:
r = await self._post("/input/mouse", json=params, timeout=10.0)
r.raise_for_status()
return r.json()
except Exception as e:
return {"ok": False, "error": str(e)}
async def type_text(self, text: str) -> dict:
if self.should_use_relay():
return await commander_relay.send_command(self.name, "type_text", {"text": text}, timeout=10.0)
try:
r = await self._post("/input/type", json={"text": text}, timeout=10.0)
r.raise_for_status()
return r.json()
except Exception as e:
return {"ok": False, "msg": str(e), "error": str(e)}
async def press_key(self, key: str) -> dict:
if self.should_use_relay():
return await commander_relay.send_command(self.name, "press_key", {"key": key}, timeout=10.0)
try:
r = await self._post("/input/key", json={"key": key}, timeout=10.0)
r.raise_for_status()
return r.json()
except Exception as e:
return {"ok": False, "msg": str(e), "error": str(e)}
async def get_cursor(self) -> dict:
if self.should_use_relay():
return await commander_relay.send_command(self.name, "get_cursor", timeout=10.0)
try:
r = await self._get("/input/cursor", timeout=10.0)
r.raise_for_status()
return r.json()
except Exception as e:
return {"ok": False, "error": str(e)}
async def cast_rtmp_start(self, url: str) -> dict:
r = await self._post("/cast/rtmp/start", data={"url": url})
r.raise_for_status()
return r.json()
async def cast_rtmp_stop(self) -> dict:
r = await self._post("/cast/rtmp/stop")
r.raise_for_status()
return r.json()
async def processes(self, count: int = 15) -> dict:
if self.should_use_relay():
res = await commander_relay.send_command(self.name, "processes", {"limit": count}, timeout=12.0)
if res.get("ok"):
return {"processes": res.get("processes", [])}
r = await self._get(f"/processes?count={count}")
r.raise_for_status()
return r.json()
async def kill_process(self, target: str) -> dict:
if self.should_use_relay():
res = await commander_relay.send_command(self.name, "kill_process", {"target": target}, timeout=10.0)
return {"success": res.get("ok", False), "message": res.get("msg", "")}
r = await self._post("/kill", data={"target": target})
r.raise_for_status()
return r.json()
async def run_cmd(self, command: str) -> dict:
if self.should_use_relay():
res = await commander_relay.send_command(self.name, "cmd", {"command": command}, timeout=40.0)
return {"output": res.get("output", "")}
r = await self._post("/cmd", data={"command": command}, timeout=60.0)
r.raise_for_status()
return r.json()
async def open_target(self, target: str) -> dict:
r = await self._post("/open", data={"target": target})
r.raise_for_status()
return r.json()
async def browse_directory(self, path: str = "") -> dict:
if self.should_use_relay():
res = await commander_relay.send_command(self.name, "file_browse", {"path": path}, timeout=15.0)
if res.get("ok") or "error" in res:
return res
try:
r = await self._get(f"/browse?path={urllib.parse.quote(path)}", timeout=15.0)
r.raise_for_status()
return r.json()
except Exception as e:
return {"ok": False, "error": str(e), "items": [], "current_path": path}
async def get_file(self, path: str, chat_id: Optional[int] = None) -> Tuple[bytes, str]:
if self.should_use_relay() and chat_id:
res = await commander_relay.send_command(self.name, "file_download", {"path": path, "chat_id": chat_id}, timeout=60.0)
if res.get("ok"):
return b"", "direct_upload"
else:
raise Exception(res.get("error", "File download failed over relay"))
r = await self._get(f"/file?path={urllib.parse.quote(path)}", timeout=60.0)
r.raise_for_status()
filename = Path(path).name or "file"
cd = r.headers.get("content-disposition", "")
if "filename=" in cd:
filename = cd.split("filename=")[-1].strip('"')
return r.content, filename
async def upload_file(self, filename: str, content: bytes) -> dict:
import base64
if self.is_local:
try:
files = {"file": (filename, content)}
r = await self._post("/upload", files=files, timeout=60.0)
r.raise_for_status()
return r.json()
except Exception as e:
logger.debug(f"Local upload_file HTTP failed: {e}. Trying relay...")
if self.should_use_relay():
if len(content) > 3 * 1024 * 1024:
raise Exception("File too large for cloud relay (>3MB). Send smaller files or use local network.")
b64 = base64.b64encode(content).decode("ascii")
res = await commander_relay.send_command(self.name, "file_upload", {"filename": filename, "data_b64": b64}, timeout=30.0)
if res.get("ok"):
return {"success": True, "path": res.get("path", filename), "auto_played": res.get("auto_played", False)}
raise Exception(res.get("error", "Remote upload failed"))
files = {"file": (filename, content)}
r = await self._post("/upload", files=files, timeout=60.0)
r.raise_for_status()
return r.json()
async def get_clipboard(self) -> str:
if self.should_use_relay():
res = await commander_relay.send_command(self.name, "clipboard_get", timeout=10.0)
return res.get("text", "")
r = await self._get("/clipboard")
r.raise_for_status()
return r.json().get("content", "")
async def set_clipboard(self, text: str) -> bool:
if self.should_use_relay():
res = await commander_relay.send_command(self.name, "clipboard_set", {"text": text}, timeout=10.0)
return res.get("ok", False)
r = await self._post("/clipboard", data={"text": text})
r.raise_for_status()
return r.json().get("success", False)
async def speak(self, text: str) -> bool:
if self.should_use_relay():
res = await commander_relay.send_command(self.name, "tts", {"text": text}, timeout=15.0)
return res.get("ok", False)
r = await self._post("/tts", data={"text": text})
r.raise_for_status()
return r.json().get("success", False)
async def play_audio(self, filename: str, content: bytes) -> dict:
import base64
if self.is_local:
try:
files = {"file": (filename, content)}
r = await self._post("/play-audio", files=files, timeout=60.0)
r.raise_for_status()
return r.json()
except Exception as e:
logger.debug(f"Local play_audio HTTP failed: {e}. Trying relay...")
if self.should_use_relay():
if len(content) > 3 * 1024 * 1024:
return {"success": False, "ok": False, "message": "Audio file too large for cloud relay (>3MB)."}
b64 = base64.b64encode(content).decode("ascii")
res = await commander_relay.send_command(self.name, "play_audio", {"filename": filename, "data_b64": b64}, timeout=30.0)
return {"success": res.get("ok", False), "ok": res.get("ok", False), "message": res.get("msg", res.get("error", ""))}
files = {"file": (filename, content)}
r = await self._post("/play-audio", files=files, timeout=60.0)
r.raise_for_status()
return r.json()
async def power_sleep(self) -> dict:
if self.should_use_relay():
return await commander_relay.send_command(self.name, "sleep", timeout=10.0)
r = await self._post("/power/sleep")
r.raise_for_status()
return r.json()
async def power_lock(self) -> dict:
if self.should_use_relay():
return await commander_relay.send_command(self.name, "lock", timeout=10.0)
r = await self._post("/power/lock")
r.raise_for_status()
return r.json()
async def power_shutdown(self, delay: int = 0) -> dict:
if self.should_use_relay():
return await commander_relay.send_command(self.name, "shutdown", {"delay": delay}, timeout=10.0)
r = await self._post(f"/power/shutdown?delay={delay}")
r.raise_for_status()
return r.json()
async def power_restart(self, delay: int = 5) -> dict:
if self.should_use_relay():
return await commander_relay.send_command(self.name, "restart", {"delay": delay}, timeout=10.0)
r = await self._post(f"/power/restart?delay={delay}")
r.raise_for_status()
return r.json()
async def power_cancel_shutdown(self) -> bool:
if self.should_use_relay():
res = await commander_relay.send_command(self.name, "cancel_shutdown", timeout=10.0)
return res.get("ok", False)
r = await self._post("/power/cancel-shutdown")
return r.json().get("success", False)
async def monitor_on(self) -> dict:
if self.should_use_relay():
return await commander_relay.send_command(self.name, "monitor_on", timeout=10.0)
r = await self._post("/monitor/on")
r.raise_for_status()
return r.json()
async def monitor_off(self) -> dict:
if self.should_use_relay():
return await commander_relay.send_command(self.name, "monitor_off", timeout=10.0)
r = await self._post("/monitor/off")
r.raise_for_status()
return r.json()
async def media_control(self, action: str):
if self.should_use_relay():
await commander_relay.send_command(self.name, "media_key", {"action": action}, timeout=10.0)
return
await self._post(f"/media/{action}")
async def alarm_status(self) -> dict:
r = await self._get("/alarm/status")
r.raise_for_status()
return r.json()
async def alarm_set(self, seconds: int, label: str) -> dict:
r = await self._post("/alarm/set", data={"seconds": seconds, "label": label})
r.raise_for_status()
return r.json()
async def alarm_stop(self) -> bool:
if self.should_use_relay():
res = await commander_relay.send_command(self.name, "alarm_stop", timeout=10.0)
return res.get("ok", False)
r = await self._post("/alarm/stop")
return r.json().get("success", False)
async def alarm_cancel(self) -> bool:
r = await self._post("/alarm/cancel")
return r.json().get("success", False)
async def alarm_trigger_now(self, label: str = "Instant Alert") -> dict:
if self.should_use_relay():
res = await commander_relay.send_command(self.name, "alarm_start", {"duration": 30, "label": label}, timeout=10.0)
return {"success": res.get("ok", False), "message": res.get("msg", "")}
r = await self._post("/alarm/trigger-now", data={"label": label})
return r.json()
async def alarm_parse_time(self, raw_input: str) -> dict:
r = await self._post("/alarm/parse-time", data={"raw_input": raw_input})
return r.json()
async def clean_scan(self) -> dict:
if self.should_use_relay():
return await commander_relay.send_command(self.name, "clean_scan", timeout=25.0)
r = await self._get("/clean/scan")
return r.json()
async def clean_execute(self) -> dict:
if self.should_use_relay():
return await commander_relay.send_command(self.name, "clean_execute", timeout=25.0)
r = await self._post("/clean/execute")
return r.json()
async def get_events(self) -> list:
try:
r = await self._get("/events", timeout=3.0)
r.raise_for_status()
return r.json().get("events", [])
except Exception:
return []
# ═══════════════════════════════════════════════════════════════════════
# SECURITY & LOCKS
# ═══════════════════════════════════════════════════════════════════════
unauthorized_alert_cooldown: dict[int, float] = {}
authenticated_sessions: dict[int, float] = {}
failed_login_attempts: dict[int, list[float]] = {}
def is_authorized(user_id: int) -> bool:
if not config.AUTHORIZED_USER_IDS:
return False
return user_id in config.AUTHORIZED_USER_IDS
def is_authenticated(user_id: int) -> bool:
if not config.BOT_PIN:
return True
expiry = authenticated_sessions.get(user_id, 0)
return datetime.now().timestamp() < expiry
async def check_access(update: Update, context: ContextTypes.DEFAULT_TYPE) -> bool:
user = update.effective_user
if not user or not is_authorized(user.id):
await notify_unauthorized_access(update, context)
return False
if not is_authenticated(user.id):
text = (
"🔒 <b>COMMAND CENTER LOCKED</b>\n"
"━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n"
"PIN security is enabled on this Sentinel.\n"
"Please authenticate to access commands:\n\n"
"👉 <code>/login YOUR_PIN</code>"
)
if update.callback_query:
await update.callback_query.answer("🔒 Bot is locked. Send /login <PIN> to unlock.", show_alert=True)
else:
await update.effective_message.reply_text(text, parse_mode="HTML")
return False
return True
async def notify_unauthorized_access(update: Update, context: ContextTypes.DEFAULT_TYPE):
user = update.effective_user
user_id = user.id if user else 0
username = f"@{user.username}" if user and user.username else f"User {user_id}"
now = datetime.now().timestamp()
if now - unauthorized_alert_cooldown.get(user_id, 0) < 60:
return
unauthorized_alert_cooldown[user_id] = now
action = update.message.text if update.message and update.message.text else (
update.callback_query.data if update.callback_query else "Unknown"
)
logger.warning(f"🚨 UNAUTHORIZED ACCESS BLOCKED: {username} ({user_id}) -> {action}")
alert_text = (
f"🚨 <b>SECURITY ALERT: UNAUTHORIZED ACCESS BLOCKED</b>\n"
f"━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n"
f"👤 <b>Attempted By:</b> {html.escape(username)} (ID: <code>{user_id}</code>)\n"
f"🕒 <b>Timestamp:</b> <code>{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}</code>\n"
f"🎯 <b>Action:</b> <code>{html.escape(action[:120])}</code>\n\n"
f"🛡️ <i>The request was immediately denied and blocked by Sentinel.</i>"
)
for owner_id in config.AUTHORIZED_USER_IDS:
try:
await context.bot.send_message(chat_id=owner_id, text=alert_text, parse_mode="HTML")
except Exception:
pass
# ═══════════════════════════════════════════════════════════════════════
# PC SELECTION HELPERS
# ═══════════════════════════════════════════════════════════════════════
def get_selected_pc(context: ContextTypes.DEFAULT_TYPE) -> Optional[dict]:
"""Get the currently selected PC info from user session (defaults to Host PC or first available)."""
pc = context.user_data.get("selected_pc")
if pc:
return pc
fleet = load_fleet()
pcs = fleet.get("pcs", [])
if pcs:
host_pc = next((p for p in pcs if p.get("is_host")), pcs[0])
context.user_data["selected_pc"] = host_pc
return host_pc
return None
def get_agent(context: ContextTypes.DEFAULT_TYPE) -> Optional[AgentClient]:
"""Get AgentClient for currently selected PC."""
pc = get_selected_pc(context)
if not pc:
return None
fleet = load_fleet()
return AgentClient(pc, get_fleet_secret(fleet))
async def require_pc(update: Update, context: ContextTypes.DEFAULT_TYPE) -> Optional[AgentClient]:
"""Require a PC to be selected. Returns agent or None (with user prompt)."""
agent = get_agent(context)
if not agent:
await show_pc_picker(update, context, prompt="⚠️ <b>No PC selected!</b>\nPlease select a PC first:")
return None
return agent
# ═══════════════════════════════════════════════════════════════════════
# PC PICKER KEYBOARD
# ═══════════════════════════════════════════════════════════════════════
async def check_fleet_health(fleet: dict) -> Dict[str, dict]:
"""Check which PCs are online via Cloud Relay or LAN."""
results = {}
secret = get_fleet_secret(fleet)
relay_pcs = commander_relay.get_pc_list() if (commander_relay and commander_relay.is_connected) else {}
# Auto-register any new PCs discovered over the relay into fleet['pcs']!
known_names = {pc["name"] for pc in fleet.get("pcs", [])}
changed = False
for r_name, r_info in relay_pcs.items():
if r_name not in known_names:
fleet.setdefault("pcs", []).append({
"name": r_name,
"label": r_name,
"ip": r_info.get("ip", "Unknown"),
"network": r_info.get("network", "Remote"),
})
known_names.add(r_name)
changed = True
if changed:
save_fleet(fleet)
async def _check(pc):
name = pc["name"]
# 1. Check Cloud Relay
if name in relay_pcs and relay_pcs[name].get("status") == "online":
results[name] = {
"online": True,
"network": relay_pcs[name].get("network", "Online (Relay)"),
}
return
# 2. Check local LAN HTTP
client = AgentClient(pc, secret)
health = await client.health()
if health:
results[name] = {
"online": True,
"network": health.get("network", f"LAN ({pc.get('ip', 'Local')})"),
}
else:
results[name] = {
"online": False,
"network": "Offline",
}
await asyncio.gather(*[_check(pc) for pc in fleet["pcs"]], return_exceptions=True)
return results
def get_pc_picker_keyboard(fleet: dict, health: Dict[str, dict]) -> InlineKeyboardMarkup:
"""Build PC selector keyboard with online/offline indicators."""
buttons = []
row = []
for i, pc in enumerate(fleet["pcs"]):
name = pc["name"]
label = pc.get("label", name)
h_info = health.get(name, {})
is_online = h_info.get("online", False)
emoji = "🟢" if is_online else "🔴"
btn_text = f"{emoji} {label}"
row.append(InlineKeyboardButton(btn_text, callback_data=f"pc_select_{i}"))
if len(row) == 2:
buttons.append(row)
row = []
if row:
buttons.append(row)
buttons.append([
InlineKeyboardButton("✏️ Rename PC", callback_data="fleet_rename_menu"),
InlineKeyboardButton("📊 Overview", callback_data="fleet_overview"),
InlineKeyboardButton("🔄 Refresh", callback_data="fleet_refresh"),
])
return InlineKeyboardMarkup(buttons)
async def show_pc_picker(update: Update, context: ContextTypes.DEFAULT_TYPE, prompt: str = None):
"""Show the PC selection menu."""
fleet = load_fleet()
health = await check_fleet_health(fleet)
if not fleet["pcs"]:
text = (
"⚠️ <b>NO PCs REGISTERED</b>\n\n"
"No PCs have been registered yet.\n"
"Plug your USB pendrive into any PC and double-click <code>install.bat</code>.\n\n"
"The PC will automatically register and appear here within seconds."
)
if update.callback_query:
await update.callback_query.edit_message_text(text, parse_mode="HTML")
else:
await update.effective_message.reply_text(text, parse_mode="HTML")
return
online_count = sum(1 for v in health.values() if v.get("online"))
header = prompt or (
f"🛡️ <b>PC REMOTE SENTINEL — FLEET COMMAND CENTER</b>\n"
f"━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n"
f"📡 <b>Fleet Status:</b> <code>{online_count}/{len(fleet['pcs'])}</code> PCs online\n\n"
f"<i>Select a PC to control:</i>"
)
keyboard = get_pc_picker_keyboard(fleet, health)
if update.callback_query:
try:
await update.callback_query.edit_message_text(header, reply_markup=keyboard, parse_mode="HTML")
except Exception:
await update.effective_message.reply_text(header, reply_markup=keyboard, parse_mode="HTML")
else:
await update.effective_message.reply_text(header, reply_markup=keyboard, parse_mode="HTML")
async def show_rename_menu(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Show PC rename selector or direct prompt."""
fleet = load_fleet()
pcs = fleet.get("pcs", [])
if not pcs:
await show_pc_picker(update, context)
return
if len(pcs) == 1:
target_pc = pcs[0]
context.user_data["awaiting_pc_rename"] = target_pc["name"]
label = target_pc.get("label", target_pc["name"])
prompt_text = (
f"✏️ <b>RENAME PC: {html.escape(label)}</b>\n"
f"━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n"
f"Hostname: <code>{html.escape(target_pc['name'])}</code>\n\n"
f"Please <b>type and send the new name</b> for this PC in this chat:\n"
f"<i>(e.g., 'Front Desk PC', 'Gaming Rig', 'Living Room Laptop')</i>\n\n"
f"<i>Send /cancel to abort.</i>"
)
cancel_kb = InlineKeyboardMarkup([[InlineKeyboardButton("❌ Cancel", callback_data="fleet_picker")]])
if update.callback_query:
await update.callback_query.edit_message_text(prompt_text, reply_markup=cancel_kb, parse_mode="HTML")
else:
await update.effective_message.reply_text(prompt_text, reply_markup=cancel_kb, parse_mode="HTML")
return
buttons = []
row = []
for i, pc in enumerate(pcs):
name = pc["name"]
label = pc.get("label", name)
btn_text = f"✏️ {label}"
row.append(InlineKeyboardButton(btn_text, callback_data=f"cb_rename_pick_{i}"))
if len(row) == 2:
buttons.append(row)
row = []
if row:
buttons.append(row)
buttons.append([InlineKeyboardButton("🔙 Back to PC List", callback_data="fleet_picker")])
menu_text = (
"✏️ <b>SELECT A PC TO RENAME</b>\n"
"━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n"
"Tap the PC you want to give a friendly custom name:"
)
kb = InlineKeyboardMarkup(buttons)
if update.callback_query:
await update.callback_query.edit_message_text(menu_text, reply_markup=kb, parse_mode="HTML")
else:
await update.effective_message.reply_text(menu_text, reply_markup=kb, parse_mode="HTML")
# ═══════════════════════════════════════════════════════════════════════
# COMMAND CENTER KEYBOARDS (same layout as before, with "Back to PCs")
# ═══════════════════════════════════════════════════════════════════════
def get_main_keyboard() -> InlineKeyboardMarkup:
return InlineKeyboardMarkup([
[
InlineKeyboardButton("📊 System Status", callback_data="cb_status"),
InlineKeyboardButton("📸 Screenshot", callback_data="cb_shot"),
],
[
InlineKeyboardButton("📺 Live Screen Cast", callback_data="cb_cast_menu"),
InlineKeyboardButton("🖱️ Remote Mouse & Type", callback_data="cb_mouse_menu"),
],
[
InlineKeyboardButton("🪟 Desktops & Windows", callback_data="cb_desktop_menu"),
InlineKeyboardButton("🎥 Screen Video", callback_data="cb_screen_menu"),
],
[
InlineKeyboardButton("📷 Webcam Menu", callback_data="cb_webcam_menu"),