lapctl 0.1.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,574 @@
1
+ """Linux Wayland/Hyprland driver implementation."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import glob
6
+ import os
7
+ import re
8
+ import shlex
9
+ import shutil
10
+ import subprocess
11
+ import sys
12
+ import time
13
+ from pathlib import Path
14
+ from typing import Literal
15
+
16
+ from lapctl.drivers.base import BaseDriver, NotSupported
17
+
18
+
19
+ def auto_detect_gui_env() -> None:
20
+ """Import or detect Wayland/Hyprland/X11 GUI environment variables."""
21
+ try:
22
+ out = subprocess.check_output(["systemctl", "--user", "show-environment"], text=True)
23
+ for line in out.splitlines():
24
+ if "=" in line:
25
+ key, val = line.split("=", 1)
26
+ if key in [
27
+ "WAYLAND_DISPLAY",
28
+ "DISPLAY",
29
+ "HYPRLAND_INSTANCE_SIGNATURE",
30
+ "DBUS_SESSION_BUS_ADDRESS",
31
+ "XDG_RUNTIME_DIR",
32
+ "XDG_CURRENT_DESKTOP",
33
+ ]:
34
+ os.environ[key] = val
35
+ except Exception:
36
+ pass
37
+
38
+ uid = os.getuid()
39
+ runtime_dir = os.environ.get("XDG_RUNTIME_DIR", f"/run/user/{uid}")
40
+ if not os.path.exists(runtime_dir):
41
+ return
42
+
43
+ w_display = os.environ.get("WAYLAND_DISPLAY")
44
+ if w_display and not os.path.exists(os.path.join(runtime_dir, w_display)):
45
+ del os.environ["WAYLAND_DISPLAY"]
46
+
47
+ h_signature = os.environ.get("HYPRLAND_INSTANCE_SIGNATURE")
48
+ if h_signature and not os.path.exists(
49
+ os.path.join(runtime_dir, "hypr", h_signature, ".socket.sock")
50
+ ):
51
+ del os.environ["HYPRLAND_INSTANCE_SIGNATURE"]
52
+
53
+ display = os.environ.get("DISPLAY")
54
+ if display:
55
+ try:
56
+ disp_num = display.replace(":", "")
57
+ if not os.path.exists(f"/tmp/.X11-unix/X{disp_num}"):
58
+ del os.environ["DISPLAY"]
59
+ except Exception:
60
+ pass
61
+
62
+ if "WAYLAND_DISPLAY" not in os.environ:
63
+ wayland_sockets = []
64
+ try:
65
+ for name in os.listdir(runtime_dir):
66
+ if re.match(r"^wayland-\d+$", name):
67
+ wayland_sockets.append(name)
68
+ except Exception:
69
+ pass
70
+ if wayland_sockets:
71
+ wayland_sockets.sort()
72
+ os.environ["WAYLAND_DISPLAY"] = wayland_sockets[0]
73
+
74
+ if "HYPRLAND_INSTANCE_SIGNATURE" not in os.environ:
75
+ hypr_dir = os.path.join(runtime_dir, "hypr")
76
+ if os.path.exists(hypr_dir):
77
+ try:
78
+ for entry in os.listdir(hypr_dir):
79
+ entry_path = os.path.join(hypr_dir, entry)
80
+ if os.path.isdir(entry_path):
81
+ if os.path.exists(os.path.join(entry_path, ".socket.sock")):
82
+ os.environ["HYPRLAND_INSTANCE_SIGNATURE"] = entry
83
+ break
84
+ except Exception:
85
+ pass
86
+
87
+ if "DISPLAY" not in os.environ:
88
+ x11_displays = glob.glob("/tmp/.X11-unix/X*")
89
+ if x11_displays:
90
+ try:
91
+ disp_num = x11_displays[0].split("/X")[-1]
92
+ os.environ["DISPLAY"] = f":{disp_num}"
93
+ except Exception:
94
+ pass
95
+
96
+
97
+ class LinuxHyprlandDriver(BaseDriver):
98
+ """Driver for Arch Linux / Wayland / Hyprland."""
99
+
100
+ name = "linux_hyprland"
101
+ capabilities = frozenset(
102
+ {
103
+ "system_status",
104
+ "system_health",
105
+ "processes",
106
+ "logs",
107
+ "network",
108
+ "network_ip",
109
+ "lock",
110
+ "power",
111
+ "audio_volume",
112
+ "audio_mute",
113
+ "audio_beep",
114
+ "media",
115
+ "brightness",
116
+ "notify",
117
+ "screenshot",
118
+ "webcam_photo",
119
+ "webcam_video",
120
+ "screenrecord",
121
+ "mic_record",
122
+ "files_read",
123
+ "files_write",
124
+ "clipboard_read",
125
+ "clipboard_write",
126
+ "browser",
127
+ "wallpaper",
128
+ "tts",
129
+ "geoip",
130
+ "ntfy",
131
+ "mouse",
132
+ "keyboard",
133
+ "shell",
134
+ }
135
+ )
136
+
137
+ @classmethod
138
+ def detect(cls) -> bool:
139
+ """Return True on Linux when a Hyprland session is detected."""
140
+ if not sys.platform.startswith("linux"):
141
+ return False
142
+ if os.environ.get("HYPRLAND_INSTANCE_SIGNATURE"):
143
+ return True
144
+ desktop = os.environ.get("XDG_CURRENT_DESKTOP", "").lower()
145
+ if "hyprland" in desktop:
146
+ return True
147
+ runtime_dir = os.environ.get("XDG_RUNTIME_DIR", f"/run/user/{os.getuid()}")
148
+ return os.path.isdir(os.path.join(runtime_dir, "hypr"))
149
+
150
+ def prepare_env(self) -> None:
151
+ auto_detect_gui_env()
152
+
153
+ def get_battery_state(self) -> tuple[int, bool, bool] | None:
154
+ total_energy_now = 0
155
+ total_energy_full = 0
156
+ for b in ["BAT0", "BAT1"]:
157
+ en_path = f"/sys/class/power_supply/{b}/energy_now"
158
+ ef_path = f"/sys/class/power_supply/{b}/energy_full"
159
+ if os.path.exists(en_path) and os.path.exists(ef_path):
160
+ try:
161
+ with open(en_path, "r") as f:
162
+ total_energy_now += int(f.read().strip())
163
+ with open(ef_path, "r") as f:
164
+ total_energy_full += int(f.read().strip())
165
+ except Exception:
166
+ pass
167
+
168
+ cap: int | None = None
169
+ if total_energy_full > 0:
170
+ cap = int(round((total_energy_now / total_energy_full) * 100))
171
+ else:
172
+ for b in ["BAT0", "BAT1"]:
173
+ cap_path = f"/sys/class/power_supply/{b}/capacity"
174
+ if os.path.exists(cap_path):
175
+ try:
176
+ with open(cap_path, "r") as f:
177
+ cap = int(f.read().strip())
178
+ break
179
+ except Exception:
180
+ pass
181
+
182
+ if cap is None:
183
+ return None
184
+
185
+ is_discharging = False
186
+ is_charging_or_full = False
187
+ for b in ["BAT0", "BAT1"]:
188
+ status_path = f"/sys/class/power_supply/{b}/status"
189
+ if os.path.exists(status_path):
190
+ try:
191
+ with open(status_path, "r") as f:
192
+ state = f.read().strip().lower()
193
+ if "discharging" in state:
194
+ is_discharging = True
195
+ if "charging" in state or "full" in state:
196
+ is_charging_or_full = True
197
+ except Exception:
198
+ pass
199
+
200
+ return cap, is_discharging, is_charging_or_full
201
+
202
+ def get_system_status(self) -> str:
203
+ status: list[str] = []
204
+
205
+ bat_path = "/sys/class/power_supply/BAT0/capacity"
206
+ if os.path.exists(bat_path):
207
+ with open(bat_path, "r") as f:
208
+ cap = f.read().strip()
209
+ status_path = "/sys/class/power_supply/BAT0/status"
210
+ state = ""
211
+ if os.path.exists(status_path):
212
+ with open(status_path, "r") as f:
213
+ state = f" ({f.read().strip()})"
214
+ status.append(f"🔋 *Baterai:* {cap}%{state}")
215
+
216
+ try:
217
+ mem_total = 0
218
+ mem_avail = 0
219
+ with open("/proc/meminfo", "r") as f:
220
+ for line in f:
221
+ if "MemTotal" in line:
222
+ mem_total = int(line.split()[1])
223
+ if "MemAvailable" in line:
224
+ mem_avail = int(line.split()[1])
225
+ if mem_total > 0:
226
+ ram_used = mem_total - mem_avail
227
+ ram_pct = round((ram_used / mem_total) * 100, 1)
228
+ status.append(
229
+ f"🧠 *RAM Terpakai:* {ram_pct}% "
230
+ f"({round(ram_used / 1024 / 1024, 2)} GB / {round(mem_total / 1024 / 1024, 2)} GB)"
231
+ )
232
+ except Exception:
233
+ pass
234
+
235
+ try:
236
+ load = os.getloadavg()
237
+ status.append(f"💻 *Load Avg:* {load[0]}, {load[1]}, {load[2]}")
238
+ except Exception:
239
+ pass
240
+
241
+ try:
242
+ vol_out = subprocess.check_output(
243
+ ["wpctl", "get-volume", "@DEFAULT_AUDIO_SINK@"], text=True
244
+ ).strip()
245
+ status.append(f"🔊 *Audio:* {vol_out}")
246
+ except Exception:
247
+ pass
248
+
249
+ try:
250
+ bright_out = subprocess.check_output(["brightnessctl", "-m"], text=True).strip()
251
+ parts = bright_out.split(",")
252
+ if len(parts) >= 4:
253
+ status.append(f"💡 *Kecerahan:* {parts[3]}")
254
+ except Exception:
255
+ pass
256
+
257
+ try:
258
+ wifi_out = subprocess.check_output(
259
+ ["nmcli", "-t", "-f", "active,ssid,signal", "dev", "wifi"], text=True
260
+ )
261
+ connected_wifi = ""
262
+ for line in wifi_out.splitlines():
263
+ if line.startswith("yes:"):
264
+ parts = line.split(":")
265
+ if len(parts) >= 3:
266
+ connected_wifi = f"📶 *WiFi:* {parts[1]} ({parts[2]}%)"
267
+ break
268
+ if connected_wifi:
269
+ status.append(connected_wifi)
270
+ else:
271
+ status.append("📶 *WiFi:* Terputus")
272
+ except Exception:
273
+ pass
274
+
275
+ return "\n".join(status)
276
+
277
+ def get_system_health(self) -> tuple[str, str, float, float, float]:
278
+ with open("/proc/uptime", "r") as f:
279
+ uptime_seconds = float(f.readline().split()[0])
280
+ uptime_str = f"{int(uptime_seconds // 3600)}j {int((uptime_seconds % 3600) // 60)}m"
281
+
282
+ temp = "N/A"
283
+ for path in [
284
+ "/sys/class/thermal/thermal_zone0/temp",
285
+ "/sys/class/hwmon/hwmon0/temp1_input",
286
+ "/sys/class/hwmon/hwmon1/temp1_input",
287
+ ]:
288
+ if os.path.exists(path):
289
+ with open(path, "r") as f:
290
+ temp = f"{round(int(f.read().strip()) / 1000.0, 1)}°C"
291
+ break
292
+
293
+ total, used, free = shutil.disk_usage("/")
294
+ disk_used_pct = round((used / total) * 100, 1)
295
+ disk_free_gb = round(free / (1024**3), 1)
296
+ disk_total_gb = round(total / (1024**3), 1)
297
+ return uptime_str, temp, disk_used_pct, disk_free_gb, disk_total_gb
298
+
299
+ def list_processes(self) -> str:
300
+ res = subprocess.run(
301
+ ["ps", "-eo", "pid,%cpu,%mem,comm", "--sort=-%cpu"],
302
+ capture_output=True,
303
+ text=True,
304
+ timeout=10,
305
+ check=True,
306
+ )
307
+ lines = res.stdout.splitlines()[:11]
308
+ return "\n".join(lines) + ("\n" if lines else "")
309
+
310
+ def get_logs(self) -> str:
311
+ res = subprocess.run(
312
+ ["journalctl", "--user", "-u", "telegram-remote-bot.service", "-n", "20", "--no-pager"],
313
+ capture_output=True,
314
+ text=True,
315
+ timeout=10,
316
+ check=True,
317
+ )
318
+ return res.stdout
319
+
320
+ def get_network_info(self) -> tuple[str, str]:
321
+ ping_out = "N/A"
322
+ try:
323
+ ping_res = subprocess.check_output(["ping", "-c", "1", "8.8.8.8"], text=True)
324
+ for line in ping_res.splitlines():
325
+ if "time=" in line:
326
+ ping_out = line.split("time=")[1].split()[0] + " ms"
327
+ except Exception:
328
+ ping_out = "RTO / Tidak terhubung internet"
329
+
330
+ interfaces = subprocess.check_output(["ip", "-br", "addr", "show", "up"], text=True)
331
+ return ping_out, interfaces
332
+
333
+ def screenshot(self, output_path: str) -> None:
334
+ subprocess.run(["grim", output_path], check=True)
335
+
336
+ def webcam_photo(self, output_path: str) -> None:
337
+ subprocess.run(
338
+ [
339
+ "ffmpeg",
340
+ "-f",
341
+ "v4l2",
342
+ "-video_size",
343
+ "640x480",
344
+ "-i",
345
+ "/dev/video0",
346
+ "-ss",
347
+ "00:00:01",
348
+ "-frames:v",
349
+ "1",
350
+ output_path,
351
+ "-y",
352
+ ],
353
+ check=True,
354
+ stdout=subprocess.DEVNULL,
355
+ stderr=subprocess.DEVNULL,
356
+ )
357
+
358
+ def webcam_video(self, output_path: str, duration: int) -> None:
359
+ subprocess.run(
360
+ [
361
+ "ffmpeg",
362
+ "-f",
363
+ "v4l2",
364
+ "-video_size",
365
+ "640x480",
366
+ "-i",
367
+ "/dev/video0",
368
+ "-t",
369
+ str(duration),
370
+ output_path,
371
+ "-y",
372
+ ],
373
+ check=True,
374
+ stdout=subprocess.DEVNULL,
375
+ stderr=subprocess.DEVNULL,
376
+ )
377
+
378
+ def record_audio(self, output_path: str, duration: int) -> None:
379
+ subprocess.run(
380
+ [
381
+ "ffmpeg",
382
+ "-f",
383
+ "pulse",
384
+ "-i",
385
+ "default",
386
+ "-t",
387
+ str(duration),
388
+ output_path,
389
+ "-y",
390
+ ],
391
+ check=True,
392
+ stdout=subprocess.DEVNULL,
393
+ stderr=subprocess.DEVNULL,
394
+ )
395
+
396
+ def screenrecord(self, output_path: str, duration: int) -> None:
397
+ if (
398
+ subprocess.run(
399
+ ["which", "wf-recorder"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL
400
+ ).returncode
401
+ != 0
402
+ ):
403
+ raise NotSupported(
404
+ "screenrecord",
405
+ "⚠️ *Perlu Menginstal wf-recorder*\n\n"
406
+ "Fitur perekaman layar membutuhkan `wf-recorder`. Silakan jalankan perintah ini di terminal laptop Anda:\n"
407
+ "`sudo pacman -S wf-recorder`",
408
+ )
409
+ if os.path.exists(output_path):
410
+ os.remove(output_path)
411
+ subprocess.run(
412
+ [
413
+ "timeout",
414
+ "--signal=SIGINT",
415
+ str(duration),
416
+ "wf-recorder",
417
+ "-f",
418
+ output_path,
419
+ ],
420
+ stdout=subprocess.DEVNULL,
421
+ stderr=subprocess.DEVNULL,
422
+ )
423
+ time.sleep(0.5)
424
+
425
+ def play_audio_url(self, url: str, loop_count: int = 1) -> None:
426
+ mpv_args = [
427
+ "mpv",
428
+ "--no-video",
429
+ "--user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64)",
430
+ ]
431
+ if loop_count > 1:
432
+ mpv_args.append(f"--loop-file={loop_count - 1}")
433
+ mpv_args.append(url)
434
+ subprocess.Popen(mpv_args)
435
+
436
+ def open_url(self, url: str) -> None:
437
+ subprocess.Popen(["xdg-open", url])
438
+
439
+ def lock_screen(self) -> None:
440
+ subprocess.Popen(["hyprlock"])
441
+
442
+ def power_action(self, action: Literal["suspend", "reboot", "shutdown"]) -> None:
443
+ unit_map = {
444
+ "suspend": "suspend",
445
+ "reboot": "reboot",
446
+ "shutdown": "poweroff",
447
+ }
448
+ subprocess.run(["systemctl", unit_map[action]], timeout=10)
449
+
450
+ def set_volume(self, level: int) -> None:
451
+ vol_scale = level / 100.0
452
+ subprocess.run(["wpctl", "set-volume", "@DEFAULT_AUDIO_SINK@", f"{vol_scale}"], check=True)
453
+ subprocess.run(["wpctl", "set-mute", "@DEFAULT_AUDIO_SINK@", "0"], check=False)
454
+
455
+ def set_mute(self, muted: bool) -> None:
456
+ subprocess.run(
457
+ ["wpctl", "set-mute", "@DEFAULT_AUDIO_SINK@", "1" if muted else "0"], check=True
458
+ )
459
+
460
+ def step_volume(self, delta: str) -> str:
461
+ subprocess.run(["wpctl", "set-volume", "@DEFAULT_AUDIO_SINK@", delta], check=True)
462
+ return subprocess.check_output(
463
+ ["wpctl", "get-volume", "@DEFAULT_AUDIO_SINK@"], text=True
464
+ ).strip()
465
+
466
+ def media_control(self, action: Literal["play", "pause", "next", "previous"]) -> None:
467
+ subprocess.run(["playerctl", action], check=True)
468
+
469
+ def play_beep(self, sound_type: str) -> None:
470
+ sound_map = {
471
+ "normal": "/usr/share/sounds/freedesktop/stereo/message-new-instant.oga",
472
+ "alert": "/usr/share/sounds/freedesktop/stereo/suspend-error.oga",
473
+ "camera": "/usr/share/sounds/freedesktop/stereo/camera-shutter.oga",
474
+ "success": "/usr/share/sounds/freedesktop/stereo/complete.oga",
475
+ }
476
+ sound_file = sound_map.get(sound_type, sound_map["normal"])
477
+ subprocess.Popen(["paplay", sound_file])
478
+
479
+ def set_brightness(self, level: int) -> None:
480
+ subprocess.run(["brightnessctl", "set", f"{level}%"], check=True)
481
+
482
+ def notify(self, title: str, message: str) -> None:
483
+ subprocess.run(["notify-send", title, message, "-i", "terminal"], check=True)
484
+
485
+ def set_wallpaper(self, path: str) -> None:
486
+ subprocess.run(["swww", "img", path], check=True)
487
+
488
+ def get_clipboard(self) -> str:
489
+ try:
490
+ return subprocess.check_output(["wl-paste"], text=True)
491
+ except subprocess.CalledProcessError:
492
+ return ""
493
+
494
+ def set_clipboard(self, text: str) -> int:
495
+ process = subprocess.Popen(["wl-copy"], stdin=subprocess.PIPE, text=True)
496
+ process.communicate(input=text)
497
+ return process.returncode
498
+
499
+ def get_cursor_pos(self) -> str:
500
+ return subprocess.check_output(["hyprctl", "cursorpos"], text=True).strip()
501
+
502
+ def move_cursor(self, x: int, y: int) -> None:
503
+ subprocess.run(["hyprctl", "dispatch", "movecursor", f"{x} {y}"], check=True)
504
+
505
+ def mouse_click(self) -> None:
506
+ subprocess.run(["xdotool", "click", "1"], check=True)
507
+
508
+ def keyboard_type(self, text: str) -> None:
509
+ subprocess.run(["xdotool", "type", text], check=True)
510
+
511
+ def keyboard_key(self, key: str) -> None:
512
+ subprocess.run(["xdotool", "key", key], check=True)
513
+
514
+ def find_files(self, query: str, roots: list[Path]) -> str:
515
+ existing_roots = [str(r) for r in roots if r.exists()]
516
+ if not existing_roots:
517
+ return ""
518
+ res = subprocess.run(
519
+ ["find", *existing_roots, "-iname", f"*{query}*"],
520
+ capture_output=True,
521
+ text=True,
522
+ timeout=10,
523
+ )
524
+ lines = [line for line in res.stdout.splitlines() if line.strip()][:15]
525
+ return "\n".join(lines) + ("\n" if lines else "")
526
+
527
+ def run_command(self, command: str, timeout: int = 15) -> str:
528
+ argv = shlex.split(command)
529
+ if not argv:
530
+ return ""
531
+ try:
532
+ res = subprocess.run(
533
+ argv,
534
+ capture_output=True,
535
+ text=True,
536
+ timeout=timeout,
537
+ )
538
+ output = (res.stdout or "") + (res.stderr or "")
539
+ if res.returncode != 0 and not output.strip():
540
+ return f"(exit code {res.returncode})"
541
+ return output
542
+ except subprocess.TimeoutExpired as exc:
543
+ raise TimeoutError(f"Command timed out after {timeout}s") from exc
544
+
545
+ def compress_video(self, input_path: str, output_path: str, target_mb: int = 45) -> bool:
546
+ try:
547
+ subprocess.run(
548
+ [
549
+ "ffmpeg",
550
+ "-i",
551
+ input_path,
552
+ "-vcodec",
553
+ "libx264",
554
+ "-crf",
555
+ "28",
556
+ "-preset",
557
+ "veryfast",
558
+ "-acodec",
559
+ "aac",
560
+ "-b:a",
561
+ "96k",
562
+ "-fs",
563
+ str(target_mb * 1024 * 1024),
564
+ output_path,
565
+ "-y",
566
+ ],
567
+ check=True,
568
+ stdout=subprocess.DEVNULL,
569
+ stderr=subprocess.DEVNULL,
570
+ timeout=60,
571
+ )
572
+ return os.path.exists(output_path) and os.path.getsize(output_path) > 0
573
+ except Exception:
574
+ return False
lapctl/main.py ADDED
@@ -0,0 +1,86 @@
1
+ """Application entrypoint for Lapctl."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import signal
6
+ import sys
7
+ import threading
8
+ from pathlib import Path
9
+ from typing import Any
10
+
11
+ from lapctl.channels.telegram.api import TelegramClient
12
+ from lapctl.channels.telegram.handlers import TelegramHandlers
13
+ from lapctl.channels.telegram.poller import TelegramPoller
14
+ from lapctl.channels.telegram.render import sync_bot_commands
15
+ from lapctl.config import get_bot_token, get_owner_id, load_config
16
+ from lapctl.core.battery import BatteryEvent, BatteryMonitor
17
+ from lapctl.core.commands import build_default_registry
18
+ from lapctl.drivers.linux_hyprland import LinuxHyprlandDriver
19
+
20
+
21
+ def _notify_battery_event(
22
+ client: TelegramClient,
23
+ allowed_user_id: int,
24
+ event: BatteryEvent,
25
+ ) -> None:
26
+ if not allowed_user_id or allowed_user_id == 0:
27
+ return
28
+ if event.kind == "low":
29
+ client.send_message(
30
+ allowed_user_id,
31
+ f"⚠️ *Baterai lemah ({event.capacity}%)!* Harap hubungkan pengisi daya.",
32
+ )
33
+ elif event.kind == "full":
34
+ client.send_message(
35
+ allowed_user_id,
36
+ f"✅ *Baterai penuh ({event.capacity}%)!* Silakan cabut charger untuk menjaga kesehatan baterai.",
37
+ )
38
+
39
+
40
+ def main(
41
+ config_path: str | Path | None = None,
42
+ legacy_json_path: str | Path | None = None,
43
+ ) -> None:
44
+ """Initialize driver, config, monitors, signal handlers, and polling."""
45
+ driver = LinuxHyprlandDriver()
46
+ driver.prepare_env()
47
+
48
+ config = load_config(config_path=config_path, legacy_json_path=legacy_json_path)
49
+ token = get_bot_token(config)
50
+ allowed_user_id = get_owner_id(config)
51
+ client = TelegramClient(token)
52
+
53
+ def sigterm_handler(signum: int, frame: Any) -> None:
54
+ print("\nMenerima sinyal stop, menyetel status offline...")
55
+ client.set_bot_status_offline()
56
+ sys.exit(0)
57
+
58
+ signal.signal(signal.SIGTERM, sigterm_handler)
59
+ signal.signal(signal.SIGINT, sigterm_handler)
60
+
61
+ monitor = BatteryMonitor(driver=driver)
62
+ if allowed_user_id and allowed_user_id != 0:
63
+ threading.Thread(
64
+ target=monitor.run,
65
+ args=(lambda ev: _notify_battery_event(client, allowed_user_id, ev),),
66
+ daemon=True,
67
+ ).start()
68
+
69
+ registry = build_default_registry()
70
+ sync_bot_commands(client, registry, config=config)
71
+
72
+ handlers = TelegramHandlers(client=client, config=config, driver=driver, registry=registry)
73
+ poller = TelegramPoller(
74
+ client=client,
75
+ allowed_user_id=allowed_user_id,
76
+ on_text=handlers.on_text,
77
+ on_document=handlers.on_document,
78
+ on_photo=handlers.on_photo,
79
+ on_callback=handlers.on_callback,
80
+ on_before_update=driver.prepare_env,
81
+ )
82
+ poller.run()
83
+
84
+
85
+ if __name__ == "__main__":
86
+ main()