wechatbot-sdk 0.3.0__tar.gz → 0.4.0__tar.gz

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.
@@ -1,6 +1,6 @@
1
- Metadata-Version: 2.4
1
+ Metadata-Version: 2.5
2
2
  Name: wechatbot-sdk
3
- Version: 0.3.0
3
+ Version: 0.4.0
4
4
  Summary: WeChat iLink Bot SDK for Python — async, typed, production-grade
5
5
  License: MIT
6
6
  Requires-Python: >=3.9
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "wechatbot-sdk"
3
- version = "0.3.0"
3
+ version = "0.4.0"
4
4
  description = "WeChat iLink Bot SDK for Python — async, typed, production-grade"
5
5
  readme = "README.md"
6
6
  license = { text = "MIT" }
@@ -0,0 +1,60 @@
1
+ """Tests for the upstream protocol fixes (channel_version, PIN status, captions)."""
2
+
3
+ import asyncio
4
+ from types import SimpleNamespace
5
+
6
+ from wechatbot.auth import status_needs_verify_code
7
+ from wechatbot.client import WeChatBot
8
+ from wechatbot.errors import ApiError
9
+ from wechatbot.protocol import (
10
+ CHANNEL_VERSION,
11
+ DEFAULT_BOT_AGENT,
12
+ ILINK_APP_CLIENT_VERSION,
13
+ SDK_VERSION,
14
+ UPSTREAM_PROTOCOL_VERSION,
15
+ )
16
+
17
+
18
+ def test_channel_version_starts_with_upstream_version():
19
+ assert CHANNEL_VERSION == f"{UPSTREAM_PROTOCOL_VERSION}/wechatbot-python-{SDK_VERSION}"
20
+
21
+
22
+ def test_client_version_header_uses_upstream_version():
23
+ major, minor, patch = (int(p) for p in UPSTREAM_PROTOCOL_VERSION.split("."))
24
+ assert ILINK_APP_CLIENT_VERSION == str((major << 16) | (minor << 8) | patch)
25
+
26
+
27
+ def test_default_bot_agent_uses_sdk_version():
28
+ assert DEFAULT_BOT_AGENT == f"WeChatBot/{SDK_VERSION}"
29
+
30
+
31
+ def test_status_needs_verify_code():
32
+ assert status_needs_verify_code("need_verifycode")
33
+ assert status_needs_verify_code("confirmed_but_need_verifycode")
34
+ assert not status_needs_verify_code("confirmed")
35
+ assert not status_needs_verify_code("verify_code_blocked")
36
+
37
+
38
+ def test_send_rejected():
39
+ assert ApiError("x", errcode=-2).is_send_rejected
40
+ assert not ApiError("x", errcode=-14).is_send_rejected
41
+
42
+
43
+ def test_caption_is_sent_as_its_own_message():
44
+ bot = WeChatBot()
45
+ bot._credentials = SimpleNamespace(base_url="https://api.example", token="t")
46
+ sent: list[list[int]] = []
47
+
48
+ async def fake_upload(creds, data, user_id, media_type):
49
+ return SimpleNamespace()
50
+
51
+ async def fake_send(base_url, token, msg):
52
+ sent.append([item["type"] for item in msg["item_list"]])
53
+ return {"ret": 0}
54
+
55
+ bot._cdn_upload = fake_upload
56
+ bot._api.send_message = fake_send
57
+ asyncio.run(
58
+ bot._send_media_buffer("u", "ctx", b"png", 1, lambda r: {"type": 2}, caption="look")
59
+ )
60
+ assert sent == [[1], [2]]
@@ -0,0 +1,65 @@
1
+ """Tests for ID-only quotes, the message cache, and send results."""
2
+
3
+ import asyncio
4
+ import json
5
+ from types import SimpleNamespace
6
+
7
+ from wechatbot.client import WeChatBot
8
+ from wechatbot.message_cache import CachedMessage, MessageCache, resolve_partial_quote
9
+
10
+
11
+ def _id_only_quote(quoted_id: str) -> dict:
12
+ # Shape from issue #112.
13
+ return json.loads(
14
+ '{"message_id": 9000000000000000001, "from_user_id": "u@im.wechat",'
15
+ ' "to_user_id": "b@im.bot", "create_time_ms": 1700000100000,'
16
+ ' "message_type": 1, "message_state": 2, "context_token": "ctx",'
17
+ ' "item_list": [{"type": 1, "msg_id": "v1:1",'
18
+ ' "ref_msg": {"message_item": {"type": 0, "msg_id": "%s"}},'
19
+ ' "text_item": {"text": "quote"}}]}' % quoted_id
20
+ )
21
+
22
+
23
+ def test_ids_are_exact_strings():
24
+ msg = WeChatBot()._parse_message(_id_only_quote("9000000000000000000"))
25
+ assert msg.message_id == "9000000000000000001"
26
+ assert msg.quoted_message.message_id == "9000000000000000000"
27
+ assert msg.quoted_message.text is None
28
+ assert msg.quoted_message.type is None
29
+
30
+
31
+ def test_svr_id_wins():
32
+ raw = _id_only_quote("1")
33
+ raw["item_list"][0]["ref_msg"]["svr_id"] = 18446744073709551615
34
+ msg = WeChatBot()._parse_message(raw)
35
+ assert msg.quoted_message.message_id == "18446744073709551615"
36
+
37
+
38
+ def test_cache_fills_quote_and_evicts():
39
+ cache = MessageCache(2)
40
+ cache.put("9000000000000000000", CachedMessage("original", "text", True))
41
+ msg = WeChatBot()._parse_message(_id_only_quote("9000000000000000000"))
42
+ cache.resolve(msg.quoted_message)
43
+ assert msg.quoted_message.text == "original"
44
+ assert msg.quoted_message.from_bot is True
45
+ cache.put("a", CachedMessage("a", "text", False))
46
+ cache.put("b", CachedMessage("b", "text", False))
47
+ assert cache.get("9000000000000000000") is None
48
+
49
+
50
+ def test_partial_quote():
51
+ partial = {"start": "two", "end": "four", "startindex": 1, "endindex": 0}
52
+ assert resolve_partial_quote("one two three two four", partial) == "two four"
53
+
54
+
55
+ def test_send_returns_message_id_and_caches_text():
56
+ bot = WeChatBot()
57
+ bot._credentials = SimpleNamespace(base_url="https://api.example", token="t")
58
+
59
+ async def fake_send(base_url, token, msg):
60
+ return {"ret": 0, "message_id": 18446744073709551615}
61
+
62
+ bot._api.send_message = fake_send
63
+ result = asyncio.run(bot._send_content("u", "ctx", "answer"))
64
+ assert result.message_id == "18446744073709551615"
65
+ assert bot._message_cache.get("18446744073709551615").text == "answer"
@@ -0,0 +1,9 @@
1
+ from wechatbot import protect_underscores
2
+
3
+
4
+ def test_protect_underscores():
5
+ assert protect_underscores("EPS_manuscript_CN.pdf") == "EPS_manuscript_CN.pdf"
6
+ assert (
7
+ protect_underscores("run `my_func` then ```\na_b\n``` ok_1")
8
+ == "run `my_func` then ```\na_b\n``` ok_1"
9
+ )
@@ -0,0 +1,35 @@
1
+ """Route tag and verify_pin (openclaw-weixin 3.0 protocol)."""
2
+
3
+ from wechatbot.protocol import (
4
+ VERIFY_PIN_BUSINESS_DATA,
5
+ ILinkApi,
6
+ _common_headers,
7
+ cradle_hostname,
8
+ post_headers,
9
+ )
10
+
11
+
12
+ def test_cradle_hostname():
13
+ assert cradle_hostname("10086") == "g10086"
14
+ assert cradle_hostname("g10086") == "g10086"
15
+ assert cradle_hostname(" ") is None
16
+
17
+
18
+ def test_route_appends_cradle_hostname():
19
+ api = ILinkApi(route_tag="10086")
20
+ assert api._route("https://a/ilink/bot/getupdates") == (
21
+ "https://a/ilink/bot/getupdates?_cradle_hostname=g10086"
22
+ )
23
+ assert api._route("https://a/x?bot_type=3").endswith("?bot_type=3&_cradle_hostname=g10086")
24
+ assert ILinkApi()._route("https://a/x") == "https://a/x"
25
+
26
+
27
+ def test_headers():
28
+ assert _common_headers("10086")["SKRouteTag"] == "10086"
29
+ assert "SKRouteTag" not in _common_headers()
30
+ qr = post_headers(None, None)
31
+ assert qr["AuthorizationType"] == "ilink_bot_token" and "Authorization" not in qr
32
+
33
+
34
+ def test_verify_pin_business_data():
35
+ assert VERIFY_PIN_BUSINESS_DATA == "eyJ2ZXJpZnlfcGluIjoxfQ=="
@@ -8,12 +8,14 @@ from .types import (
8
8
  FileContent,
9
9
  VideoContent,
10
10
  QuotedMessage,
11
+ SendResult,
11
12
  ContentType,
12
13
  DownloadedMedia,
13
14
  UploadResult,
14
15
  MediaType,
15
16
  )
