watchpost-agent 0.4.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.
- watchpost/__init__.py +4 -0
- watchpost/adapters/__init__.py +24 -0
- watchpost/adapters/dingtalk.py +348 -0
- watchpost/adapters/discord.py +289 -0
- watchpost/adapters/external_plugin.py +98 -0
- watchpost/adapters/feishu.py +668 -0
- watchpost/adapters/local_sandbox.py +277 -0
- watchpost/adapters/simulator.py +198 -0
- watchpost/adapters/slack.py +376 -0
- watchpost/adapters/telegram.py +608 -0
- watchpost/adapters/wecom.py +360 -0
- watchpost/assets/avatar.jpg +0 -0
- watchpost/backends/__init__.py +8 -0
- watchpost/backends/antigravity.py +216 -0
- watchpost/backends/cli_agent.py +284 -0
- watchpost/backends/fallback.py +139 -0
- watchpost/backends/mock.py +165 -0
- watchpost/bubbles.py +227 -0
- watchpost/cli.py +1123 -0
- watchpost/config.py +552 -0
- watchpost/context.py +203 -0
- watchpost/daemon.py +1132 -0
- watchpost/debouncer.py +110 -0
- watchpost/engine.py +1837 -0
- watchpost/filters.py +131 -0
- watchpost/media.py +95 -0
- watchpost/models.py +188 -0
- watchpost/notifiers/__init__.py +269 -0
- watchpost/notifiers/bark.py +136 -0
- watchpost/notifiers/console.py +96 -0
- watchpost/notifiers/discord.py +181 -0
- watchpost/notifiers/external_plugin.py +122 -0
- watchpost/notifiers/imessage.py +571 -0
- watchpost/notifiers/ntfy.py +192 -0
- watchpost/notifiers/pushover.py +130 -0
- watchpost/notifiers/slack.py +212 -0
- watchpost/notifiers/telegram.py +918 -0
- watchpost/notifiers/wecom.py +120 -0
- watchpost/plugins.py +268 -0
- watchpost/ports.py +112 -0
- watchpost/prompts.py +396 -0
- watchpost/sandbox.py +345 -0
- watchpost/sandbox_ui.py +1300 -0
- watchpost/sdk.py +302 -0
- watchpost/security.py +142 -0
- watchpost/server.py +386 -0
- watchpost/setup_wizard.py +489 -0
- watchpost/skill_installer.py +53 -0
- watchpost/skills/watchpost/SKILL.md +116 -0
- watchpost/store.py +966 -0
- watchpost_agent-0.4.1.dist-info/METADATA +171 -0
- watchpost_agent-0.4.1.dist-info/RECORD +55 -0
- watchpost_agent-0.4.1.dist-info/WHEEL +4 -0
- watchpost_agent-0.4.1.dist-info/entry_points.txt +2 -0
- watchpost_agent-0.4.1.dist-info/licenses/LICENSE +202 -0
watchpost/__init__.py
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
"""Channel adapters for Watchpost."""
|
|
2
|
+
|
|
3
|
+
from watchpost.adapters.dingtalk import DingTalkAdapter
|
|
4
|
+
from watchpost.adapters.discord import DiscordAdapter
|
|
5
|
+
from watchpost.adapters.external_plugin import ExternalCommandAdapter
|
|
6
|
+
from watchpost.adapters.feishu import FeishuAdapter
|
|
7
|
+
from watchpost.adapters.local_sandbox import LocalSandboxAdapter
|
|
8
|
+
from watchpost.adapters.simulator import SimulatorAdapter
|
|
9
|
+
from watchpost.adapters.slack import SlackAdapter
|
|
10
|
+
from watchpost.adapters.telegram import TelegramInboundAdapter, TelegramUpdateHub
|
|
11
|
+
from watchpost.adapters.wecom import WeComAdapter
|
|
12
|
+
|
|
13
|
+
__all__ = [
|
|
14
|
+
"DingTalkAdapter",
|
|
15
|
+
"DiscordAdapter",
|
|
16
|
+
"ExternalCommandAdapter",
|
|
17
|
+
"FeishuAdapter",
|
|
18
|
+
"LocalSandboxAdapter",
|
|
19
|
+
"SimulatorAdapter",
|
|
20
|
+
"SlackAdapter",
|
|
21
|
+
"TelegramInboundAdapter",
|
|
22
|
+
"TelegramUpdateHub",
|
|
23
|
+
"WeComAdapter",
|
|
24
|
+
]
|
|
@@ -0,0 +1,348 @@
|
|
|
1
|
+
"""DingTalk ChannelAdapter powered by signed callback webhooks + official robot media API."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import base64
|
|
6
|
+
from datetime import datetime
|
|
7
|
+
import hashlib
|
|
8
|
+
import hmac
|
|
9
|
+
import json
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
import re
|
|
12
|
+
import time
|
|
13
|
+
from typing import Any
|
|
14
|
+
|
|
15
|
+
import httpx
|
|
16
|
+
|
|
17
|
+
from watchpost.config import DingTalkConfig
|
|
18
|
+
from watchpost.models import (
|
|
19
|
+
ChannelConfig,
|
|
20
|
+
MediaArtifact,
|
|
21
|
+
MediaRef,
|
|
22
|
+
Mention,
|
|
23
|
+
NormalizedMessage,
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
_SAFE_STEM_RE = re.compile(r"[^A-Za-z0-9._-]+")
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def verify_dingtalk_signature(
|
|
30
|
+
timestamp: str,
|
|
31
|
+
sign: str,
|
|
32
|
+
secret: str,
|
|
33
|
+
*,
|
|
34
|
+
now_ms: int | None = None,
|
|
35
|
+
max_skew_ms: int = 3_600_000,
|
|
36
|
+
) -> bool:
|
|
37
|
+
"""Verify DingTalk robot/event callback HMAC-SHA256 signature and timestamp window."""
|
|
38
|
+
ts_clean = (timestamp or "").strip()
|
|
39
|
+
sign_clean = (sign or "").strip()
|
|
40
|
+
sec_clean = (secret or "").strip()
|
|
41
|
+
if not ts_clean or not sign_clean or not sec_clean:
|
|
42
|
+
return False
|
|
43
|
+
try:
|
|
44
|
+
ts_ms = int(ts_clean)
|
|
45
|
+
except ValueError:
|
|
46
|
+
return False
|
|
47
|
+
ref_ms = now_ms if now_ms is not None else int(time.time() * 1000)
|
|
48
|
+
if abs(ref_ms - ts_ms) > max_skew_ms:
|
|
49
|
+
return False
|
|
50
|
+
string_to_sign = f"{ts_clean}\n{sec_clean}".encode("utf-8")
|
|
51
|
+
digest = hmac.new(sec_clean.encode("utf-8"), string_to_sign, hashlib.sha256).digest()
|
|
52
|
+
expected = base64.b64encode(digest).decode("utf-8")
|
|
53
|
+
return hmac.compare_digest(expected, sign_clean)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _format_ts_ms(create_ms: int) -> str:
|
|
57
|
+
if create_ms <= 0:
|
|
58
|
+
return ""
|
|
59
|
+
return datetime.fromtimestamp(create_ms / 1000.0).strftime("%H:%M:%S")
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _sanitize_filename(name: str, *, fallback: str, default_ext: str) -> str:
|
|
63
|
+
base = Path(name or "").name.strip()
|
|
64
|
+
base = _SAFE_STEM_RE.sub("_", base).strip("._")
|
|
65
|
+
if not base:
|
|
66
|
+
base = _SAFE_STEM_RE.sub("_", fallback) or "artifact"
|
|
67
|
+
if "." not in base and default_ext:
|
|
68
|
+
base = f"{base}.{default_ext.lstrip('.')}"
|
|
69
|
+
return base[:120]
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
class DingTalkAdapter:
|
|
73
|
+
"""DingTalk ChannelAdapter using signed HTTP callback events and official media APIs."""
|
|
74
|
+
|
|
75
|
+
name = "dingtalk"
|
|
76
|
+
|
|
77
|
+
def __init__(
|
|
78
|
+
self,
|
|
79
|
+
config: DingTalkConfig,
|
|
80
|
+
*,
|
|
81
|
+
inbox_path: Path | None = None,
|
|
82
|
+
client: httpx.AsyncClient | None = None,
|
|
83
|
+
) -> None:
|
|
84
|
+
self.config = config
|
|
85
|
+
raw_inbox = inbox_path or (
|
|
86
|
+
Path(config.inbox_path).expanduser()
|
|
87
|
+
if config.inbox_path
|
|
88
|
+
else Path("~/.local/share/watchpost/webhooks/dingtalk.jsonl").expanduser()
|
|
89
|
+
)
|
|
90
|
+
self._inbox_path = Path(raw_inbox)
|
|
91
|
+
self._owner_user_id = config.owner_user_id.strip()
|
|
92
|
+
self._base_url = (config.base_url or "https://api.dingtalk.com").strip().rstrip("/")
|
|
93
|
+
self._external_client = client
|
|
94
|
+
self._owned_client: httpx.AsyncClient | None = None
|
|
95
|
+
self._token_value: str = ""
|
|
96
|
+
self._token_expires_at: float = 0.0
|
|
97
|
+
|
|
98
|
+
@property
|
|
99
|
+
def inbox_path(self) -> Path:
|
|
100
|
+
return self._inbox_path
|
|
101
|
+
|
|
102
|
+
def _client(self) -> httpx.AsyncClient:
|
|
103
|
+
if self._external_client is not None:
|
|
104
|
+
return self._external_client
|
|
105
|
+
if self._owned_client is None:
|
|
106
|
+
self._owned_client = httpx.AsyncClient(timeout=20.0)
|
|
107
|
+
return self._owned_client
|
|
108
|
+
|
|
109
|
+
async def aclose(self) -> None:
|
|
110
|
+
if self._owned_client is not None:
|
|
111
|
+
await self._owned_client.aclose()
|
|
112
|
+
self._owned_client = None
|
|
113
|
+
|
|
114
|
+
async def _get_access_token(self) -> str:
|
|
115
|
+
now = time.monotonic()
|
|
116
|
+
if self._token_value and now < self._token_expires_at - 60:
|
|
117
|
+
return self._token_value
|
|
118
|
+
if not self.config.app_key.strip() or not self.config.app_secret.strip():
|
|
119
|
+
raise RuntimeError("DingTalk app_key and app_secret must be configured")
|
|
120
|
+
resp = await self._client().post(
|
|
121
|
+
f"{self._base_url}/v1.0/oauth2/accessToken",
|
|
122
|
+
json={
|
|
123
|
+
"appKey": self.config.app_key.strip(),
|
|
124
|
+
"appSecret": self.config.app_secret.strip(),
|
|
125
|
+
},
|
|
126
|
+
)
|
|
127
|
+
resp.raise_for_status()
|
|
128
|
+
payload = resp.json()
|
|
129
|
+
token = str((payload or {}).get("accessToken") or "").strip()
|
|
130
|
+
if not token:
|
|
131
|
+
raise RuntimeError(f"DingTalk accessToken request failed: {payload}")
|
|
132
|
+
ttl = int((payload or {}).get("expireIn") or 7200)
|
|
133
|
+
self._token_value = token
|
|
134
|
+
self._token_expires_at = now + ttl
|
|
135
|
+
return token
|
|
136
|
+
|
|
137
|
+
def ingest_webhook_payload(self, payload: dict[str, Any]) -> NormalizedMessage:
|
|
138
|
+
"""Normalize and persist an incoming DingTalk callback event to the local JSONL inbox."""
|
|
139
|
+
conv_id = str(payload.get("conversationId") or "").strip()
|
|
140
|
+
if not conv_id:
|
|
141
|
+
raise ValueError("DingTalk payload missing conversationId")
|
|
142
|
+
|
|
143
|
+
conv_type_raw = str(payload.get("conversationType") or "2").strip()
|
|
144
|
+
chat_type = "p2p" if conv_type_raw == "1" else "group"
|
|
145
|
+
sender_id = str(payload.get("senderStaffId") or payload.get("senderId") or "").strip()
|
|
146
|
+
sender_name = str(payload.get("senderNick") or sender_id or "Unknown").strip()
|
|
147
|
+
conv_title = str(payload.get("conversationTitle") or sender_name or conv_id).strip()
|
|
148
|
+
|
|
149
|
+
raw_create = payload.get("createAt") or payload.get("timestamp")
|
|
150
|
+
try:
|
|
151
|
+
create_ms = int(raw_create) if raw_create is not None else int(time.time() * 1000)
|
|
152
|
+
if 0 < create_ms < 10_000_000_000:
|
|
153
|
+
create_ms *= 1000
|
|
154
|
+
except (TypeError, ValueError):
|
|
155
|
+
create_ms = int(time.time() * 1000)
|
|
156
|
+
|
|
157
|
+
msg_id = str(payload.get("msgId") or f"dt_{create_ms}_{sender_id or 'msg'}").strip()
|
|
158
|
+
is_owner = bool(self._owner_user_id and sender_id == self._owner_user_id)
|
|
159
|
+
msgtype = str(payload.get("msgtype") or "text").strip().lower()
|
|
160
|
+
|
|
161
|
+
text_parts: list[str] = []
|
|
162
|
+
media_refs: list[MediaRef] = []
|
|
163
|
+
content_obj = payload.get("content") if isinstance(payload.get("content"), dict) else {}
|
|
164
|
+
|
|
165
|
+
if msgtype == "text":
|
|
166
|
+
txt = str((payload.get("text") or {}).get("content") or "").strip()
|
|
167
|
+
if txt:
|
|
168
|
+
text_parts.append(txt)
|
|
169
|
+
elif msgtype == "richtext":
|
|
170
|
+
for chunk in content_obj.get("richText") or []:
|
|
171
|
+
if not isinstance(chunk, dict):
|
|
172
|
+
continue
|
|
173
|
+
if chunk.get("text"):
|
|
174
|
+
text_parts.append(str(chunk["text"]).strip())
|
|
175
|
+
pic_code = str(chunk.get("pictureDownloadCode") or chunk.get("downloadCode") or "").strip()
|
|
176
|
+
if pic_code:
|
|
177
|
+
media_refs.append(MediaRef(kind="image", key=pic_code, ext="png", extra={"name": f"{pic_code}.png"}))
|
|
178
|
+
elif msgtype in {"picture", "image"}:
|
|
179
|
+
code = str(content_obj.get("downloadCode") or payload.get("downloadCode") or "").strip()
|
|
180
|
+
if code:
|
|
181
|
+
media_refs.append(MediaRef(kind="image", key=code, ext="png", extra={"name": f"{code}.png"}))
|
|
182
|
+
elif msgtype in {"audio", "voice"}:
|
|
183
|
+
code = str(content_obj.get("downloadCode") or payload.get("downloadCode") or "").strip()
|
|
184
|
+
rec = str(content_obj.get("recognition") or "").strip()
|
|
185
|
+
if rec:
|
|
186
|
+
text_parts.append(rec)
|
|
187
|
+
if code:
|
|
188
|
+
media_refs.append(MediaRef(kind="audio", key=code, ext="amr", extra={"name": f"{code}.amr"}))
|
|
189
|
+
elif msgtype == "file":
|
|
190
|
+
code = str(content_obj.get("downloadCode") or payload.get("downloadCode") or "").strip()
|
|
191
|
+
fname = str(content_obj.get("fileName") or f"{code}.bin").strip()
|
|
192
|
+
ext = Path(fname).suffix.lower().lstrip(".") or "bin"
|
|
193
|
+
if code:
|
|
194
|
+
media_refs.append(MediaRef(kind="file", key=code, ext=ext, extra={"name": fname}))
|
|
195
|
+
else:
|
|
196
|
+
fallback = str((payload.get("text") or {}).get("content") or payload.get("content") or "").strip()
|
|
197
|
+
if fallback:
|
|
198
|
+
text_parts.append(fallback)
|
|
199
|
+
|
|
200
|
+
clean_text = "\n".join(p for p in text_parts if p).strip()
|
|
201
|
+
mentions: list[Mention] = []
|
|
202
|
+
mentions_owner = False
|
|
203
|
+
at_users = payload.get("atUsers") or []
|
|
204
|
+
for u in at_users:
|
|
205
|
+
if not isinstance(u, dict):
|
|
206
|
+
continue
|
|
207
|
+
staff_id = str(u.get("staffId") or "").strip()
|
|
208
|
+
dt_id = str(u.get("dingtalkId") or "").strip()
|
|
209
|
+
uid = staff_id or dt_id
|
|
210
|
+
if not uid:
|
|
211
|
+
continue
|
|
212
|
+
disp = str(u.get("name") or u.get("nick") or uid).strip()
|
|
213
|
+
mentions.append(Mention(id=uid, name=disp, key=f"@{disp}"))
|
|
214
|
+
if self._owner_user_id and self._owner_user_id in {staff_id, dt_id}:
|
|
215
|
+
mentions_owner = True
|
|
216
|
+
|
|
217
|
+
if not self._owner_user_id and bool(payload.get("isInAtList")):
|
|
218
|
+
mentions_owner = True
|
|
219
|
+
|
|
220
|
+
norm_msg_type = "text"
|
|
221
|
+
if not clean_text and media_refs:
|
|
222
|
+
norm_msg_type = media_refs[0].kind
|
|
223
|
+
|
|
224
|
+
msg = NormalizedMessage(
|
|
225
|
+
message_id=msg_id,
|
|
226
|
+
create_ms=create_ms,
|
|
227
|
+
create_time=_format_ts_ms(create_ms),
|
|
228
|
+
sender_id=sender_id,
|
|
229
|
+
sender_name=sender_name,
|
|
230
|
+
sender_type="user",
|
|
231
|
+
is_owner=is_owner,
|
|
232
|
+
is_bot=False,
|
|
233
|
+
msg_type=norm_msg_type,
|
|
234
|
+
raw_content=json.dumps(payload, ensure_ascii=False),
|
|
235
|
+
clean_text=clean_text,
|
|
236
|
+
mentions=mentions,
|
|
237
|
+
mentions_owner=mentions_owner,
|
|
238
|
+
mentions_all=False,
|
|
239
|
+
media_refs=media_refs,
|
|
240
|
+
)
|
|
241
|
+
record = {
|
|
242
|
+
"chat": {
|
|
243
|
+
"external_chat_id": conv_id,
|
|
244
|
+
"name": conv_title,
|
|
245
|
+
"chat_type": chat_type,
|
|
246
|
+
},
|
|
247
|
+
"message": msg.model_dump(mode="json"),
|
|
248
|
+
}
|
|
249
|
+
self._inbox_path.parent.mkdir(parents=True, exist_ok=True)
|
|
250
|
+
with self._inbox_path.open("a", encoding="utf-8") as fh:
|
|
251
|
+
fh.write(json.dumps(record, ensure_ascii=False) + "\n")
|
|
252
|
+
return msg
|
|
253
|
+
|
|
254
|
+
def _read_inbox_records(self) -> list[dict[str, Any]]:
|
|
255
|
+
if not self._inbox_path.is_file():
|
|
256
|
+
return []
|
|
257
|
+
entries: list[dict[str, Any]] = []
|
|
258
|
+
for raw_line in self._inbox_path.read_text(encoding="utf-8", errors="replace").splitlines():
|
|
259
|
+
line = raw_line.strip()
|
|
260
|
+
if not line:
|
|
261
|
+
continue
|
|
262
|
+
try:
|
|
263
|
+
obj = json.loads(line)
|
|
264
|
+
except json.JSONDecodeError:
|
|
265
|
+
continue
|
|
266
|
+
if isinstance(obj, dict) and isinstance(obj.get("message"), dict):
|
|
267
|
+
entries.append(obj)
|
|
268
|
+
return entries
|
|
269
|
+
|
|
270
|
+
async def list_available_chats(self) -> list[dict[str, str]]:
|
|
271
|
+
seen: dict[str, dict[str, str]] = {}
|
|
272
|
+
for entry in self._read_inbox_records():
|
|
273
|
+
chat = entry.get("chat") or {}
|
|
274
|
+
cid = str(chat.get("external_chat_id") or "").strip()
|
|
275
|
+
if not cid:
|
|
276
|
+
continue
|
|
277
|
+
seen[cid] = {
|
|
278
|
+
"external_chat_id": cid,
|
|
279
|
+
"name": str(chat.get("name") or cid),
|
|
280
|
+
"chat_type": str(chat.get("chat_type") or "group"),
|
|
281
|
+
}
|
|
282
|
+
return list(seen.values())
|
|
283
|
+
|
|
284
|
+
async def fetch_recent(self, channel: ChannelConfig, *, limit: int = 50) -> list[NormalizedMessage]:
|
|
285
|
+
by_id: dict[str, NormalizedMessage] = {}
|
|
286
|
+
for entry in self._read_inbox_records():
|
|
287
|
+
chat = entry.get("chat") or {}
|
|
288
|
+
if str(chat.get("external_chat_id") or "").strip() != channel.external_chat_id:
|
|
289
|
+
continue
|
|
290
|
+
msg = NormalizedMessage.model_validate(entry["message"])
|
|
291
|
+
msg = msg.model_copy(update={"channel_id": channel.id})
|
|
292
|
+
by_id[msg.message_id] = msg
|
|
293
|
+
ordered = sorted(by_id.values(), key=lambda m: (m.create_ms, m.message_id))
|
|
294
|
+
return ordered[-max(1, int(limit)) :]
|
|
295
|
+
|
|
296
|
+
async def fetch_by_ids(self, channel: ChannelConfig, message_ids: list[str]) -> list[NormalizedMessage]:
|
|
297
|
+
wanted = {str(mid).strip() for mid in message_ids if str(mid).strip()}
|
|
298
|
+
if not wanted:
|
|
299
|
+
return []
|
|
300
|
+
out: list[NormalizedMessage] = []
|
|
301
|
+
for entry in self._read_inbox_records():
|
|
302
|
+
chat = entry.get("chat") or {}
|
|
303
|
+
if str(chat.get("external_chat_id") or "").strip() != channel.external_chat_id:
|
|
304
|
+
continue
|
|
305
|
+
msg = NormalizedMessage.model_validate(entry["message"])
|
|
306
|
+
if msg.message_id in wanted:
|
|
307
|
+
out.append(msg.model_copy(update={"channel_id": channel.id}))
|
|
308
|
+
return sorted(out, key=lambda m: (m.create_ms, m.message_id))
|
|
309
|
+
|
|
310
|
+
async def download_media(
|
|
311
|
+
self,
|
|
312
|
+
channel: ChannelConfig,
|
|
313
|
+
message: NormalizedMessage,
|
|
314
|
+
dest_dir: Path,
|
|
315
|
+
) -> list[MediaArtifact]:
|
|
316
|
+
del channel
|
|
317
|
+
if not message.media_refs:
|
|
318
|
+
return []
|
|
319
|
+
target_dir = Path(dest_dir).expanduser()
|
|
320
|
+
target_dir.mkdir(parents=True, exist_ok=True)
|
|
321
|
+
robot_code = (self.config.robot_code or self.config.app_key).strip()
|
|
322
|
+
artifacts: list[MediaArtifact] = []
|
|
323
|
+
|
|
324
|
+
for ref in message.media_refs:
|
|
325
|
+
try:
|
|
326
|
+
token = await self._get_access_token()
|
|
327
|
+
resp = await self._client().post(
|
|
328
|
+
f"{self._base_url}/v1.0/robot/messageFiles/download",
|
|
329
|
+
headers={"x-acs-dingtalk-access-token": token},
|
|
330
|
+
json={"downloadCode": ref.key, "robotCode": robot_code},
|
|
331
|
+
)
|
|
332
|
+
resp.raise_for_status()
|
|
333
|
+
dl_url = str((resp.json() or {}).get("downloadUrl") or "").strip()
|
|
334
|
+
if not dl_url:
|
|
335
|
+
raise RuntimeError("DingTalk messageFiles/download did not return downloadUrl")
|
|
336
|
+
dl = await self._client().get(dl_url, follow_redirects=True)
|
|
337
|
+
dl.raise_for_status()
|
|
338
|
+
fname = _sanitize_filename(
|
|
339
|
+
str((ref.extra or {}).get("name") or ""),
|
|
340
|
+
fallback=ref.key,
|
|
341
|
+
default_ext=ref.ext or "bin",
|
|
342
|
+
)
|
|
343
|
+
dest_path = target_dir / f"{_SAFE_STEM_RE.sub('_', ref.key)}_{fname}"
|
|
344
|
+
dest_path.write_bytes(dl.content)
|
|
345
|
+
artifacts.append(MediaArtifact(kind=ref.kind, key=ref.key, path=str(dest_path)))
|
|
346
|
+
except Exception as exc:
|
|
347
|
+
artifacts.append(MediaArtifact(kind=ref.kind, key=ref.key, error=str(exc)))
|
|
348
|
+
return artifacts
|
|
@@ -0,0 +1,289 @@
|
|
|
1
|
+
"""Discord Guild ChannelAdapter built cleanly on the official Discord REST API v10."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from datetime import datetime
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
import re
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
import httpx
|
|
11
|
+
|
|
12
|
+
from watchpost.config import DiscordConfig
|
|
13
|
+
from watchpost.models import (
|
|
14
|
+
ChannelConfig,
|
|
15
|
+
MediaArtifact,
|
|
16
|
+
MediaRef,
|
|
17
|
+
Mention,
|
|
18
|
+
NormalizedMessage,
|
|
19
|
+
)
|
|
20
|
+
|
|
21
|
+
_MENTION_RE = re.compile(r"<@!?(\d+)>")
|
|
22
|
+
_SAFE_STEM_RE = re.compile(r"[^A-Za-z0-9._-]+")
|
|
23
|
+
_IMAGE_EXTS = frozenset({"png", "jpg", "jpeg", "gif", "webp", "bmp", "heic"})
|
|
24
|
+
_AUDIO_EXTS = frozenset({"mp3", "wav", "ogg", "oga", "m4a", "aac", "opus", "webm", "flac"})
|
|
25
|
+
_DISCORD_TEXT_CHANNEL_TYPES = frozenset({0, 5, 10, 11, 12})
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _snowflake_key(msg_id: str) -> tuple[int, str]:
|
|
29
|
+
clean = (msg_id or "").strip()
|
|
30
|
+
return (int(clean) if clean.isdigit() else 0), clean
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _parse_iso_ms(raw_ts: str) -> int:
|
|
34
|
+
clean = (raw_ts or "").strip()
|
|
35
|
+
if not clean:
|
|
36
|
+
return 0
|
|
37
|
+
try:
|
|
38
|
+
return int(datetime.fromisoformat(clean.replace("Z", "+00:00")).timestamp() * 1000)
|
|
39
|
+
except ValueError:
|
|
40
|
+
return 0
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _format_ts_ms(create_ms: int) -> str:
|
|
44
|
+
if create_ms <= 0:
|
|
45
|
+
return ""
|
|
46
|
+
return datetime.fromtimestamp(create_ms / 1000.0).strftime("%H:%M:%S")
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _sanitize_filename(name: str, *, fallback: str, default_ext: str) -> str:
|
|
50
|
+
base = Path(name or "").name.strip()
|
|
51
|
+
base = _SAFE_STEM_RE.sub("_", base).strip("._")
|
|
52
|
+
if not base:
|
|
53
|
+
base = _SAFE_STEM_RE.sub("_", fallback) or "artifact"
|
|
54
|
+
if "." not in base and default_ext:
|
|
55
|
+
base = f"{base}.{default_ext.lstrip('.')}"
|
|
56
|
+
return base[:120]
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _classify_attachment(att: dict[str, Any]) -> tuple[str, str]:
|
|
60
|
+
ctype = str(att.get("content_type") or "").lower()
|
|
61
|
+
fname = str(att.get("filename") or "").strip()
|
|
62
|
+
ext = Path(fname).suffix.lower().lstrip(".")
|
|
63
|
+
if ctype.startswith("image/") or ext in _IMAGE_EXTS:
|
|
64
|
+
return "image", ext or "png"
|
|
65
|
+
if ctype.startswith("audio/") or ext in _AUDIO_EXTS:
|
|
66
|
+
return "audio", ext or "ogg"
|
|
67
|
+
return "file", ext or "bin"
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
class DiscordAdapter:
|
|
71
|
+
"""Official Discord REST API v10 ChannelAdapter (`bot_token`)."""
|
|
72
|
+
|
|
73
|
+
name = "discord"
|
|
74
|
+
|
|
75
|
+
def __init__(self, config: DiscordConfig, *, client: httpx.AsyncClient | None = None) -> None:
|
|
76
|
+
self.config = config
|
|
77
|
+
self._token = config.bot_token.strip()
|
|
78
|
+
self._owner_user_id = config.owner_user_id.strip()
|
|
79
|
+
self._base_url = (config.base_url or "https://discord.com/api/v10").strip().rstrip("/")
|
|
80
|
+
self._external_client = client
|
|
81
|
+
self._owned_client: httpx.AsyncClient | None = None
|
|
82
|
+
|
|
83
|
+
def _client(self) -> httpx.AsyncClient:
|
|
84
|
+
if self._external_client is not None:
|
|
85
|
+
return self._external_client
|
|
86
|
+
if self._owned_client is None:
|
|
87
|
+
self._owned_client = httpx.AsyncClient(timeout=20.0)
|
|
88
|
+
return self._owned_client
|
|
89
|
+
|
|
90
|
+
async def aclose(self) -> None:
|
|
91
|
+
if self._owned_client is not None:
|
|
92
|
+
await self._owned_client.aclose()
|
|
93
|
+
self._owned_client = None
|
|
94
|
+
|
|
95
|
+
def _auth_headers(self) -> dict[str, str]:
|
|
96
|
+
if not self._token:
|
|
97
|
+
raise RuntimeError("Discord bot_token must be configured")
|
|
98
|
+
return {"Authorization": f"Bot {self._token}"}
|
|
99
|
+
|
|
100
|
+
def _normalize_message(self, channel_id: str, raw: dict[str, Any]) -> NormalizedMessage:
|
|
101
|
+
msg_id = str(raw.get("id") or "").strip()
|
|
102
|
+
create_ms = _parse_iso_ms(str(raw.get("timestamp") or ""))
|
|
103
|
+
author = raw.get("author") or {}
|
|
104
|
+
sender_id = str(author.get("id") or "").strip()
|
|
105
|
+
sender_name = (
|
|
106
|
+
str(author.get("global_name") or author.get("username") or sender_id or "Unknown").strip()
|
|
107
|
+
)
|
|
108
|
+
is_bot = bool(author.get("bot"))
|
|
109
|
+
is_owner = bool(self._owner_user_id and sender_id == self._owner_user_id)
|
|
110
|
+
|
|
111
|
+
raw_text = str(raw.get("content") or "")
|
|
112
|
+
user_names: dict[str, str] = {}
|
|
113
|
+
mentions: list[Mention] = []
|
|
114
|
+
seen_mention_ids: set[str] = set()
|
|
115
|
+
mentions_owner = False
|
|
116
|
+
|
|
117
|
+
for m_user in raw.get("mentions") or []:
|
|
118
|
+
if not isinstance(m_user, dict):
|
|
119
|
+
continue
|
|
120
|
+
uid = str(m_user.get("id") or "").strip()
|
|
121
|
+
if not uid:
|
|
122
|
+
continue
|
|
123
|
+
disp = str(m_user.get("global_name") or m_user.get("username") or uid).strip()
|
|
124
|
+
user_names[uid] = disp
|
|
125
|
+
if uid not in seen_mention_ids:
|
|
126
|
+
seen_mention_ids.add(uid)
|
|
127
|
+
mentions.append(Mention(id=uid, name=disp, key=f"<@{uid}>"))
|
|
128
|
+
if self._owner_user_id and uid == self._owner_user_id:
|
|
129
|
+
mentions_owner = True
|
|
130
|
+
|
|
131
|
+
for match in _MENTION_RE.finditer(raw_text):
|
|
132
|
+
uid = match.group(1)
|
|
133
|
+
if uid not in seen_mention_ids:
|
|
134
|
+
seen_mention_ids.add(uid)
|
|
135
|
+
mentions.append(Mention(id=uid, name=user_names.get(uid, uid), key=match.group(0)))
|
|
136
|
+
if self._owner_user_id and uid == self._owner_user_id:
|
|
137
|
+
mentions_owner = True
|
|
138
|
+
|
|
139
|
+
clean_text = _MENTION_RE.sub(lambda m: f"@{user_names.get(m.group(1), m.group(1))}", raw_text).strip()
|
|
140
|
+
mentions_all = bool(raw.get("mention_everyone"))
|
|
141
|
+
reply_to_id = str((raw.get("message_reference") or {}).get("message_id") or "").strip()
|
|
142
|
+
|
|
143
|
+
media_refs: list[MediaRef] = []
|
|
144
|
+
for att in raw.get("attachments") or []:
|
|
145
|
+
if not isinstance(att, dict):
|
|
146
|
+
continue
|
|
147
|
+
kind, ext = _classify_attachment(att)
|
|
148
|
+
att_id = str(att.get("id") or f"{msg_id}_att").strip()
|
|
149
|
+
media_refs.append(
|
|
150
|
+
MediaRef(
|
|
151
|
+
kind=kind,
|
|
152
|
+
key=att_id,
|
|
153
|
+
ext=ext,
|
|
154
|
+
extra={
|
|
155
|
+
"url": str(att.get("url") or att.get("proxy_url") or "").strip(),
|
|
156
|
+
"name": str(att.get("filename") or f"{att_id}.{ext}"),
|
|
157
|
+
},
|
|
158
|
+
)
|
|
159
|
+
)
|
|
160
|
+
|
|
161
|
+
msg_type = "text"
|
|
162
|
+
if not clean_text and media_refs:
|
|
163
|
+
msg_type = media_refs[0].kind
|
|
164
|
+
|
|
165
|
+
return NormalizedMessage(
|
|
166
|
+
message_id=msg_id,
|
|
167
|
+
channel_id=channel_id,
|
|
168
|
+
create_ms=create_ms,
|
|
169
|
+
create_time=_format_ts_ms(create_ms),
|
|
170
|
+
sender_id=sender_id,
|
|
171
|
+
sender_name=sender_name,
|
|
172
|
+
sender_type="bot" if is_bot else "user",
|
|
173
|
+
is_owner=is_owner,
|
|
174
|
+
is_bot=is_bot,
|
|
175
|
+
msg_type=msg_type,
|
|
176
|
+
raw_content=raw_text,
|
|
177
|
+
clean_text=clean_text,
|
|
178
|
+
reply_to_id=reply_to_id,
|
|
179
|
+
mentions=mentions,
|
|
180
|
+
mentions_owner=mentions_owner,
|
|
181
|
+
mentions_all=mentions_all,
|
|
182
|
+
media_refs=media_refs,
|
|
183
|
+
)
|
|
184
|
+
|
|
185
|
+
async def list_available_chats(self) -> list[dict[str, str]]:
|
|
186
|
+
guild_ids = [str(g).strip() for g in self.config.guild_ids if str(g).strip()]
|
|
187
|
+
if not guild_ids:
|
|
188
|
+
resp = await self._client().get(
|
|
189
|
+
f"{self._base_url}/users/@me/guilds",
|
|
190
|
+
headers=self._auth_headers(),
|
|
191
|
+
)
|
|
192
|
+
resp.raise_for_status()
|
|
193
|
+
guild_ids = [
|
|
194
|
+
str(g.get("id") or "").strip()
|
|
195
|
+
for g in (resp.json() or [])
|
|
196
|
+
if isinstance(g, dict) and str(g.get("id") or "").strip()
|
|
197
|
+
]
|
|
198
|
+
|
|
199
|
+
chats: list[dict[str, str]] = []
|
|
200
|
+
for gid in guild_ids:
|
|
201
|
+
resp = await self._client().get(
|
|
202
|
+
f"{self._base_url}/guilds/{gid}/channels",
|
|
203
|
+
headers=self._auth_headers(),
|
|
204
|
+
)
|
|
205
|
+
resp.raise_for_status()
|
|
206
|
+
for ch in resp.json() or []:
|
|
207
|
+
if not isinstance(ch, dict):
|
|
208
|
+
continue
|
|
209
|
+
if ch.get("type") not in _DISCORD_TEXT_CHANNEL_TYPES:
|
|
210
|
+
continue
|
|
211
|
+
cid = str(ch.get("id") or "").strip()
|
|
212
|
+
if not cid:
|
|
213
|
+
continue
|
|
214
|
+
raw_name = str(ch.get("name") or cid).strip()
|
|
215
|
+
chats.append(
|
|
216
|
+
{
|
|
217
|
+
"external_chat_id": cid,
|
|
218
|
+
"name": raw_name if raw_name.startswith("#") else f"#{raw_name}",
|
|
219
|
+
"chat_type": "group",
|
|
220
|
+
}
|
|
221
|
+
)
|
|
222
|
+
return chats
|
|
223
|
+
|
|
224
|
+
async def fetch_recent(self, channel: ChannelConfig, *, limit: int = 50) -> list[NormalizedMessage]:
|
|
225
|
+
resp = await self._client().get(
|
|
226
|
+
f"{self._base_url}/channels/{channel.external_chat_id}/messages",
|
|
227
|
+
params={"limit": min(max(int(limit), 1), 100)},
|
|
228
|
+
headers=self._auth_headers(),
|
|
229
|
+
)
|
|
230
|
+
resp.raise_for_status()
|
|
231
|
+
items = resp.json() or []
|
|
232
|
+
ordered = sorted(
|
|
233
|
+
[m for m in items if isinstance(m, dict) and str(m.get("id") or "").strip()],
|
|
234
|
+
key=lambda m: _snowflake_key(str(m.get("id") or "")),
|
|
235
|
+
)
|
|
236
|
+
return [self._normalize_message(channel.id, raw) for raw in ordered]
|
|
237
|
+
|
|
238
|
+
async def fetch_by_ids(self, channel: ChannelConfig, message_ids: list[str]) -> list[NormalizedMessage]:
|
|
239
|
+
out: list[NormalizedMessage] = []
|
|
240
|
+
for mid in message_ids:
|
|
241
|
+
clean_id = str(mid or "").strip()
|
|
242
|
+
if not clean_id:
|
|
243
|
+
continue
|
|
244
|
+
resp = await self._client().get(
|
|
245
|
+
f"{self._base_url}/channels/{channel.external_chat_id}/messages/{clean_id}",
|
|
246
|
+
headers=self._auth_headers(),
|
|
247
|
+
)
|
|
248
|
+
if resp.status_code == 404:
|
|
249
|
+
continue
|
|
250
|
+
resp.raise_for_status()
|
|
251
|
+
raw = resp.json()
|
|
252
|
+
if isinstance(raw, dict):
|
|
253
|
+
out.append(self._normalize_message(channel.id, raw))
|
|
254
|
+
return out
|
|
255
|
+
|
|
256
|
+
async def download_media(
|
|
257
|
+
self,
|
|
258
|
+
channel: ChannelConfig,
|
|
259
|
+
message: NormalizedMessage,
|
|
260
|
+
dest_dir: Path,
|
|
261
|
+
) -> list[MediaArtifact]:
|
|
262
|
+
del channel
|
|
263
|
+
if not message.media_refs:
|
|
264
|
+
return []
|
|
265
|
+
target_dir = Path(dest_dir).expanduser()
|
|
266
|
+
target_dir.mkdir(parents=True, exist_ok=True)
|
|
267
|
+
artifacts: list[MediaArtifact] = []
|
|
268
|
+
|
|
269
|
+
for ref in message.media_refs:
|
|
270
|
+
url = str((ref.extra or {}).get("url") or "").strip()
|
|
271
|
+
if not url:
|
|
272
|
+
artifacts.append(
|
|
273
|
+
MediaArtifact(kind=ref.kind, key=ref.key, error="Missing Discord attachment URL")
|
|
274
|
+
)
|
|
275
|
+
continue
|
|
276
|
+
fname = _sanitize_filename(
|
|
277
|
+
str((ref.extra or {}).get("name") or ""),
|
|
278
|
+
fallback=ref.key,
|
|
279
|
+
default_ext=ref.ext or "bin",
|
|
280
|
+
)
|
|
281
|
+
dest_path = target_dir / f"{_SAFE_STEM_RE.sub('_', ref.key)}_{fname}"
|
|
282
|
+
try:
|
|
283
|
+
resp = await self._client().get(url, follow_redirects=True)
|
|
284
|
+
resp.raise_for_status()
|
|
285
|
+
dest_path.write_bytes(resp.content)
|
|
286
|
+
artifacts.append(MediaArtifact(kind=ref.kind, key=ref.key, path=str(dest_path)))
|
|
287
|
+
except Exception as exc:
|
|
288
|
+
artifacts.append(MediaArtifact(kind=ref.kind, key=ref.key, error=str(exc)))
|
|
289
|
+
return artifacts
|