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,1260 @@
1
+ """Core command handlers with security controls (Fase 4)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import socket
7
+ import tempfile
8
+ import time
9
+ import urllib.parse
10
+ from typing import Any, Literal
11
+
12
+ import requests
13
+
14
+ from lapctl.core.confirm import ConfirmationManager
15
+ from lapctl.core.keyboards import (
16
+ get_menu_buttons,
17
+ get_start_buttons,
18
+ get_status_buttons,
19
+ )
20
+ from lapctl.core.paths import (
21
+ PathAccessError,
22
+ resolve_allowed_roots,
23
+ validate_path,
24
+ )
25
+ from lapctl.core.ratelimit import RateLimiter
26
+ from lapctl.drivers.base import BaseDriver, NotSupported
27
+ from lapctl.registry import Command, CommandContext, CommandRegistry
28
+ from lapctl.results import (
29
+ Audio,
30
+ Button,
31
+ Buttons,
32
+ CommandOutput,
33
+ File,
34
+ Image,
35
+ Location,
36
+ Text,
37
+ Video,
38
+ )
39
+
40
+ TEXT_MAP: dict[str, str] = {
41
+ "🤖 menu": "/menu",
42
+ "📊 status": "/status",
43
+ "📸 screenshot": "/ss",
44
+ "📷 camera": "/cam",
45
+ "📹 video cam": "/vid",
46
+ "🎙️ rekam 5s": "/record 5",
47
+ "🔒 lock screen": "/lock",
48
+ "🌐 info ip": "/ip",
49
+ "📋 get clipboard": "/getclip",
50
+ "❓ help": "/help",
51
+ "🔊 vol up": "/volup",
52
+ "🔉 vol down": "/voldown",
53
+ "📍 lokasi": "/location",
54
+ "📱 cari hp": "/carihp",
55
+ "🔔 bunyikan hp": "/carihp",
56
+ }
57
+
58
+
59
+ def _make_temp_path(suffix: str) -> str:
60
+ fd, path = tempfile.mkstemp(prefix="lapctl_", suffix=suffix)
61
+ os.close(fd)
62
+ return path
63
+
64
+
65
+ def _get_ntfy_topic(config: dict[str, Any]) -> str:
66
+ external = config.get("external")
67
+ if isinstance(external, dict) and external.get("ntfy_topic") is not None:
68
+ return str(external.get("ntfy_topic", "")).strip()
69
+ return str(config.get("ntfy_topic", "")).strip()
70
+
71
+
72
+ def _cmd_start(ctx: CommandContext) -> CommandOutput:
73
+ welcome_text = (
74
+ "👋 *Halo! Selamat datang di Remote Laptop Bot Anda.*\n\n"
75
+ "Bot ini siap membantu Anda untuk mengontrol dan memantau laptop Arch Linux (Hyprland) Anda dari jarak jauh secara aman.\n\n"
76
+ "Silakan ketuk tombol *🤖 Menu Kontrol* di bawah untuk menampilkan seluruh menu kontrol, atau ketik `/help` untuk melihat daftar lengkap perintah tertulis."
77
+ )
78
+ return Buttons(text=welcome_text, rows=get_start_buttons())
79
+
80
+
81
+ def _cmd_help(ctx: CommandContext) -> CommandOutput:
82
+ help_text = (
83
+ "🤖 *Remote Laptop Bot - Daftar Perintah*\n\n"
84
+ "Berikut perintah yang bisa Anda gunakan:\n"
85
+ "📺 `/youtube <judul>` - Membuka browser & mencari/memutar video\n"
86
+ "📸 `/ss` atau `/screenshot` - Mengambil screenshot layar laptop\n"
87
+ "📷 `/cam` atau `/camera` - Mengambil foto lewat webcam laptop\n"
88
+ "📹 `/vid` atau `/video` - Merekam video webcam laptop (1-15s, default 5s)\n"
89
+ "🎙️ `/record <detik>` - Rekam suara mic laptop (1-30s, default 5s)\n"
90
+ "🗣️ `/say [loop_count] <teks>` - Membacakan teks bahasa Indonesia di laptop speaker (maksimal loop 20)\n"
91
+ "📋 `/setclip <teks>` atau `/copy <teks>` - Menyalin teks ke clipboard laptop\n"
92
+ "📋 `/getclip` atau `/paste` - Mengambil teks dari clipboard laptop\n"
93
+ "📊 `/status` - Melihat status baterai, RAM, CPU, volume, kecerahan, & WiFi\n"
94
+ "💡 `/brightness <0-100>` - Mengatur tingkat kecerahan layar\n"
95
+ "🔒 `/lock` - Mengunci layar laptop (`hyprlock`)\n"
96
+ "🔊 `/volume <0-100>` - Mengatur volume suara laptop\n"
97
+ "🔇 `/mute` | `/unmute` - Mematikan/mengaktifkan suara laptop\n"
98
+ "🎵 `/play` | `/pause` | `/next` | `/prev` - Kontrol musik/video\n"
99
+ "🔔 `/beep <normal|alert|camera|success>` - Memutar suara beep di laptop\n"
100
+ "📱 `/carihp` atau `/ringphone` - Membunyikan HP (deras & tembus silent via ntfy)\n"
101
+ "💬 `/notify [judul] | <pesan>` - Mengirim popup notifikasi ke laptop\n"
102
+ "🖼️ `/wallpaper <path>` - Mengubah wallpaper laptop\n"
103
+ "🌐 `/ip` - Melihat IP lokal dan publik laptop\n"
104
+ "📍 `/loc` atau `/location` - Mengirim koordinat peta lokasi laptop Anda\n"
105
+ "📂 `/ls <path>` - List file/folder di folder yang diizinkan\n"
106
+ "📄 `/download <path>` - Mengunduh file dari laptop ke Telegram\n"
107
+ "📥 *Upload file/foto* langsung ke chat ini untuk disimpan ke laptop (`~/Downloads/TelegramBot/`)\n"
108
+ "🖼️ *Upload foto dengan caption* `/wallpaper` untuk mengubah wallpaper\n"
109
+ "⚡ `/suspend` | `/reboot` | `/shutdown` - Kontrol daya laptop (dengan konfirmasi)\n"
110
+ "🐚 `/cmd <perintah>` - Menjalankan perintah (khusus profil lengkap)"
111
+ )
112
+ return Buttons(text=help_text, rows=get_start_buttons())
113
+
114
+
115
+ def _cmd_youtube(ctx: CommandContext) -> CommandOutput:
116
+ if not ctx.args:
117
+ return Text("Gunakan format: `/youtube <judul lagu/pencarian>`")
118
+ query = urllib.parse.quote(ctx.args)
119
+ youtube_url = f"https://www.youtube.com/results?search_query={query}"
120
+ try:
121
+ ctx.driver.open_url(youtube_url)
122
+ return Text(f"Membuka YouTube untuk pencarian: *{ctx.args}*...")
123
+ except NotSupported:
124
+ raise
125
+ except Exception as e:
126
+ return Text(f"Gagal membuka browser: {e}")
127
+
128
+
129
+ def _cmd_ss(ctx: CommandContext) -> CommandOutput:
130
+ photo_path = _make_temp_path(".png")
131
+ try:
132
+ ctx.driver.screenshot(photo_path)
133
+ return [
134
+ Text("Mengambil screenshot..."),
135
+ Image(path=photo_path, caption="Screenshot layar laptop saat ini", cleanup=True),
136
+ ]
137
+ except NotSupported:
138
+ if os.path.exists(photo_path):
139
+ os.remove(photo_path)
140
+ raise
141
+ except Exception as e:
142
+ if os.path.exists(photo_path):
143
+ os.remove(photo_path)
144
+ return Text(f"Gagal mengambil screenshot (pastikan `grim` terinstal): {e}")
145
+
146
+
147
+ def _cmd_cam(ctx: CommandContext) -> CommandOutput:
148
+ photo_path = _make_temp_path(".jpg")
149
+ try:
150
+ ctx.driver.webcam_photo(photo_path)
151
+ if os.path.exists(photo_path) and os.path.getsize(photo_path) > 0:
152
+ return [
153
+ Text("Mengambil foto webcam..."),
154
+ Image(path=photo_path, caption="Foto dari webcam laptop", cleanup=True),
155
+ ]
156
+ if os.path.exists(photo_path):
157
+ os.remove(photo_path)
158
+ return Text("Gagal mengambil foto (file output tidak ditemukan).")
159
+ except NotSupported:
160
+ if os.path.exists(photo_path):
161
+ os.remove(photo_path)
162
+ raise
163
+ except Exception as e:
164
+ if os.path.exists(photo_path):
165
+ os.remove(photo_path)
166
+ return Text(
167
+ f"Gagal mengambil foto dari webcam (pastikan webcam terhubung dan ffmpeg terinstal): {e}"
168
+ )
169
+
170
+
171
+ def _cmd_vid(ctx: CommandContext) -> CommandOutput:
172
+ duration = 5
173
+ if ctx.args:
174
+ try:
175
+ duration = int(ctx.args)
176
+ if duration < 1 or duration > 15:
177
+ duration = 5
178
+ except Exception:
179
+ pass
180
+
181
+ video_path = _make_temp_path(".mp4")
182
+ try:
183
+ ctx.driver.webcam_video(video_path, duration)
184
+ if os.path.exists(video_path) and os.path.getsize(video_path) > 0:
185
+ return [
186
+ Text(f"📹 Merekam video webcam selama {duration} detik..."),
187
+ Video(path=video_path, caption=f"Video webcam ({duration} detik)", cleanup=True),
188
+ ]
189
+ if os.path.exists(video_path):
190
+ os.remove(video_path)
191
+ return Text("Gagal merekam video (file output tidak ditemukan).")
192
+ except NotSupported:
193
+ if os.path.exists(video_path):
194
+ os.remove(video_path)
195
+ raise
196
+ except Exception as e:
197
+ if os.path.exists(video_path):
198
+ os.remove(video_path)
199
+ return Text(f"Gagal merekam video: {e}")
200
+
201
+
202
+ def _cmd_record(ctx: CommandContext) -> CommandOutput:
203
+ duration = 5
204
+ if ctx.args:
205
+ try:
206
+ duration = int(ctx.args)
207
+ if duration < 1 or duration > 30:
208
+ duration = 5
209
+ except Exception:
210
+ pass
211
+
212
+ voice_path = _make_temp_path(".ogg")
213
+ try:
214
+ ctx.driver.record_audio(voice_path, duration)
215
+ if os.path.exists(voice_path) and os.path.getsize(voice_path) > 0:
216
+ return [
217
+ Text(f"🎙️ Merekam suara selama {duration} detik..."),
218
+ Audio(path=voice_path, caption=f"Rekaman suara ({duration} detik)", cleanup=True),
219
+ ]
220
+ if os.path.exists(voice_path):
221
+ os.remove(voice_path)
222
+ return Text("Gagal merekam suara (file output tidak ditemukan).")
223
+ except NotSupported:
224
+ if os.path.exists(voice_path):
225
+ os.remove(voice_path)
226
+ raise
227
+ except Exception as e:
228
+ if os.path.exists(voice_path):
229
+ os.remove(voice_path)
230
+ return Text(f"Gagal merekam suara: {e}")
231
+
232
+
233
+ def _cmd_say(ctx: CommandContext) -> CommandOutput:
234
+ if not ctx.args:
235
+ return Text("Gunakan format: `/say <teks>` atau `/say [loop_count] <teks>`")
236
+
237
+ parts_say = ctx.args.split()
238
+ if not parts_say:
239
+ return None
240
+
241
+ lang = "id"
242
+ loop_count = 1
243
+ if parts_say[0].isdigit():
244
+ loop_count = int(parts_say[0])
245
+ text_to_say = " ".join(parts_say[1:])
246
+ if not text_to_say:
247
+ text_to_say = parts_say[0]
248
+ loop_count = 1
249
+ else:
250
+ text_to_say = ctx.args.strip()
251
+
252
+ if not text_to_say:
253
+ return Text("Silakan masukkan teks yang ingin dibacakan.")
254
+
255
+ if loop_count > 20:
256
+ loop_count = 20
257
+
258
+ try:
259
+ encoded_text = urllib.parse.quote(text_to_say)
260
+ tts_url = f"https://translate.google.com/translate_tts?ie=UTF-8&tl={lang}&client=tw-ob&q={encoded_text}"
261
+ ctx.driver.play_audio_url(tts_url, loop_count=loop_count)
262
+ return Text(f'🗣️ Membacakan teks sebanyak {loop_count} kali: "{text_to_say}"...')
263
+ except NotSupported:
264
+ raise
265
+ except Exception as e:
266
+ return Text(f"Gagal membacakan teks: {e}")
267
+
268
+
269
+ def _cmd_status(ctx: CommandContext) -> CommandOutput:
270
+ status_text = ctx.driver.get_system_status()
271
+ return Buttons(
272
+ text=status_text if status_text else "Gagal mengambil info status sistem.",
273
+ rows=get_status_buttons(),
274
+ )
275
+
276
+
277
+ def _cmd_menu(ctx: CommandContext) -> CommandOutput:
278
+ return Buttons(
279
+ text="🤖 *MY LAPTOP* (Menu Kontrol)",
280
+ rows=get_menu_buttons(registry=ctx.registry, config=ctx.config),
281
+ )
282
+
283
+
284
+ def _cmd_none(ctx: CommandContext) -> CommandOutput:
285
+ return None
286
+
287
+
288
+ def _cmd_health(ctx: CommandContext) -> CommandOutput:
289
+ try:
290
+ uptime_str, temp, disk_used_pct, disk_free_gb, disk_total_gb = (
291
+ ctx.driver.get_system_health()
292
+ )
293
+ health_info = (
294
+ f"🩺 *Kesehatan Sistem:*\n\n"
295
+ f"⏱️ *Uptime:* {uptime_str}\n"
296
+ f"🌡️ *Suhu CPU:* {temp}\n"
297
+ f"💾 *Penyimpanan (/):* {disk_used_pct}% terpakai ({disk_free_gb} GB bebas dari {disk_total_gb} GB)"
298
+ )
299
+ return Text(health_info)
300
+ except NotSupported:
301
+ raise
302
+ except Exception as e:
303
+ return Text(f"❌ Gagal mengambil info kesehatan: {e}")
304
+
305
+
306
+ def _cmd_ps(ctx: CommandContext) -> CommandOutput:
307
+ try:
308
+ out = ctx.driver.list_processes()
309
+ return Text(f"⚙️ *Proses Teratas (Sort CPU):*\n```\n{out}\n```")
310
+ except NotSupported:
311
+ raise
312
+ except Exception as e:
313
+ return Text(f"❌ Gagal mendapatkan daftar proses: {e}")
314
+
315
+
316
+ def _cmd_logs(ctx: CommandContext) -> CommandOutput:
317
+ try:
318
+ out = ctx.driver.get_logs()
319
+ return Text(f"📜 *Log Bot 20 Baris Terakhir:*\n```\n{out}\n```")
320
+ except NotSupported:
321
+ raise
322
+ except Exception as e:
323
+ return Text(f"❌ Gagal mengambil log: {e}")
324
+
325
+
326
+ def _cmd_mouse(ctx: CommandContext) -> CommandOutput:
327
+ if not ctx.args:
328
+ try:
329
+ pos = ctx.driver.get_cursor_pos()
330
+ return Text(
331
+ f"🖱 *Posisi Kursor:* `{pos}`\n\n*Penggunaan:*\n"
332
+ "- `/mouse move <x> <y>` - Pindahkan kursor\n"
333
+ "- `/mouse click` - Klik kiri (via xdotool)"
334
+ )
335
+ except NotSupported:
336
+ raise
337
+ except Exception as e:
338
+ return Text(f"🖱 Gagal mendapatkan posisi kursor: {e}")
339
+
340
+ parts_mouse = ctx.args.split()
341
+ sub = parts_mouse[0].lower()
342
+ if sub == "move" and len(parts_mouse) >= 3:
343
+ try:
344
+ x = int(parts_mouse[1])
345
+ y = int(parts_mouse[2])
346
+ ctx.driver.move_cursor(x, y)
347
+ return Text(f"🖱 Kursor dipindahkan ke `{x}, {y}`.")
348
+ except NotSupported:
349
+ raise
350
+ except Exception as e:
351
+ return Text(f"❌ Gagal memindahkan kursor: {e}")
352
+ if sub == "click":
353
+ try:
354
+ ctx.driver.mouse_click()
355
+ return Text("🖱 Melakukan klik kiri (via xdotool).")
356
+ except NotSupported:
357
+ raise
358
+ except Exception as e:
359
+ return Text(f"❌ Gagal klik (xdotool tidak berjalan atau sedang di luar XWayland): {e}")
360
+ return None
361
+
362
+
363
+ def _cmd_keyboard(ctx: CommandContext) -> CommandOutput:
364
+ if not ctx.args:
365
+ return Text(
366
+ "Gunakan format: `/keyboard <teks>` untuk mengetik teks, atau `/keyboard key <tombol>` untuk menekan tombol tertentu (misal: Return, space)."
367
+ )
368
+ parts_kb = ctx.args.split(maxsplit=1)
369
+ if parts_kb[0].lower() == "key" and len(parts_kb) > 1:
370
+ key = parts_kb[1]
371
+ try:
372
+ ctx.driver.keyboard_key(key)
373
+ return Text(f"⌨️ Menekan tombol: `{key}`")
374
+ except NotSupported:
375
+ raise
376
+ except Exception as e:
377
+ return Text(f"❌ Gagal menekan tombol: {e}")
378
+ try:
379
+ ctx.driver.keyboard_type(ctx.args)
380
+ return Text(f"⌨️ Mengetik teks: `{ctx.args}`")
381
+ except NotSupported:
382
+ raise
383
+ except Exception as e:
384
+ return Text(f"❌ Gagal mengetik teks (pastikan xdotool berjalan): {e}")
385
+
386
+
387
+ def _cmd_find(ctx: CommandContext) -> CommandOutput:
388
+ if not ctx.args:
389
+ return Text("Gunakan format: `/find <nama_file>`")
390
+ roots = resolve_allowed_roots(ctx.config)
391
+ try:
392
+ out = ctx.driver.find_files(ctx.args.strip(), roots)
393
+ if out.strip():
394
+ return Text(f"🔎 *Hasil pencarian:*\n```\n{out}\n```")
395
+ return Text("❌ File tidak ditemukan.")
396
+ except NotSupported:
397
+ raise
398
+ except Exception as e:
399
+ return Text(f"❌ Gagal mencari file: {e}")
400
+
401
+
402
+ def _cmd_upload(ctx: CommandContext) -> CommandOutput:
403
+ return Text(
404
+ "⬆️ *Cara Upload File/Foto ke Laptop:*\n\n"
405
+ "Kirim saja file atau foto apa saja langsung ke chat bot ini.\n"
406
+ "File tersebut akan otomatis disimpan ke direktori laptop Anda di:\n"
407
+ "`~/Downloads/TelegramBot/`"
408
+ )
409
+
410
+
411
+ def _cmd_screenrecord(ctx: CommandContext) -> CommandOutput:
412
+ duration = 5
413
+ if ctx.args:
414
+ try:
415
+ duration = int(ctx.args)
416
+ if duration < 1 or duration > 30:
417
+ duration = 5
418
+ except Exception:
419
+ pass
420
+
421
+ video_path = _make_temp_path(".mp4")
422
+ try:
423
+ ctx.driver.screenrecord(video_path, duration)
424
+ if os.path.exists(video_path) and os.path.getsize(video_path) > 0:
425
+ return [
426
+ Text(f"🖥 Merekam layar selama {duration} detik..."),
427
+ Video(
428
+ path=video_path,
429
+ caption=f"Perekaman Layar ({duration} detik)",
430
+ cleanup=True,
431
+ ),
432
+ ]
433
+ if os.path.exists(video_path):
434
+ os.remove(video_path)
435
+ return Text("❌ Gagal merekam layar (file output kosong atau tidak ditemukan).")
436
+ except NotSupported as exc:
437
+ if os.path.exists(video_path):
438
+ os.remove(video_path)
439
+ return Text(exc.reason)
440
+ except Exception as e:
441
+ if os.path.exists(video_path):
442
+ os.remove(video_path)
443
+ return Text(f"❌ Gagal merekam layar: {e}")
444
+
445
+
446
+ def _cmd_network(ctx: CommandContext) -> CommandOutput:
447
+ try:
448
+ ping_out, interfaces = ctx.driver.get_network_info()
449
+ network_info = (
450
+ f"📡 *Informasi Jaringan:*\n\n"
451
+ f"⚡ *Ping Latency:* {ping_out}\n\n"
452
+ f"🔗 *Antarmuka Aktif:* \n```\n{interfaces}\n```"
453
+ )
454
+ return Text(network_info)
455
+ except NotSupported:
456
+ raise
457
+ except Exception as e:
458
+ return Text(f"❌ Gagal mengambil informasi jaringan: {e}")
459
+
460
+
461
+ def _cmd_setclip(ctx: CommandContext) -> CommandOutput:
462
+ if not ctx.args:
463
+ return Text("Gunakan format: `/setclip <teks>` atau `/copy <teks>`")
464
+ try:
465
+ rc = ctx.driver.set_clipboard(ctx.args)
466
+ if rc == 0:
467
+ return Text(f"📋 Teks berhasil disalin ke clipboard laptop:\n`{ctx.args}`")
468
+ return Text(f"❌ Gagal menyalin ke clipboard (exit code: {rc})")
469
+ except NotSupported:
470
+ raise
471
+ except Exception as e:
472
+ return Text(f"❌ Gagal menyalin ke clipboard: {e}")
473
+
474
+
475
+ def _cmd_getclip(ctx: CommandContext) -> CommandOutput:
476
+ try:
477
+ out = ctx.driver.get_clipboard()
478
+ if out == "":
479
+ return Text("📋 Clipboard laptop kosong.")
480
+ if out.strip():
481
+ return Text(f"📋 *Clipboard laptop saat ini:*\n```\n{out}\n```")
482
+ return Text("📋 Clipboard laptop kosong atau tidak berisi teks.")
483
+ except NotSupported:
484
+ raise
485
+ except Exception as e:
486
+ return Text(f"❌ Gagal membaca clipboard: {e}")
487
+
488
+
489
+ def _cmd_brightness(ctx: CommandContext) -> CommandOutput:
490
+ if not ctx.args:
491
+ return Buttons(
492
+ text="💡 *Pilih Kecerahan Layar:*",
493
+ rows=[
494
+ [
495
+ Button(text="☀️ 10%", callback_data="/brightness 10"),
496
+ Button(text="☀️ 30%", callback_data="/brightness 30"),
497
+ Button(text="☀️ 50%", callback_data="/brightness 50"),
498
+ Button(text="☀️ 80%", callback_data="/brightness 80"),
499
+ Button(text="☀️ 100%", callback_data="/brightness 100"),
500
+ ]
501
+ ],
502
+ )
503
+ try:
504
+ level = int(ctx.args)
505
+ if level < 0 or level > 100:
506
+ raise ValueError
507
+ ctx.driver.set_brightness(level)
508
+ return Text(f"💡 Kecerahan layar diatur ke *{level}%*")
509
+ except NotSupported:
510
+ raise
511
+ except Exception as e:
512
+ return Text(f"Gagal mengatur kecerahan: {e}. Pastikan format angka benar (0-100).")
513
+
514
+
515
+ def _cmd_lock(ctx: CommandContext) -> CommandOutput:
516
+ try:
517
+ ctx.driver.lock_screen()
518
+ return Text("Mengunci layar...")
519
+ except NotSupported:
520
+ raise
521
+ except Exception as e:
522
+ return Text(f"Gagal mengunci layar: {e}")
523
+
524
+
525
+ def _cmd_volume(ctx: CommandContext) -> CommandOutput:
526
+ if not ctx.args:
527
+ return Buttons(
528
+ text="🔊 *Pilih Volume Suara:*",
529
+ rows=[
530
+ [
531
+ Button(text="🔇 Mute", callback_data="/mute"),
532
+ Button(text="🔉 -10%", callback_data="/voldown"),
533
+ Button(text="🔊 +10%", callback_data="/volup"),
534
+ Button(text="🔊 Unmute", callback_data="/unmute"),
535
+ ],
536
+ [
537
+ Button(text="🔈 20%", callback_data="/volume 20"),
538
+ Button(text="🔉 50%", callback_data="/volume 50"),
539
+ Button(text="🔊 80%", callback_data="/volume 80"),
540
+ Button(text="🔊 100%", callback_data="/volume 100"),
541
+ ],
542
+ ],
543
+ )
544
+ try:
545
+ vol = int(ctx.args)
546
+ if vol < 0 or vol > 100:
547
+ raise ValueError
548
+ ctx.driver.set_volume(vol)
549
+ return Text(f"🔊 Volume berhasil diatur ke *{vol}%*")
550
+ except NotSupported:
551
+ raise
552
+ except Exception:
553
+ return Text("Gagal mengatur volume. Pastikan format angka benar (0-100).")
554
+
555
+
556
+ def _cmd_mute(ctx: CommandContext) -> CommandOutput:
557
+ try:
558
+ ctx.driver.set_mute(True)
559
+ return Text("🔇 Suara laptop berhasil di-mute.")
560
+ except NotSupported:
561
+ raise
562
+ except Exception as e:
563
+ return Text(f"Gagal me-mute: {e}")
564
+
565
+
566
+ def _cmd_unmute(ctx: CommandContext) -> CommandOutput:
567
+ try:
568
+ ctx.driver.set_mute(False)
569
+ return Text("🔊 Suara laptop berhasil di-unmute.")
570
+ except NotSupported:
571
+ raise
572
+ except Exception as e:
573
+ return Text(f"Gagal meng-unmute: {e}")
574
+
575
+
576
+ def _cmd_volup(ctx: CommandContext) -> CommandOutput:
577
+ try:
578
+ vol_out = ctx.driver.step_volume("0.05+")
579
+ return Text(f"🔊 Volume dinaikkan: *{vol_out}*")
580
+ except NotSupported:
581
+ raise
582
+ except Exception as e:
583
+ return Text(f"Gagal menaikkan volume: {e}")
584
+
585
+
586
+ def _cmd_voldown(ctx: CommandContext) -> CommandOutput:
587
+ try:
588
+ vol_out = ctx.driver.step_volume("0.05-")
589
+ return Text(f"🔉 Volume diturunkan: *{vol_out}*")
590
+ except NotSupported:
591
+ raise
592
+ except Exception as e:
593
+ return Text(f"Gagal menurunkan volume: {e}")
594
+
595
+
596
+ def _make_media_handler(action: str):
597
+ def _handler(ctx: CommandContext) -> CommandOutput:
598
+ try:
599
+ ctx.driver.media_control(action) # type: ignore[arg-type]
600
+ return Text(f"🎵 Media: *{action.capitalize()}*")
601
+ except NotSupported:
602
+ raise
603
+ except Exception as e:
604
+ return Text(f"Gagal mengontrol media: {e}")
605
+
606
+ return _handler
607
+
608
+
609
+ def _cmd_beep(ctx: CommandContext) -> CommandOutput:
610
+ sound_type = ctx.args.lower().strip() if ctx.args else "normal"
611
+ try:
612
+ ctx.driver.play_beep(sound_type)
613
+ return Text(f"🔊 Memutar suara beep ({sound_type})...")
614
+ except NotSupported:
615
+ raise
616
+ except Exception as e:
617
+ return Text(f"Gagal memutar suara: {e}")
618
+
619
+
620
+ def _cmd_carihp(ctx: CommandContext) -> CommandOutput:
621
+ topic = _get_ntfy_topic(ctx.config)
622
+ if not topic:
623
+ return Text(
624
+ "⚠️ Fitur `/carihp` belum dikonfigurasi. Tambahkan `ntfy_topic` di konfigurasi terlebih dahulu."
625
+ )
626
+
627
+ try:
628
+ requests.post(
629
+ f"https://ntfy.sh/{topic}",
630
+ data="🚨 HP KAMU DI SINI! SEGERA AMBIL! 🚨".encode("utf-8"),
631
+ headers={
632
+ "Title": "PENCARI HP AKTIF!",
633
+ "Priority": "urgent",
634
+ "Tags": "rotating_light,loudspeaker,warning,bell",
635
+ },
636
+ timeout=5,
637
+ )
638
+ except Exception:
639
+ pass
640
+
641
+ msg_text = (
642
+ "📱 *PENCARI HP - Google Find My Device*\n\n"
643
+ "Fitur resmi Google untuk membunyikan HP Anda dengan volume *100% MAKSIMAL* selama 5 menit:\n"
644
+ "✅ *Tembus Mode Hening / Silent total*\n"
645
+ "✅ *Tembus Mode Getar & Jangan Ganggu (DND)*\n"
646
+ "✅ *100% Aman untuk M-Banking & E-Wallet*\n\n"
647
+ "👉 Ketuk tombol *🔊 Putar Suara di HP (Google)* di bawah, lalu klik tombol **Putar Suara** (*Play Sound*) untuk membunyikan HP seketika!"
648
+ )
649
+ return Buttons(
650
+ text=msg_text,
651
+ rows=[
652
+ [
653
+ Button(
654
+ text="🔊 Putar Suara di HP (Google)", url="https://www.google.com/android/find"
655
+ )
656
+ ],
657
+ [Button(text="💻 Buka di Browser Laptop", callback_data="/openfindmydevice")],
658
+ ],
659
+ )
660
+
661
+
662
+ def _cmd_openfindmydevice(ctx: CommandContext) -> CommandOutput:
663
+ try:
664
+ ctx.driver.open_url("https://www.google.com/android/find")
665
+ return Text(
666
+ "🌐 *Google Find My Device telah dibuka di browser laptop!*\n\n"
667
+ "Silakan lihat layar laptop Anda, lalu klik tombol **Putar Suara** (*Play Sound*)."
668
+ )
669
+ except NotSupported:
670
+ raise
671
+ except Exception as e:
672
+ return Text(f"Gagal membuka browser laptop: {e}")
673
+
674
+
675
+ def _cmd_notify(ctx: CommandContext) -> CommandOutput:
676
+ if not ctx.args:
677
+ return Text("Gunakan format: `/notify [judul] | <pesan>` atau `/notify <pesan>`")
678
+
679
+ title = "Remote Bot"
680
+ message = ctx.args
681
+ if "|" in ctx.args:
682
+ parts_notify = ctx.args.split("|", 1)
683
+ title = parts_notify[0].strip()
684
+ message = parts_notify[1].strip()
685
+
686
+ try:
687
+ ctx.driver.notify(title, message)
688
+ return Text(f"💬 Notifikasi dikirim ke laptop:\n*Title:* {title}\n*Message:* {message}")
689
+ except NotSupported:
690
+ raise
691
+ except Exception as e:
692
+ return Text(f"Gagal mengirim notifikasi: {e}")
693
+
694
+
695
+ def _cmd_wallpaper(ctx: CommandContext) -> CommandOutput:
696
+ if not ctx.args:
697
+ return Text("Gunakan format: `/wallpaper <path_file_gambar>`")
698
+
699
+ roots = resolve_allowed_roots(ctx.config)
700
+ try:
701
+ safe_path = validate_path(ctx.args, roots)
702
+ except PathAccessError as exc:
703
+ return Text(f"❌ {exc}")
704
+
705
+ if not safe_path.exists():
706
+ return Text("❌ Gambar tidak ditemukan di path tersebut.")
707
+
708
+ try:
709
+ ctx.driver.set_wallpaper(str(safe_path))
710
+ return Text("✅ Wallpaper berhasil diubah!")
711
+ except NotSupported:
712
+ raise
713
+ except Exception as e:
714
+ return Text(f"Gagal mengganti wallpaper: {e}")
715
+
716
+
717
+ def _cmd_ip(ctx: CommandContext) -> CommandOutput:
718
+ local_ip = "Tidak diketahui"
719
+ try:
720
+ s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
721
+ s.connect(("10.255.255.255", 1))
722
+ local_ip = s.getsockname()[0]
723
+ s.close()
724
+ except Exception:
725
+ pass
726
+
727
+ public_ip = "Tidak diketahui"
728
+ try:
729
+ public_ip = requests.get("https://api.ipify.org", timeout=5).text.strip()
730
+ except Exception:
731
+ pass
732
+
733
+ return Text(
734
+ f"🌐 *Informasi IP Laptop*\n\n🏠 *IP Lokal:* `{local_ip}`\n🌍 *IP Publik:* `{public_ip}`"
735
+ )
736
+
737
+
738
+ def _cmd_loc(ctx: CommandContext) -> CommandOutput:
739
+ try:
740
+ r = requests.get("http://ip-api.com/json", timeout=10)
741
+ if r.status_code == 200:
742
+ data = r.json()
743
+ if data.get("status") == "success":
744
+ lat = data.get("lat")
745
+ lon = data.get("lon")
746
+ city = data.get("city")
747
+ region = data.get("regionName")
748
+ country = data.get("country")
749
+ isp = data.get("isp")
750
+
751
+ loc_info = (
752
+ "📍 *Lokasi Terdeteksi (IP Geolocation)*\n\n"
753
+ f"🌍 *Negara:* {country}\n"
754
+ f"🏙️ *Kota/Wilayah:* {city}, {region}\n"
755
+ f"📡 *Provider/ISP:* {isp}\n"
756
+ f"📐 *Koordinat:* `{lat}, {lon}`"
757
+ )
758
+ return [
759
+ Text(loc_info),
760
+ Location(latitude=float(lat), longitude=float(lon)),
761
+ ]
762
+ return Text("❌ Gagal mendapatkan koordinat dari API Geolocation.")
763
+ return Text("❌ Gagal menghubungi server Geolocation.")
764
+ except Exception as e:
765
+ return Text(f"❌ Terjadi kesalahan saat mendeteksi lokasi: {e}")
766
+
767
+
768
+ def _cmd_ls(ctx: CommandContext) -> CommandOutput:
769
+ roots = resolve_allowed_roots(ctx.config)
770
+ if not ctx.args:
771
+ lines = [f"📁 `{r}`" for r in roots if r.exists()]
772
+ if not lines:
773
+ return Text("❌ Tidak ada folder yang diizinkan yang tersedia.")
774
+ return Text("📂 *Folder yang diizinkan:*\n\n" + "\n".join(lines))
775
+
776
+ try:
777
+ target = validate_path(ctx.args, roots)
778
+ except PathAccessError as exc:
779
+ return Text(f"❌ {exc}")
780
+
781
+ try:
782
+ if not target.exists():
783
+ return Text("❌ Folder tidak ditemukan.")
784
+ if not target.is_dir():
785
+ return Text("❌ Path tersebut bukan sebuah direktori.")
786
+
787
+ items = os.listdir(target)
788
+ folders = []
789
+ files = []
790
+ for item in sorted(items):
791
+ full_path = target / item
792
+ if full_path.is_dir():
793
+ folders.append(f"📁 {item}/")
794
+ else:
795
+ try:
796
+ size = full_path.stat().st_size
797
+ if size > 1024 * 1024:
798
+ size_str = f"{round(size / (1024 * 1024), 1)} MB"
799
+ else:
800
+ size_str = f"{round(size / 1024, 1)} KB"
801
+ except Exception:
802
+ size_str = "Error size"
803
+ files.append(f"📄 {item} ({size_str})")
804
+
805
+ content = folders + files
806
+ if not content:
807
+ return Text("Folder kosong.")
808
+
809
+ out_text = f"📂 *Daftar file di:* `{target}`\n\n" + "\n".join(content[:50])
810
+ if len(content) > 50:
811
+ out_text += f"\n... dan {len(content) - 50} item lainnya."
812
+ return Text(out_text)
813
+ except Exception as e:
814
+ return Text(f"Error: {e}")
815
+
816
+
817
+ def _cmd_download(ctx: CommandContext) -> CommandOutput:
818
+ if not ctx.args:
819
+ return Text("Gunakan format: `/download <path_file>`")
820
+
821
+ roots = resolve_allowed_roots(ctx.config)
822
+ try:
823
+ target = validate_path(ctx.args, roots)
824
+ except PathAccessError as exc:
825
+ return Text(f"❌ {exc}")
826
+
827
+ if not target.exists():
828
+ return Text("❌ File tidak ditemukan.")
829
+ if target.is_dir():
830
+ return Text("❌ Path tersebut adalah direktori, bukan file.")
831
+
832
+ return [
833
+ Text(f"Mengirim file: `{target.name}`..."),
834
+ File(path=str(target)),
835
+ ]
836
+
837
+
838
+ def _make_power_prompt_handler(action: Literal["suspend", "reboot", "shutdown"], label: str):
839
+ def _handler(ctx: CommandContext) -> CommandOutput:
840
+ if ctx.confirmations is None:
841
+ return Text("⚠️ Sistem konfirmasi belum tersedia.")
842
+ token = ctx.confirmations.create(ctx.owner_id, action)
843
+ return Buttons(
844
+ text=f"⚠️ *Konfirmasi {label}*\n\nYakin ingin menjalankan `{action}`? (berlaku 30 detik)",
845
+ rows=[
846
+ [
847
+ Button(text=f"✅ Ya, {label}", callback_data=f"/confirm {action} {token}"),
848
+ Button(text="❌ Batal", callback_data=f"/cancel {token}"),
849
+ ]
850
+ ],
851
+ )
852
+
853
+ return _handler
854
+
855
+
856
+ def _cmd_confirm(ctx: CommandContext) -> CommandOutput:
857
+ if ctx.confirmations is None:
858
+ return Text("⚠️ Sistem konfirmasi belum tersedia.")
859
+ parts = ctx.args.split()
860
+ if len(parts) != 2:
861
+ return Text("❌ Format konfirmasi tidak valid.")
862
+ action, token = parts[0].lower(), parts[1]
863
+ if action not in {"suspend", "reboot", "shutdown"}:
864
+ return Text("❌ Aksi power tidak valid.")
865
+
866
+ ok, reason = ctx.confirmations.consume(token, ctx.owner_id, action)
867
+ if not ok:
868
+ if reason == "expired":
869
+ return Text("⌛ Token konfirmasi sudah kedaluwarsa. Silakan ulangi perintah.")
870
+ return Text("❌ Token konfirmasi tidak valid atau sudah digunakan.")
871
+
872
+ time.sleep(1)
873
+ try:
874
+ ctx.driver.power_action(action) # type: ignore[arg-type]
875
+ return Text(f"✅ Menjalankan *{action}*...")
876
+ except NotSupported:
877
+ raise
878
+ except Exception as e:
879
+ return Text(f"Gagal menjalankan {action}: {e}")
880
+
881
+
882
+ def _cmd_cancel(ctx: CommandContext) -> CommandOutput:
883
+ if ctx.confirmations is None or not ctx.args.strip():
884
+ return Text("❌ Dibatalkan.")
885
+ ctx.confirmations.cancel(ctx.args.strip(), ctx.owner_id)
886
+ return Text("❌ Perintah power dibatalkan.")
887
+
888
+
889
+ def _cmd_cmd(ctx: CommandContext) -> CommandOutput:
890
+ if not ctx.args:
891
+ return Text("Gunakan format: `/cmd <perintah>`")
892
+
893
+ try:
894
+ out = ctx.driver.run_command(ctx.args, timeout=15)
895
+ if not out.strip():
896
+ out = "(Perintah selesai dijalankan, tidak ada output)"
897
+ if len(out) > 4000:
898
+ out = out[:4000] + "\n... (output terlalu panjang, dipotong)"
899
+ return Text(f"Output:\n```\n{out}\n```")
900
+ except TimeoutError:
901
+ return Text("⚠️ Perintah melampaui batas waktu 15 detik.")
902
+ except ValueError as e:
903
+ return Text(f"⚠️ Format perintah tidak valid: {e}")
904
+ except NotSupported:
905
+ raise
906
+ except Exception as e:
907
+ return Text(f"⚠️ Gagal mengeksekusi perintah:\n`{e}`")
908
+
909
+
910
+ def build_default_registry() -> CommandRegistry:
911
+ """Create and populate the default CommandRegistry with all commands."""
912
+ reg = CommandRegistry()
913
+
914
+ reg.register(Command("/start", _cmd_start, "R", "aman", description="Mulai bot"))
915
+ reg.register(Command("/help", _cmd_help, "R", "aman", description="Daftar perintah"))
916
+ reg.register(Command("/menu", _cmd_menu, "R", "aman", description="Menu kontrol"))
917
+ reg.register(Command("/none", _cmd_none, "R", "aman", show_in_commands=False))
918
+
919
+ reg.register(
920
+ Command(
921
+ "/status", _cmd_status, "R", "aman", ("system_status",), description="Status laptop"
922
+ )
923
+ )
924
+ reg.register(
925
+ Command(
926
+ "/health", _cmd_health, "R", "aman", ("system_health",), description="Kesehatan sistem"
927
+ )
928
+ )
929
+ reg.register(
930
+ Command(
931
+ "/ps",
932
+ _cmd_ps,
933
+ "R",
934
+ "aman",
935
+ ("processes",),
936
+ aliases=("/processes",),
937
+ description="Proses teratas",
938
+ )
939
+ )
940
+ reg.register(Command("/logs", _cmd_logs, "R", "aman", ("logs",), description="Log service bot"))
941
+ reg.register(
942
+ Command("/network", _cmd_network, "R", "aman", ("network",), description="Info jaringan")
943
+ )
944
+ reg.register(
945
+ Command("/ip", _cmd_ip, "R", "aman", ("network_ip",), description="IP lokal dan publik")
946
+ )
947
+
948
+ reg.register(Command("/lock", _cmd_lock, "C", "aman", ("lock",), description="Kunci layar"))
949
+ reg.register(
950
+ Command(
951
+ "/suspend",
952
+ _make_power_prompt_handler("suspend", "Suspend"),
953
+ "P",
954
+ "aman",
955
+ ("power",),
956
+ description="Tidurkan laptop",
957
+ )
958
+ )
959
+ reg.register(
960
+ Command(
961
+ "/reboot",
962
+ _make_power_prompt_handler("reboot", "Reboot"),
963
+ "P",
964
+ "aman",
965
+ ("power",),
966
+ description="Restart laptop",
967
+ )
968
+ )
969
+ reg.register(
970
+ Command(
971
+ "/shutdown",
972
+ _make_power_prompt_handler("shutdown", "Shutdown"),
973
+ "P",
974
+ "aman",
975
+ ("power",),
976
+ description="Matikan laptop",
977
+ )
978
+ )
979
+ reg.register(Command("/confirm", _cmd_confirm, "P", "aman", ("power",), show_in_commands=False))
980
+ reg.register(Command("/cancel", _cmd_cancel, "P", "aman", show_in_commands=False))
981
+
982
+ reg.register(
983
+ Command("/volume", _cmd_volume, "C", "aman", ("audio_volume",), description="Atur volume")
984
+ )
985
+ reg.register(
986
+ Command("/mute", _cmd_mute, "C", "aman", ("audio_mute",), description="Bisukan suara")
987
+ )
988
+ reg.register(
989
+ Command("/unmute", _cmd_unmute, "C", "aman", ("audio_mute",), description="Aktifkan suara")
990
+ )
991
+ reg.register(
992
+ Command("/volup", _cmd_volup, "C", "aman", ("audio_volume",), description="Naikkan volume")
993
+ )
994
+ reg.register(
995
+ Command(
996
+ "/voldown", _cmd_voldown, "C", "aman", ("audio_volume",), description="Turunkan volume"
997
+ )
998
+ )
999
+ reg.register(
1000
+ Command(
1001
+ "/play", _make_media_handler("play"), "C", "aman", ("media",), description="Putar media"
1002
+ )
1003
+ )
1004
+ reg.register(
1005
+ Command(
1006
+ "/pause",
1007
+ _make_media_handler("pause"),
1008
+ "C",
1009
+ "aman",
1010
+ ("media",),
1011
+ description="Jeda media",
1012
+ )
1013
+ )
1014
+ reg.register(
1015
+ Command(
1016
+ "/next",
1017
+ _make_media_handler("next"),
1018
+ "C",
1019
+ "aman",
1020
+ ("media",),
1021
+ description="Trek berikutnya",
1022
+ )
1023
+ )
1024
+ reg.register(
1025
+ Command(
1026
+ "/prev",
1027
+ _make_media_handler("previous"),
1028
+ "C",
1029
+ "aman",
1030
+ ("media",),
1031
+ description="Trek sebelumnya",
1032
+ )
1033
+ )
1034
+ reg.register(
1035
+ Command("/beep", _cmd_beep, "C", "aman", ("audio_beep",), description="Putar suara beep")
1036
+ )
1037
+
1038
+ reg.register(
1039
+ Command(
1040
+ "/brightness",
1041
+ _cmd_brightness,
1042
+ "C",
1043
+ "aman",
1044
+ ("brightness",),
1045
+ description="Atur kecerahan",
1046
+ )
1047
+ )
1048
+ reg.register(
1049
+ Command(
1050
+ "/notify", _cmd_notify, "C", "aman", ("notify",), description="Kirim notifikasi desktop"
1051
+ )
1052
+ )
1053
+
1054
+ reg.register(
1055
+ Command(
1056
+ "/ss",
1057
+ _cmd_ss,
1058
+ "S",
1059
+ "standar",
1060
+ ("screenshot",),
1061
+ aliases=("/screenshot",),
1062
+ description="Ambil screenshot",
1063
+ )
1064
+ )
1065
+ reg.register(
1066
+ Command(
1067
+ "/cam",
1068
+ _cmd_cam,
1069
+ "S",
1070
+ "standar",
1071
+ ("webcam_photo",),
1072
+ aliases=("/camera",),
1073
+ description="Foto webcam",
1074
+ )
1075
+ )
1076
+ reg.register(
1077
+ Command(
1078
+ "/vid",
1079
+ _cmd_vid,
1080
+ "S",
1081
+ "standar",
1082
+ ("webcam_video",),
1083
+ aliases=("/video", "/camvideo"),
1084
+ description="Video webcam",
1085
+ )
1086
+ )
1087
+ reg.register(
1088
+ Command(
1089
+ "/screenrecord",
1090
+ _cmd_screenrecord,
1091
+ "S",
1092
+ "standar",
1093
+ ("screenrecord",),
1094
+ aliases=("/scr",),
1095
+ description="Rekam layar",
1096
+ )
1097
+ )
1098
+ reg.register(
1099
+ Command(
1100
+ "/record", _cmd_record, "S", "standar", ("mic_record",), description="Rekam mikrofon"
1101
+ )
1102
+ )
1103
+
1104
+ reg.register(
1105
+ Command("/ls", _cmd_ls, "S", "standar", ("files_read",), description="Daftar file folder")
1106
+ )
1107
+ reg.register(
1108
+ Command("/find", _cmd_find, "S", "standar", ("files_read",), description="Cari file")
1109
+ )
1110
+ reg.register(
1111
+ Command(
1112
+ "/download", _cmd_download, "S", "standar", ("files_read",), description="Unduh file"
1113
+ )
1114
+ )
1115
+ reg.register(
1116
+ Command(
1117
+ "/getclip",
1118
+ _cmd_getclip,
1119
+ "S",
1120
+ "standar",
1121
+ ("clipboard_read",),
1122
+ aliases=("/paste",),
1123
+ description="Baca clipboard",
1124
+ )
1125
+ )
1126
+ reg.register(
1127
+ Command(
1128
+ "/upload", _cmd_upload, "X", "lengkap", ("files_write",), description="Info upload file"
1129
+ )
1130
+ )
1131
+ reg.register(
1132
+ Command(
1133
+ "/setclip",
1134
+ _cmd_setclip,
1135
+ "X",
1136
+ "lengkap",
1137
+ ("clipboard_write",),
1138
+ aliases=("/copy",),
1139
+ description="Salin ke clipboard",
1140
+ )
1141
+ )
1142
+
1143
+ reg.register(
1144
+ Command(
1145
+ "/youtube", _cmd_youtube, "C", "standar", ("browser",), description="Cari di YouTube"
1146
+ )
1147
+ )
1148
+ reg.register(
1149
+ Command(
1150
+ "/wallpaper",
1151
+ _cmd_wallpaper,
1152
+ "C",
1153
+ "standar",
1154
+ ("wallpaper",),
1155
+ description="Ubah wallpaper",
1156
+ )
1157
+ )
1158
+
1159
+ reg.register(
1160
+ Command("/say", _cmd_say, "S", "standar", ("tts",), description="Bacakan teks (TTS)")
1161
+ )
1162
+ reg.register(
1163
+ Command(
1164
+ "/loc",
1165
+ _cmd_loc,
1166
+ "S",
1167
+ "standar",
1168
+ ("geoip",),
1169
+ aliases=("/location",),
1170
+ description="Lokasi laptop",
1171
+ )
1172
+ )
1173
+ reg.register(
1174
+ Command(
1175
+ "/carihp",
1176
+ _cmd_carihp,
1177
+ "S",
1178
+ "standar",
1179
+ ("ntfy",),
1180
+ aliases=("/ringphone", "/bunyikanhp"),
1181
+ description="Cari HP",
1182
+ )
1183
+ )
1184
+ reg.register(
1185
+ Command(
1186
+ "/openfindmydevice",
1187
+ _cmd_openfindmydevice,
1188
+ "C",
1189
+ "standar",
1190
+ ("browser",),
1191
+ show_in_commands=False,
1192
+ )
1193
+ )
1194
+
1195
+ reg.register(
1196
+ Command("/mouse", _cmd_mouse, "X", "lengkap", ("mouse",), description="Kontrol mouse")
1197
+ )
1198
+ reg.register(
1199
+ Command(
1200
+ "/keyboard",
1201
+ _cmd_keyboard,
1202
+ "X",
1203
+ "lengkap",
1204
+ ("keyboard",),
1205
+ aliases=("/type",),
1206
+ description="Kontrol keyboard",
1207
+ )
1208
+ )
1209
+ reg.register(
1210
+ Command("/cmd", _cmd_cmd, "X", "lengkap", ("shell",), description="Jalankan perintah")
1211
+ )
1212
+
1213
+ return reg
1214
+
1215
+
1216
+ def dispatch_command(
1217
+ registry: CommandRegistry,
1218
+ config: dict[str, Any],
1219
+ driver: BaseDriver,
1220
+ chat_id: int | str,
1221
+ text: str,
1222
+ owner_id: int = 0,
1223
+ confirmations: ConfirmationManager | None = None,
1224
+ rate_limiter: RateLimiter | None = None,
1225
+ ) -> CommandOutput:
1226
+ """Resolve text/alias, enforce rate limit & profile, and run handler."""
1227
+ if rate_limiter is not None and not rate_limiter.allow(owner_id):
1228
+ return Text("⏳ Terlalu banyak perintah dalam waktu singkat. Coba lagi sebentar.")
1229
+
1230
+ clean_text = text.strip()
1231
+ mapped_text = TEXT_MAP.get(clean_text.lower(), clean_text)
1232
+
1233
+ parts = mapped_text.split(maxsplit=1)
1234
+ if not parts:
1235
+ return None
1236
+
1237
+ cmd_name = parts[0].lower()
1238
+ args = parts[1] if len(parts) > 1 else ""
1239
+
1240
+ command = registry.resolve(cmd_name)
1241
+ if command is None:
1242
+ return Text("❓ Perintah tidak dikenal. Ketik `/help` untuk bantuan.")
1243
+
1244
+ if not registry.is_allowed(command, config):
1245
+ return Text("🔒 Perintah ini tidak aktif pada profil izin saat ini.")
1246
+
1247
+ ctx = CommandContext(
1248
+ chat_id=chat_id,
1249
+ command=cmd_name,
1250
+ args=args,
1251
+ config=config,
1252
+ driver=driver,
1253
+ owner_id=owner_id,
1254
+ registry=registry,
1255
+ confirmations=confirmations,
1256
+ )
1257
+ try:
1258
+ return command.handler(ctx)
1259
+ except NotSupported as exc:
1260
+ return Text(f"⚠️ {exc.reason}")