16
17
  from .client import SendContent, WeChatBot
18
+ from .text import protect_underscores
17
19
  from .errors import (
18
20
  WeChatBotError,
19
21
  ApiError,
@@ -39,6 +41,7 @@ __all__ = [
39
41
  "FileContent",
40
42
  "VideoContent",
41
43
  "QuotedMessage",
44
+ "SendResult",
42
45
  "ContentType",
43
46
  "DownloadedMedia",
44
47
  "UploadResult",
@@ -53,4 +56,5 @@ __all__ = [
53
56
  "generate_aes_key",
54
57
  "decode_aes_key",
55
58
  "encrypted_size",
59
+ "protect_underscores",
56
60
  ]
@@ -57,8 +57,20 @@ async def clear_credentials(path: Path | None = None) -> None:
57
57
  target.unlink(missing_ok=True)
58
58
 
59
59
 
60
+ def status_needs_verify_code(status: str) -> bool:
61
+ """Any status containing need_verifycode asks for the phone's digits
62
+ (need_verifycode, confirmed_but_need_verifycode, ...), as upstream does."""
63
+ return "need_verifycode" in status
64
+
65
+
60
66
  async def _read_verify_code(is_retry: bool) -> str:
61
67
  """Default pairing-code prompt: read a line from stdin."""
68
+ if not sys.stdin.isatty():
69
+ raise AuthError(
70
+ "WeChat asked for the pairing code shown on the phone, but no "
71
+ "on_verify_code callback was given and stdin is not a terminal. "
72
+ "Pass on_verify_code to supply the code."
73
+ )
62
74
  prompt = (
63
75
  "Code mismatch — enter the pairing code shown in WeChat again: "
64
76
  if is_retry
@@ -112,7 +124,7 @@ async def login(
112
124
  status = await api.poll_qr_status(
113
125
  current_poll_base_url, qr["qrcode"], pending_verify_code
114
126
  )
115
- current = status["status"]
127
+ current = status.get("status", "wait")
116
128
 
117
129
  if current != last_status:
118
130
  last_status = current
@@ -151,7 +163,7 @@ async def login(
151
163
  return creds
152
164
 
153
165
  # Pair-code challenge: ask the user for the digits shown in WeChat
154
- if current == "need_verifycode":
166
+ if status_needs_verify_code(current):
155
167
  is_retry = pending_verify_code is not None
156
168
  if on_verify_code:
157
169
  pending_verify_code = on_verify_code(is_retry)
@@ -23,6 +23,7 @@ from .crypto import (
23
23
  generate_aes_key,
24
24
  )
25
25
  from .errors import ApiError, MediaError, NoContextError
26
+ from .message_cache import CachedMessage, MessageCache
26
27
  from .protocol import CDN_BASE_URL, DEFAULT_BASE_URL, ILinkApi
27
28
  from .types import (
28
29
  CDNMedia,
@@ -35,6 +36,7 @@ from .types import (
35
36
  MessageItemType,
36
37
  MessageType,
37
38
  QuotedMessage,
39
+ SendResult,
38
40
  UploadResult,
39
41
  VideoContent,
40
42
  VoiceContent,
@@ -79,6 +81,9 @@ class WeChatBot:
79
81
  on_error: Callable[[Exception], None] | None = None,
80
82
  on_verify_code: Callable[[bool], str] | None = None,
81
83
  bot_agent: str | None = None,
84
+ message_cache_size: int = 1000,
85
+ route_tag: str | None = None,
86
+ verify_pin: bool = False,
82
87
  ) -> None:
83
88
  self._base_url = base_url or DEFAULT_BASE_URL
84
89
  self._cred_path = Path(cred_path) if cred_path else None
@@ -88,7 +93,11 @@ class WeChatBot:
88
93
  self._on_error = on_error
89
94
  self._on_verify_code = on_verify_code
90
95
 
91
- self._api = ILinkApi(bot_agent=bot_agent)
96
+ # route_tag: deployment tag WeChat may give you (SKRouteTag header and
97
+ # _cradle_hostname). verify_pin: require the phone PIN when binding.
98
+ self._api = ILinkApi(bot_agent=bot_agent, route_tag=route_tag, verify_pin=verify_pin)
99
+ # Recent messages by server ID, to fill ID-only quotes. 0 disables.
100
+ self._message_cache = MessageCache(message_cache_size)
92
101
  self._credentials: Credentials | None = None
93
102
  self._context_tokens: dict[str, str] = {}
94
103
  self._handlers: list[MessageHandler] = []
@@ -126,19 +135,20 @@ class WeChatBot:
126
135
 
127
136
  # ── Sending ───────────────────────────────────────────────────────
128
137
 
129
- async def reply(self, msg: IncomingMessage, text: str) -> None:
138
+ async def reply(self, msg: IncomingMessage, text: str) -> SendResult:
130
139
  """Reply to an incoming message with text.
131
140
 
132
141
  For media (images, files, video), use :meth:`reply_media`.
133
142
  """
134
143
  self._context_tokens[msg.user_id] = msg._context_token
135
- await self._send_content(msg.user_id, msg._context_token, text)
144
+ result = await self._send_content(msg.user_id, msg._context_token, text)
136
145
  try:
137
146
  await self.stop_typing(msg.user_id)
138
147
  except Exception:
139
148
  pass
149
+ return result
140
150
 
141
- async def reply_media(self, msg: IncomingMessage, content: SendContent) -> None:
151
+ async def reply_media(self, msg: IncomingMessage, content: SendContent) -> SendResult:
142
152
  """Reply to an incoming message with media content.
143
153
 
144
154
  Accepts text string or media dict::
@@ -148,13 +158,14 @@ class WeChatBot:
148
158
  await bot.reply_media(msg, {"video": mp4_bytes, "caption": "Check this"})
149
159
  """
150
160
  self._context_tokens[msg.user_id] = msg._context_token
151
- await self._send_content(msg.user_id, msg._context_token, content)
161
+ result = await self._send_content(msg.user_id, msg._context_token, content)
152
162
  try:
153
163
  await self.stop_typing(msg.user_id)
154
164
  except Exception:
155
165
  pass
166
+ return result
156
167
 
157
- async def send(self, user_id: str, text: str) -> None:
168
+ async def send(self, user_id: str, text: str) -> SendResult:
158
169
  """Send a text message to a user (requires prior context_token).
159
170
 
160
171
  For media (images, files, video), use :meth:`send_media`.
@@ -162,14 +173,14 @@ class WeChatBot:
162
173
  ct = self._context_tokens.get(user_id)
163
174
  if not ct:
164
175
  raise NoContextError(user_id)
165
- await self._send_content(user_id, ct, text)
176
+ return await self._send_content(user_id, ct, text)
166
177
 
167
- async def send_media(self, user_id: str, content: SendContent) -> None:
178
+ async def send_media(self, user_id: str, content: SendContent) -> SendResult:
168
179
  """Send media content to a user (requires prior context_token)."""
169
180
  ct = self._context_tokens.get(user_id)
170
181
  if not ct:
171
182
  raise NoContextError(user_id)
172
- await self._send_content(user_id, ct, content)
183
+ return await self._send_content(user_id, ct, content)
173
184
 
174
185
  # ── Download ───────────────────────────────────────────────────
175
186
 
@@ -282,6 +293,11 @@ class WeChatBot:
282
293
  self._remember_context(raw)
283
294
  msg = self._parse_message(raw)
284
295
  if msg:
296
+ # Fill an ID-only quote, then remember this message
297
+ self._message_cache.resolve(msg.quoted_message)
298
+ self._message_cache.put(
299
+ msg.message_id, CachedMessage(msg.text, msg.type, False)
300
+ )
285
301
  await self._dispatch(msg)
286
302
 
287
303
  except ApiError as e:
@@ -338,20 +354,20 @@ class WeChatBot:
338
354
 
339
355
  async def _send_content(
340
356
  self, user_id: str, context_token: str, content: SendContent,
341
- ) -> None:
357
+ ) -> SendResult:
342
358
  # String shorthand → text
343
359
  if isinstance(content, str):
344
- await self._send_text(user_id, content, context_token)
345
- return
360
+ return SendResult(message_id=await self._send_text(user_id, content, context_token))
346
361
 
347
362
  # {"text": ...}
348
363
  if "text" in content:
349
- await self._send_text(user_id, content["text"], context_token)
350
- return
364
+ return SendResult(
365
+ message_id=await self._send_text(user_id, content["text"], context_token)
366
+ )
351
367
 
352
368
  # {"image": bytes}
353
369
  if "image" in content:
354
- await self._send_media_buffer(
370
+ return await self._send_media_buffer(
355
371
  user_id, context_token, content["image"],
356
372
  MediaType.IMAGE,
357
373
  lambda result: {"type": int(MessageItemType.IMAGE), "image_item": {
@@ -360,11 +376,10 @@ class WeChatBot:
360
376
  }},
361
377
  content.get("caption"),
362
378
  )
363
- return
364
379
 
365
380
  # {"video": bytes}
366
381
  if "video" in content:
367
- await self._send_media_buffer(
382
+ return await self._send_media_buffer(
368
383
  user_id, context_token, content["video"],
369
384
  MediaType.VIDEO,
370
385
  lambda result: {"type": int(MessageItemType.VIDEO), "video_item": {
@@ -373,7 +388,6 @@ class WeChatBot:
373
388
  }},
374
389
  content.get("caption"),
375
390
  )
376
- return
377
391
 
378
392
  # {"file": bytes, "file_name": str}
379
393
  if "file" in content:
@@ -381,23 +395,18 @@ class WeChatBot:
381
395
  category = _categorize_by_extension(file_name)
382
396
 
383
397
  if category == "image":
384
- await self._send_content(user_id, context_token, {
398
+ return await self._send_content(user_id, context_token, {
385
399
  "image": content["file"], "caption": content.get("caption"),
386
400
  })
387
- return
388
401
 
389
402
  if category == "video":
390
- await self._send_content(user_id, context_token, {
403
+ return await self._send_content(user_id, context_token, {
391
404
  "video": content["file"], "caption": content.get("caption"),
392
405
  })
393
- return
394
406
 
395
407
  # Generic file
396
- caption = content.get("caption")
397
- if caption:
398
- await self._send_text(user_id, caption, context_token)
399
408
  raw_data = content["file"]
400
- await self._send_media_buffer(
409
+ return await self._send_media_buffer(
401
410
  user_id, context_token, raw_data,
402
411
  MediaType.FILE,
403
412
  lambda result: {"type": int(MessageItemType.FILE), "file_item": {
@@ -405,8 +414,8 @@ class WeChatBot:
405
414
  "file_name": file_name,
406
415
  "len": str(len(raw_data)),
407
416
  }},
417
+ content.get("caption"),
408
418
  )
409
- return
410
419
 
411
420
  raise ValueError(f"Unsupported content type: {content!r}")
412
421
 
@@ -418,16 +427,21 @@ class WeChatBot:
418
427
  media_type: int,
419
428
  build_item: Callable[[UploadResult], dict[str, Any]],
420
429
  caption: str | None = None,
421
- ) -> None:
430
+ ) -> SendResult:
422
431
  creds = self._require_creds()
423
432
  result = await self._cdn_upload(creds, data, user_id, media_type)
424
- items: list[dict[str, Any]] = []
433
+ # iLink rejects a text item and a media item in one item_list
434
+ # ("invalid arguments"), so the caption goes first as its own message.
435
+ caption_id = None
425
436
  if caption:
426
- items.append({"type": int(MessageItemType.TEXT), "text_item": {"text": caption}})
427
- items.append(build_item(result))
428
- msg = self._api.build_media_message(user_id, context_token, items)
429
- await self._api.send_message(creds.base_url, creds.token, msg)
437
+ caption_id = await self._send_text(user_id, caption, context_token)
438
+ msg = self._api.build_media_message(user_id, context_token, [build_item(result)])
439
+ resp = await self._api.send_message(creds.base_url, creds.token, msg)
440
+ message_id = _id_str(resp.get("message_id"))
441
+ kind = _MEDIA_CONTENT_TYPE.get(media_type, "file")
442
+ self._message_cache.put(message_id, CachedMessage(f"[{kind}]", kind, True))
430
443
  self._log(f"Sent media type={media_type} to {user_id} ({len(data)} bytes)")
444
+ return SendResult(message_id=message_id, caption_message_id=caption_id)
431
445
 
432
446
  # ── Internal: CDN download ─────────────────────────────────────
433
447
 
@@ -513,13 +527,18 @@ class WeChatBot:
513
527
 
514
528
  # ── Internal: text ─────────────────────────────────────────────
515
529
 
516
- async def _send_text(self, user_id: str, text: str, context_token: str) -> None:
530
+ async def _send_text(self, user_id: str, text: str, context_token: str) -> str | None:
531
+ """Send text; return the server ID of the last chunk and cache the text."""
517
532
  if not text:
518
533
  raise ValueError("Message text cannot be empty")
519
534
  creds = self._require_creds()
535
+ message_id = None
520
536
  for chunk in _chunk_text(text, 4000):
521
537
  msg = self._api.build_text_message(user_id, context_token, chunk)
522
- await self._api.send_message(creds.base_url, creds.token, msg)
538
+ resp = await self._api.send_message(creds.base_url, creds.token, msg)
539
+ message_id = _id_str(resp.get("message_id"))
540
+ self._message_cache.put(message_id, CachedMessage(text, "text", True))
541
+ return message_id
523
542
 
524
543
  def _remember_context(self, raw: dict[str, Any]) -> None:
525
544
  mt = raw.get("message_type")
@@ -573,9 +592,7 @@ class WeChatBot:
573
592
  duration_ms=vi.get("play_length"),
574
593
  ))
575
594
  if item.get("ref_msg"):
576
- ref = item["ref_msg"]
577
- qt = ref.get("message_item", {}).get("text_item", {}).get("text")
578
- quoted = QuotedMessage(title=ref.get("title"), text=qt)
595
+ quoted = _parse_ref_message(item["ref_msg"])
579
596
 
580
597
  return IncomingMessage(
581
598
  user_id=raw["from_user_id"],
@@ -587,6 +604,7 @@ class WeChatBot:
587
604
  images=images, voices=voices, files=files, videos=videos,
588
605
  quoted_message=quoted, raw=raw,
589
606
  _context_token=raw.get("context_token", ""),
607
+ message_id=_id_str(raw.get("message_id")),
590
608
  )
591
609
 
592
610
  async def _dispatch(self, msg: IncomingMessage) -> None:
@@ -612,6 +630,34 @@ class WeChatBot:
612
630
  print(f"[wechatbot] {msg}", file=sys.stderr)
613
631
 
614
632
 
633
+ _MEDIA_CONTENT_TYPE = {
634
+ int(MediaType.IMAGE): "image",
635
+ int(MediaType.VIDEO): "video",
636
+ int(MediaType.FILE): "file",
637
+ int(MediaType.VOICE): "voice",
638
+ }
639
+
640
+
641
+ def _id_str(value: Any) -> str | None:
642
+ """uint64 IDs arrive as JSON numbers or strings; expose them as strings."""
643
+ if value is None or value == "":
644
+ return None
645
+ return str(value).strip() or None
646
+
647
+
648
+ def _parse_ref_message(ref: dict[str, Any]) -> QuotedMessage:
649
+ item = ref.get("message_item") or {}
650
+ # type 0 is an empty placeholder item (ID-only quote): leave type unset.
651
+ kind = _detect_type([item]) if item.get("type") else None
652
+ return QuotedMessage(
653
+ title=ref.get("title"),
654
+ text=(item.get("text_item") or {}).get("text"),
655
+ type=kind,
656
+ message_id=_id_str(ref.get("svr_id")) or _id_str(item.get("msg_id")),
657
+ partial_text=ref.get("partial_text"),
658
+ )
659
+
660
+
615
661
  def _detect_type(items: list[dict[str, Any]]) -> str:
616
662
  if not items:
617
663
  return "text"
@@ -29,6 +29,12 @@ class ApiError(WeChatBotError):
29
29
  def is_session_expired(self) -> bool:
30
30
  return self.errcode == -14
31
31
 
32
+ @property
33
+ def is_send_rejected(self) -> bool:
34
+ """ret=-2 from sendmessage: no user message in 24 h, too many bot
35
+ messages since the user's last message, or a malformed payload."""
36
+ return self.errcode == -2
37
+
32
38
 
33
39
  class AuthError(WeChatBotError):
34
40
  """Authentication errors (QR expired, login failed, etc.)."""
@@ -0,0 +1,111 @@
1
+ """In-memory cache of recent messages, used to fill ID-only quotes."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ from collections import OrderedDict
7
+ from dataclasses import dataclass
8
+ from typing import Any
9
+
10
+ from .types import ContentType, QuotedMessage
11
+
12
+
13
+ @dataclass
14
+ class CachedMessage:
15
+ text: str
16
+ type: ContentType
17
+ from_bot: bool
18
+
19
+
20
+ class MessageCache:
21
+ """Recent messages keyed by server message ID; oldest evicted first.
22
+
23
+ Newer WeChat clients send only the ID of a quoted message
24
+ (``ref_msg.svr_id`` or ``ref_msg.message_item.msg_id``). The SDK keeps the
25
+ messages it receives and sends here so it can fill ``quoted_message.text``.
26
+ It does not survive a restart.
27
+ """
28
+
29
+ def __init__(self, max_entries: int) -> None:
30
+ self._max = max_entries
31
+ self._entries: OrderedDict[str, CachedMessage] = OrderedDict()
32
+
33
+ def get(self, message_id: str) -> CachedMessage | None:
34
+ return self._entries.get(message_id)
35
+
36
+ def put(self, message_id: str | None, message: CachedMessage) -> None:
37
+ if not message_id or self._max <= 0:
38
+ return
39
+ self._entries.pop(message_id, None)
40
+ self._entries[message_id] = message
41
+ while len(self._entries) > self._max:
42
+ self._entries.popitem(last=False)
43
+
44
+ def resolve(self, quoted: QuotedMessage | None) -> QuotedMessage | None:
45
+ """Fill a quoted message's text and type from the cache."""
46
+ if quoted is None or not quoted.message_id:
47
+ return quoted
48
+ hit = self._entries.get(quoted.message_id)
49
+ if hit is None:
50
+ return quoted
51
+ quoted.from_bot = hit.from_bot
52
+ if quoted.type is None:
53
+ quoted.type = hit.type
54
+ if not quoted.text:
55
+ part = (
56
+ resolve_partial_quote(hit.text, quoted.partial_text)
57
+ if quoted.partial_text
58
+ else None
59
+ )
60
+ quoted.text = part if part is not None else hit.text
61
+ return quoted
62
+
63
+
64
+ def _nth_index(text: str, value: str, occurrence: int, start: int = 0) -> int:
65
+ if not value or not isinstance(occurrence, int) or occurrence < 0:
66
+ return -1
67
+ position = start
68
+ for current in range(occurrence + 1):
69
+ position = text.find(value, position)
70
+ if position < 0:
71
+ return -1
72
+ if current < occurrence:
73
+ position += len(value)
74
+ return position
75
+
76
+
77
+ def _candidate(full: str, partial: dict[str, Any], relative: bool) -> str | None:
78
+ start_s, end_s = partial.get("start", ""), partial.get("end", "")
79
+ start = _nth_index(full, start_s, partial.get("startindex", 0))
80
+ if start < 0:
81
+ return None
82
+ end = (
83
+ _nth_index(full, end_s, partial.get("endindex", 0), start + len(start_s))
84
+ if relative
85
+ else _nth_index(full, end_s, partial.get("endindex", 0))
86
+ )
87
+ if end < start:
88
+ return None
89
+ return full[start : end + len(end_s)]
90
+
91
+
92
+ def resolve_partial_quote(full_text: str, partial: dict[str, Any]) -> str | None:
93
+ """Cut the quoted part out of the full text (``ref_msg.partial_text``).
94
+
95
+ ``endindex`` is seen both as a global and a relative occurrence count;
96
+ ``quotemd5``, when present, picks the right one. Ported from openclaw-weixin.
97
+ """
98
+ if not full_text or not partial.get("start") or not partial.get("end"):
99
+ return None
100
+ candidates: list[str] = []
101
+ for relative in (False, True):
102
+ c = _candidate(full_text, partial, relative)
103
+ if c and c not in candidates:
104
+ candidates.append(c)
105
+ md5 = (partial.get("quotemd5") or "").lower()
106
+ if not md5:
107
+ return candidates[0] if candidates else None
108
+ for c in candidates:
109
+ if hashlib.md5(c.encode("utf-8")).hexdigest() == md5:
110
+ return c
111
+ return None
@@ -2,6 +2,7 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
+ import asyncio
5
6
  import base64
6
7
  import json
7
8
  import os
@@ -20,19 +21,40 @@ from .types import MediaType, MessageItemType, MessageState, MessageType
20
21
  DEFAULT_BASE_URL = "https://ilinkai.weixin.qq.com"
21
22
  CDN_BASE_URL = "https://novac2c.cdn.weixin.qq.com/c2c"
22
23
 
23
- # Read version from package metadata; fall back to pyproject.toml parsing
24
+ # This SDK's own package version.
24
25
  try:
25
- CHANNEL_VERSION = pkg_version("wechatbot-sdk")
26
+ SDK_VERSION = pkg_version("wechatbot-sdk")
26
27
  except Exception:
27
- CHANNEL_VERSION = "0.1.0"
28
+ SDK_VERSION = "0.0.0"
29
+
30
+ # The openclaw-weixin release whose wire protocol this SDK implements. The
31
+ # server reads the first three numbers of channel_version as the openclaw-weixin
32
+ # version, so they must be this value, not the SDK version. Bump it after each
33
+ # upstream sync (see docs/protocol.md).
34
+ UPSTREAM_PROTOCOL_VERSION = "3.0.0"
35
+
36
+ # base_info.channel_version: upstream version first, our version as a suffix
37
+ # that the server ignores, e.g. "3.0.0/wechatbot-python-0.4.0".
38
+ CHANNEL_VERSION = f"{UPSTREAM_PROTOCOL_VERSION}/wechatbot-python-{SDK_VERSION}"
39
+
40
+ # Client timeout for one get_qrcode_status long poll (the server holds ~35 s).
41
+ QR_STATUS_TIMEOUT_SECS = 40
42
+
43
+ # Explanation appended to sendmessage ret=-2 errors.
44
+ SEND_REJECTED_HINT = (
45
+ "WeChat rejected the send (ret=-2). Usual causes: the user has not messaged "
46
+ "the bot in the last 24 hours, or the bot sent too many messages since the "
47
+ "user's last message. The user must message the bot again. A malformed "
48
+ "item_list also returns ret=-2."
49
+ )
28
50
 
29
51
  # iLink-App-Id header value
30
52
  ILINK_APP_ID = "bot"
31
53
 
32
54
 
33
55
  def _build_client_version() -> str:
34
- """Encode version as 0x00MMNNPP uint32 string."""
35
- parts = CHANNEL_VERSION.split(".")
56
+ """Encode the upstream version as a 0x00MMNNPP uint32 string."""
57
+ parts = UPSTREAM_PROTOCOL_VERSION.split(".")
36
58
  try:
37
59
  major = int(parts[0]) & 0xFF if len(parts) > 0 else 0
38
60
  minor = int(parts[1]) & 0xFF if len(parts) > 1 else 0
@@ -50,26 +72,49 @@ def random_wechat_uin() -> str:
50
72
  return base64.b64encode(str(val).encode("utf-8")).decode("ascii")
51
73
 
52
74
 
53
- def _common_headers() -> dict[str, str]:
75
+ def _common_headers(route_tag: str | None = None) -> dict[str, str]:
54
76
  """Headers included in both GET and POST requests."""
55
- return {
77
+ headers = {
56
78
  "iLink-App-Id": ILINK_APP_ID,
57
79
  "iLink-App-ClientVersion": ILINK_APP_CLIENT_VERSION,
58
80
  }
81
+ if route_tag:
82
+ headers["SKRouteTag"] = route_tag
83
+ return headers
59
84
 
60
85
 
61
- def auth_headers(token: str) -> dict[str, str]:
62
- return {
86
+ def post_headers(token: str | None = None, route_tag: str | None = None) -> dict[str, str]:
87
+ """JSON POST headers. token is None for the QR-code request."""
88
+ headers = {
63
89
  "Content-Type": "application/json",
64
90
  "AuthorizationType": "ilink_bot_token",
65
- "Authorization": f"Bearer {token}",
66
91
  "X-WECHAT-UIN": random_wechat_uin(),
67
- **_common_headers(),
92
+ **_common_headers(route_tag),
68
93
  }
94
+ if token:
95
+ headers["Authorization"] = f"Bearer {token}"
96
+ return headers
97
+
98
+
99
+ def auth_headers(token: str, route_tag: str | None = None) -> dict[str, str]:
100
+ return post_headers(token, route_tag)
101
+
102
+
103
+ def cradle_hostname(route_tag: str | None) -> str | None:
104
+ """_cradle_hostname for a route tag: "10086" -> "g10086"; a value that
105
+ already starts with "g" is kept."""
106
+ value = (route_tag or "").strip()
107
+ if not value:
108
+ return None
109
+ return value if value.startswith("g") else f"g{value}"
110
+
111
+
112
+ #: {"verify_pin":1} as UTF-8 then standard base64, for bot_spam_business_data.
113
+ VERIFY_PIN_BUSINESS_DATA = base64.b64encode(b'{"verify_pin":1}').decode("ascii")
69
114
 
70
115
 
71
116
  # Default bot_agent when none is configured or the configured value is invalid.
72
- DEFAULT_BOT_AGENT = f"WeChatBot/{CHANNEL_VERSION}"
117
+ DEFAULT_BOT_AGENT = f"WeChatBot/{SDK_VERSION}"
73
118
 
74
119
  # Maximum length (bytes) of the sanitized bot_agent string.
75
120
  _BOT_AGENT_MAX_LEN = 256
@@ -122,9 +167,26 @@ async def _parse_response(resp: aiohttp.ClientResponse, label: str) -> dict[str,
122
167
  class ILinkApi:
123
168
  """Low-level iLink API client. Each method maps 1:1 to an endpoint."""
124
169
 
125
- def __init__(self, *, bot_agent: str | None = None) -> None:
170
+ def __init__(
171
+ self,
172
+ *,
173
+ bot_agent: str | None = None,
174
+ route_tag: str | None = None,
175
+ verify_pin: bool = False,
176
+ ) -> None:
126
177
  self._timeout = aiohttp.ClientTimeout(total=45)
127
178
  self._bot_agent = sanitize_bot_agent(bot_agent)
179
+ # Deployment route tag: SKRouteTag header + _cradle_hostname on every URL.
180
+ self._route_tag = (route_tag or "").strip() or None
181
+ # Ask WeChat to require the phone PIN when binding.
182
+ self._verify_pin = verify_pin
183
+
184
+ def _route(self, url: str) -> str:
185
+ cradle = cradle_hostname(self._route_tag)
186
+ if not cradle:
187
+ return url
188
+ sep = "&" if "?" in url else "?"
189
+ return f"{url}{sep}_cradle_hostname={quote(cradle, safe='')}"
128
190
 
129
191
  def _base_info(self) -> dict[str, str]:
130
192
  return {"channel_version": CHANNEL_VERSION, "bot_agent": self._bot_agent}
@@ -138,11 +200,13 @@ class ILinkApi:
138
200
  first) so the server can answer binded_redirect for an already-bound
139
201
  bot instead of issuing a duplicate session.
140
202
  """
141
- url = f"{base_url}/ilink/bot/get_bot_qrcode?bot_type=3"
142
- body = {"local_token_list": local_token_list or []}
203
+ url = self._route(f"{base_url}/ilink/bot/get_bot_qrcode?bot_type=3")
204
+ body: dict[str, Any] = {"local_token_list": local_token_list or []}
205
+ if self._verify_pin:
206
+ body["bot_spam_business_data"] = VERIFY_PIN_BUSINESS_DATA
143
207
  async with aiohttp.ClientSession() as session:
144
208
  async with session.post(
145
- url, headers=_common_headers(), json=body
209
+ url, headers=post_headers(None, self._route_tag), json=body
146
210
  ) as resp:
147
211
  return await _parse_response(resp, "get_bot_qrcode")
148
212
 
@@ -157,11 +221,16 @@ class ILinkApi:
157
221
  url = f"{base_url}/ilink/bot/get_qrcode_status?qrcode={quote(qrcode, safe='')}"
158
222
  if verify_code:
159
223
  url += f"&verify_code={quote(verify_code, safe='')}"
160
- async with aiohttp.ClientSession() as session:
161
- async with session.get(
162
- url, headers=_common_headers()
163
- ) as resp:
164
- return await _parse_response(resp, "get_qrcode_status")
224
+ # Long poll: a timeout or network error means "no change yet", as upstream.
225
+ timeout = aiohttp.ClientTimeout(total=QR_STATUS_TIMEOUT_SECS)
226
+ try:
227
+ async with aiohttp.ClientSession(timeout=timeout) as session:
228
+ async with session.get(
229
+ self._route(url), headers=_common_headers(self._route_tag)
230
+ ) as resp:
231
+ return await _parse_response(resp, "get_qrcode_status")
232
+ except (asyncio.TimeoutError, aiohttp.ClientError):
233
+ return {"status": "wait"}
165
234
 
166
235
  async def get_updates(
167
236
  self, base_url: str, token: str, cursor: str
@@ -173,7 +242,17 @@ class ILinkApi:
173
242
  self, base_url: str, token: str, msg: dict[str, Any]
174
243
  ) -> dict[str, Any]:
175
244
  body = {"msg": msg, "base_info": self._base_info()}
176
- return await self._post(base_url, "/ilink/bot/sendmessage", token, body)
245
+ try:
246
+ return await self._post(base_url, "/ilink/bot/sendmessage", token, body)
247
+ except ApiError as e:
248
+ if e.is_send_rejected:
249
+ raise ApiError(
250
+ f"{e} — {SEND_REJECTED_HINT}",
251
+ http_status=e.http_status,
252
+ errcode=e.errcode,
253
+ payload=e.payload,
254
+ ) from e
255
+ raise
177
256
 
178
257
  async def get_config(
179
258
  self, base_url: str, token: str, user_id: str, context_token: str
@@ -235,11 +314,11 @@ class ILinkApi:
235
314
  body: dict[str, Any],
236
315
  timeout_secs: int = 15,
237
316
  ) -> dict[str, Any]:
238
- url = f"{base_url.rstrip('/')}{endpoint}"
317
+ url = self._route(f"{base_url.rstrip('/')}{endpoint}")
239
318
  timeout = aiohttp.ClientTimeout(total=timeout_secs)
240
319
  async with aiohttp.ClientSession(timeout=timeout) as session:
241
320
  async with session.post(
242
- url, headers=auth_headers(token), json=body
321
+ url, headers=auth_headers(token, self._route_tag), json=body
243
322
  ) as resp:
244
323
  return await _parse_response(resp, endpoint)
245
324
 
@@ -0,0 +1,25 @@
1
+ """Text helpers for WeChat delivery."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+
7
+ #: Full-width low line (U+FF3F). WeChat shows it as a character, not markup.
8
+ FULLWIDTH_UNDERSCORE = "_"
9
+
10
+ _CODE = re.compile(r"(```[\s\S]*?```|`[^`\n]*`)")
11
+
12
+
13
+ def protect_underscores(text: str) -> str:
14
+ """Keep underscores visible in WeChat.
15
+
16
+ WeChat renders bot text as Markdown, so ``EPS_manuscript_CN.pdf`` shows as
17
+ ``EPSmanuscriptCN.pdf`` and ``\\_`` does not help (issue #79). This replaces
18
+ every ``_`` outside code spans and fences with the full-width ``_``
19
+ (U+FF3F). Text the user copies then contains ``_``, not ``_``.
20
+ """
21
+ parts = _CODE.split(text)
22
+ return "".join(
23
+ part if i % 2 else part.replace("_", FULLWIDTH_UNDERSCORE)
24
+ for i, part in enumerate(parts)
25
+ )
@@ -83,8 +83,28 @@ class VideoContent:
83
83
  @dataclass
84
84
  class QuotedMessage:
85
85
  title: str | None = None
86
+ #: Quoted text. For a partial quote, only the quoted part when resolvable.
86
87
  text: str | None = None
87
88
  type: ContentType | None = None
89
+ #: Server ID of the quoted message. Newer WeChat clients send only this
90
+ #: ID; the SDK then fills ``text`` from its message cache when it has seen
91
+ #: the message (see ``message_cache_size``).
92
+ message_id: str | None = None
93
+ #: True when the quoted message was sent by this bot (known from the cache).
94
+ from_bot: bool | None = None
95
+ #: ``ref_msg.partial_text`` when the user quoted only part of the message.
96
+ partial_text: dict[str, Any] | None = None
97
+
98
+
99
+ @dataclass
100
+ class SendResult:
101
+ """Result of a send."""
102
+
103
+ #: Server-assigned message ID as a string (uint64). For long text split
104
+ #: into chunks, the ID of the last chunk. None when the server sent none.
105
+ message_id: str | None = None
106
+ #: ID of the separate caption message, when a caption was sent.
107
+ caption_message_id: str | None = None
88
108
 
89
109
 
90
110
  @dataclass
@@ -126,3 +146,5 @@ class IncomingMessage:
126
146
  quoted_message: QuotedMessage | None = None
127
147
  raw: dict[str, Any] = field(default_factory=dict)
128
148
  _context_token: str = ""
149
+ #: Server message ID (uint64 as a string). A later quote refers to this ID.
150
+ message_id: str | None = None
File without changes
File without changes