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,163 @@
1
+ """Long-polling loop with fail-closed auth and non-blocking worker pool."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ import time
7
+ from collections.abc import Callable
8
+ from concurrent.futures import ThreadPoolExecutor
9
+ from typing import Any
10
+
11
+ from lapctl.channels.telegram.api import TelegramClient
12
+ from lapctl.channels.telegram.auth import is_authorized, log_ignored_update
13
+
14
+ logger = logging.getLogger(__name__)
15
+
16
+
17
+ class TelegramPoller:
18
+ """Runs Telegram long-polling and dispatches authorized private updates."""
19
+
20
+ def __init__(
21
+ self,
22
+ client: TelegramClient,
23
+ allowed_user_id: int,
24
+ on_text: Callable[[int | str, str, int | None, str, int], None],
25
+ on_document: Callable[[int | str, str, str, str, int], None],
26
+ on_photo: Callable[[int | str, str, str, str, int], None],
27
+ on_callback: Callable[[int | str, str, str, int], None],
28
+ on_before_update: Callable[[], None] | None = None,
29
+ max_workers: int = 4,
30
+ ) -> None:
31
+ self.client = client
32
+ self.allowed_user_id = allowed_user_id
33
+ self.on_text = on_text
34
+ self.on_document = on_document
35
+ self.on_photo = on_photo
36
+ self.on_callback = on_callback
37
+ self.on_before_update = on_before_update
38
+ self._executor = ThreadPoolExecutor(
39
+ max_workers=max_workers, thread_name_prefix="lapctl-worker"
40
+ )
41
+
42
+ def process_update(self, update: dict[str, Any], async_dispatch: bool = True) -> None:
43
+ """Authorize and dispatch a single Telegram update."""
44
+ if self.on_before_update is not None:
45
+ self.on_before_update()
46
+
47
+ message = update.get("message")
48
+ if message:
49
+ sender_id = message.get("from", {}).get("id", 0)
50
+ chat = message.get("chat", {})
51
+ chat_id = chat.get("id", 0)
52
+ chat_type = chat.get("type", "")
53
+ username = message.get("from", {}).get("username", "Unknown")
54
+
55
+ if not is_authorized(sender_id, self.allowed_user_id, chat_type=chat_type):
56
+ log_ignored_update(sender_id, chat_type)
57
+ return
58
+
59
+ if "text" in message:
60
+ self._dispatch(
61
+ async_dispatch,
62
+ self.on_text,
63
+ chat_id,
64
+ message["text"],
65
+ message.get("message_id"),
66
+ username,
67
+ sender_id,
68
+ )
69
+ elif "document" in message:
70
+ doc = message["document"]
71
+ self._dispatch(
72
+ async_dispatch,
73
+ self.on_document,
74
+ chat_id,
75
+ doc["file_id"],
76
+ doc.get("file_name", "upload"),
77
+ username,
78
+ sender_id,
79
+ )
80
+ elif "photo" in message:
81
+ photo_list = message["photo"]
82
+ if photo_list:
83
+ largest_photo = photo_list[-1]
84
+ caption = message.get("caption", "").strip().lower()
85
+ self._dispatch(
86
+ async_dispatch,
87
+ self.on_photo,
88
+ chat_id,
89
+ largest_photo["file_id"],
90
+ caption,
91
+ username,
92
+ sender_id,
93
+ )
94
+ return
95
+
96
+ cb = update.get("callback_query")
97
+ if cb:
98
+ sender_id = cb.get("from", {}).get("id", 0)
99
+ msg = cb.get("message") or {}
100
+ chat = msg.get("chat", {})
101
+ chat_id = chat.get("id", 0)
102
+ chat_type = chat.get("type", "")
103
+ cb_data = cb.get("data", "")
104
+
105
+ if not is_authorized(sender_id, self.allowed_user_id, chat_type=chat_type):
106
+ log_ignored_update(sender_id, chat_type)
107
+ return
108
+
109
+ self.client.answer_callback_query(cb["id"])
110
+ username = cb.get("from", {}).get("username", "Unknown")
111
+ self._dispatch(
112
+ async_dispatch,
113
+ self.on_callback,
114
+ chat_id,
115
+ cb_data,
116
+ username,
117
+ sender_id,
118
+ )
119
+
120
+ def _dispatch(self, async_dispatch: bool, fn: Callable[..., None], *args: Any) -> None:
121
+ if async_dispatch:
122
+ self._executor.submit(self._safe_call, fn, *args)
123
+ else:
124
+ self._safe_call(fn, *args)
125
+
126
+ @staticmethod
127
+ def _safe_call(fn: Callable[..., None], *args: Any) -> None:
128
+ try:
129
+ fn(*args)
130
+ except Exception as e:
131
+ logger.exception("Unhandled error in worker: %s", e)
132
+
133
+ def run(self) -> None:
134
+ """Start the blocking long-polling loop."""
135
+ is_online_status_set = self.client.set_bot_status_online()
136
+ last_online_attempt = time.time()
137
+ offset: int | None = None
138
+
139
+ print("=" * 40)
140
+ print("Lapctl agent sedang berjalan...")
141
+ print("Tekan Ctrl+C untuk menghentikan.")
142
+ print("=" * 40)
143
+
144
+ try:
145
+ while True:
146
+ try:
147
+ data = self.client.get_updates(offset=offset, timeout=30)
148
+ if data is not None:
149
+ if not is_online_status_set:
150
+ current_time = time.time()
151
+ if current_time - last_online_attempt > 60:
152
+ is_online_status_set = self.client.set_bot_status_online()
153
+ last_online_attempt = current_time
154
+ if "result" in data:
155
+ for update in data["result"]:
156
+ offset = update["update_id"] + 1
157
+ self.process_update(update, async_dispatch=True)
158
+ except Exception as e:
159
+ logger.warning("Polling error: %s", e)
160
+ time.sleep(5)
161
+ finally:
162
+ self._executor.shutdown(wait=False)
163
+ self.client.set_bot_status_offline()
@@ -0,0 +1,166 @@
1
+ """Render core Result objects to Telegram API calls with 50 MB size checks."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import tempfile
7
+ from typing import Any
8
+
9
+ from lapctl.channels.telegram.api import TelegramClient
10
+ from lapctl.drivers.base import BaseDriver
11
+ from lapctl.registry import CommandRegistry
12
+ from lapctl.results import (
13
+ Audio,
14
+ Button,
15
+ Buttons,
16
+ CommandOutput,
17
+ DeleteMessage,
18
+ File,
19
+ Image,
20
+ Location,
21
+ Result,
22
+ Text,
23
+ Video,
24
+ )
25
+
26
+ MAX_TELEGRAM_UPLOAD_BYTES = 50 * 1024 * 1024
27
+
28
+
29
+ def _button_to_dict(btn: Button) -> dict[str, str]:
30
+ data: dict[str, str] = {"text": btn.text}
31
+ if btn.url is not None:
32
+ data["url"] = btn.url
33
+ elif btn.callback_data is not None:
34
+ data["callback_data"] = btn.callback_data
35
+ return data
36
+
37
+
38
+ def buttons_to_reply_markup(buttons: Buttons) -> dict[str, Any]:
39
+ """Convert a Buttons Result into Telegram inline_keyboard markup."""
40
+ return {"inline_keyboard": [[_button_to_dict(btn) for btn in row] for row in buttons.rows]}
41
+
42
+
43
+ def _cleanup_if_needed(path: str, cleanup: bool) -> None:
44
+ if cleanup and os.path.exists(path):
45
+ try:
46
+ os.remove(path)
47
+ except OSError:
48
+ pass
49
+
50
+
51
+ def _render_video(
52
+ client: TelegramClient,
53
+ chat_id: int | str,
54
+ item: Video,
55
+ driver: BaseDriver | None,
56
+ ) -> None:
57
+ send_path = item.path
58
+ compressed_path: str | None = None
59
+ try:
60
+ size = os.path.getsize(send_path) if os.path.exists(send_path) else 0
61
+ if size > MAX_TELEGRAM_UPLOAD_BYTES:
62
+ if driver is not None:
63
+ fd, compressed_path = tempfile.mkstemp(prefix="lapctl_cmp_", suffix=".mp4")
64
+ os.close(fd)
65
+ if (
66
+ driver.compress_video(send_path, compressed_path)
67
+ and os.path.getsize(compressed_path) <= MAX_TELEGRAM_UPLOAD_BYTES
68
+ ):
69
+ send_path = compressed_path
70
+ else:
71
+ client.send_message(
72
+ chat_id,
73
+ "❌ Video melebihi batas Telegram (±50 MB) dan gagal dikompres.",
74
+ )
75
+ return
76
+ else:
77
+ client.send_message(
78
+ chat_id,
79
+ "❌ Video melebihi batas Telegram (±50 MB) dan tidak dapat dikirim.",
80
+ )
81
+ return
82
+ client.send_video(chat_id, send_path, caption=item.caption)
83
+ finally:
84
+ _cleanup_if_needed(item.path, item.cleanup)
85
+ if compressed_path is not None:
86
+ _cleanup_if_needed(compressed_path, True)
87
+
88
+
89
+ def render_single(
90
+ client: TelegramClient,
91
+ chat_id: int | str,
92
+ item: Result,
93
+ driver: BaseDriver | None = None,
94
+ ) -> dict[str, Any] | None:
95
+ """Render a single Result item via TelegramClient."""
96
+ if isinstance(item, Text):
97
+ return client.send_message(chat_id, item.text)
98
+ if isinstance(item, Buttons):
99
+ return client.send_message(chat_id, item.text, reply_markup=buttons_to_reply_markup(item))
100
+ if isinstance(item, Image):
101
+ try:
102
+ if os.path.exists(item.path) and os.path.getsize(item.path) > MAX_TELEGRAM_UPLOAD_BYTES:
103
+ client.send_message(chat_id, "❌ Ukuran gambar melebihi batas Telegram (±50 MB).")
104
+ return None
105
+ client.send_photo(chat_id, item.path, caption=item.caption)
106
+ finally:
107
+ _cleanup_if_needed(item.path, item.cleanup)
108
+ return None
109
+ if isinstance(item, Video):
110
+ _render_video(client, chat_id, item, driver)
111
+ return None
112
+ if isinstance(item, Audio):
113
+ try:
114
+ if os.path.exists(item.path) and os.path.getsize(item.path) > MAX_TELEGRAM_UPLOAD_BYTES:
115
+ client.send_message(chat_id, "❌ Ukuran audio melebihi batas Telegram (±50 MB).")
116
+ return None
117
+ client.send_voice(chat_id, item.path, caption=item.caption)
118
+ finally:
119
+ _cleanup_if_needed(item.path, item.cleanup)
120
+ return None
121
+ if isinstance(item, File):
122
+ try:
123
+ if os.path.exists(item.path) and os.path.getsize(item.path) > MAX_TELEGRAM_UPLOAD_BYTES:
124
+ client.send_message(
125
+ chat_id,
126
+ "❌ Ukuran file melebihi batas Telegram (±50 MB) dan tidak dapat dikirim.",
127
+ )
128
+ return None
129
+ client.send_document(chat_id, item.path, caption=item.caption)
130
+ finally:
131
+ _cleanup_if_needed(item.path, item.cleanup)
132
+ return None
133
+ if isinstance(item, Location):
134
+ client.send_location(chat_id, item.latitude, item.longitude)
135
+ return None
136
+ if isinstance(item, DeleteMessage):
137
+ client.delete_message(chat_id, item.message_id)
138
+ return None
139
+ return None
140
+
141
+
142
+ def render_output(
143
+ client: TelegramClient,
144
+ chat_id: int | str,
145
+ output: CommandOutput,
146
+ driver: BaseDriver | None = None,
147
+ ) -> dict[str, Any] | None:
148
+ """Render a CommandOutput (single Result, list of Results, or None)."""
149
+ if output is None:
150
+ return None
151
+ items = output if isinstance(output, list) else [output]
152
+ last_response: dict[str, Any] | None = None
153
+ for item in items:
154
+ resp = render_single(client, chat_id, item, driver=driver)
155
+ if resp is not None:
156
+ last_response = resp
157
+ return last_response
158
+
159
+
160
+ def sync_bot_commands(
161
+ client: TelegramClient,
162
+ registry: CommandRegistry,
163
+ config: dict[str, Any] | None = None,
164
+ ) -> bool:
165
+ """Sync registered commands (filtered by profile) to Telegram's setMyCommands."""
166
+ return client.set_my_commands(registry.list_telegram_commands(config=config))