wechatbot-sdk 0.2.1__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.
- {wechatbot_sdk-0.2.1 → wechatbot_sdk-0.4.0}/PKG-INFO +2 -2
- {wechatbot_sdk-0.2.1 → wechatbot_sdk-0.4.0}/pyproject.toml +1 -1
- wechatbot_sdk-0.4.0/tests/test_bot_agent.py +42 -0
- wechatbot_sdk-0.4.0/tests/test_protocol_fixes.py +60 -0
- wechatbot_sdk-0.4.0/tests/test_quoted_messages.py +65 -0
- wechatbot_sdk-0.4.0/tests/test_text.py +9 -0
- wechatbot_sdk-0.4.0/tests/test_upstream_3.py +35 -0
- {wechatbot_sdk-0.2.1 → wechatbot_sdk-0.4.0}/wechatbot/__init__.py +4 -0
- {wechatbot_sdk-0.2.1 → wechatbot_sdk-0.4.0}/wechatbot/auth.py +72 -7
- {wechatbot_sdk-0.2.1 → wechatbot_sdk-0.4.0}/wechatbot/client.py +103 -38
- {wechatbot_sdk-0.2.1 → wechatbot_sdk-0.4.0}/wechatbot/errors.py +6 -0
- wechatbot_sdk-0.4.0/wechatbot/message_cache.py +111 -0
- {wechatbot_sdk-0.2.1 → wechatbot_sdk-0.4.0}/wechatbot/protocol.py +169 -31
- wechatbot_sdk-0.4.0/wechatbot/text.py +25 -0
- {wechatbot_sdk-0.2.1 → wechatbot_sdk-0.4.0}/wechatbot/types.py +22 -0
- {wechatbot_sdk-0.2.1 → wechatbot_sdk-0.4.0}/.gitignore +0 -0
- {wechatbot_sdk-0.2.1 → wechatbot_sdk-0.4.0}/README.md +0 -0
- {wechatbot_sdk-0.2.1 → wechatbot_sdk-0.4.0}/examples/echo_bot.py +0 -0
- {wechatbot_sdk-0.2.1 → wechatbot_sdk-0.4.0}/tests/test_client.py +0 -0
- {wechatbot_sdk-0.2.1 → wechatbot_sdk-0.4.0}/tests/test_crypto.py +0 -0
- {wechatbot_sdk-0.2.1 → wechatbot_sdk-0.4.0}/wechatbot/crypto.py +0 -0
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
"""Tests for bot_agent sanitization."""
|
|
2
|
+
|
|
3
|
+
from wechatbot.protocol import DEFAULT_BOT_AGENT, sanitize_bot_agent
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def test_empty_input_falls_back_to_default():
|
|
7
|
+
assert sanitize_bot_agent(None) == DEFAULT_BOT_AGENT
|
|
8
|
+
assert sanitize_bot_agent("") == DEFAULT_BOT_AGENT
|
|
9
|
+
assert sanitize_bot_agent(" ") == DEFAULT_BOT_AGENT
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def test_single_product():
|
|
13
|
+
assert sanitize_bot_agent("MyApp/1.2") == "MyApp/1.2"
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def test_product_with_comment():
|
|
17
|
+
assert sanitize_bot_agent("MyApp/1.2 (prod build)") == "MyApp/1.2 (prod build)"
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def test_multiple_products():
|
|
21
|
+
assert sanitize_bot_agent("MyApp/1.2 (prod) Lib/0.3") == "MyApp/1.2 (prod) Lib/0.3"
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def test_normalizes_whitespace():
|
|
25
|
+
assert sanitize_bot_agent(" MyApp/1.2 Lib/0.3 ") == "MyApp/1.2 Lib/0.3"
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def test_invalid_input_falls_back_wholesale():
|
|
29
|
+
assert sanitize_bot_agent("no-slash") == DEFAULT_BOT_AGENT
|
|
30
|
+
assert sanitize_bot_agent("bad name/1.0 !!!") == DEFAULT_BOT_AGENT
|
|
31
|
+
assert sanitize_bot_agent("(orphan comment)") == DEFAULT_BOT_AGENT
|
|
32
|
+
assert sanitize_bot_agent("App/1.0 (unclosed") == DEFAULT_BOT_AGENT
|
|
33
|
+
assert sanitize_bot_agent("App/1.0 (nested (comment))") == DEFAULT_BOT_AGENT
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def test_overlong_tokens_rejected():
|
|
37
|
+
assert sanitize_bot_agent("a" * 33 + "/1.0") == DEFAULT_BOT_AGENT
|
|
38
|
+
assert sanitize_bot_agent("App/" + "1" * 33) == DEFAULT_BOT_AGENT
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def test_over_byte_cap_rejected():
|
|
42
|
+
assert sanitize_bot_agent(("App/1.0 " * 40).strip()) == DEFAULT_BOT_AGENT
|
|
@@ -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,6 +57,29 @@ 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
|
+
|
|
66
|
+
async def _read_verify_code(is_retry: bool) -> str:
|
|
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
|
+
)
|
|
74
|
+
prompt = (
|
|
75
|
+
"Code mismatch — enter the pairing code shown in WeChat again: "
|
|
76
|
+
if is_retry
|
|
77
|
+
else "Enter the pairing code shown in WeChat on your phone: "
|
|
78
|
+
)
|
|
79
|
+
code = await asyncio.to_thread(input, prompt)
|
|
80
|
+
return code.strip()
|
|
81
|
+
|
|
82
|
+
|
|
60
83
|
async def login(
|
|
61
84
|
api: ILinkApi,
|
|
62
85
|
*,
|
|
@@ -66,12 +89,16 @@ async def login(
|
|
|
66
89
|
on_qr_url: Callable[[str], None] | None = None,
|
|
67
90
|
on_scanned: Callable[[], None] | None = None,
|
|
68
91
|
on_expired: Callable[[], None] | None = None,
|
|
92
|
+
on_verify_code: Callable[[bool], str] | None = None,
|
|
69
93
|
) -> Credentials:
|
|
70
94
|
"""QR code login. Returns stored credentials if available and force=False."""
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
95
|
+
stored = await load_credentials(cred_path)
|
|
96
|
+
if not force and stored:
|
|
97
|
+
return stored
|
|
98
|
+
|
|
99
|
+
# Send known local tokens so the server can answer binded_redirect
|
|
100
|
+
# instead of issuing a duplicate session for an already-bound bot.
|
|
101
|
+
local_token_list = [stored.token] if stored and stored.token else []
|
|
75
102
|
|
|
76
103
|
qr_refresh_count = 0
|
|
77
104
|
while True:
|
|
@@ -81,7 +108,7 @@ async def login(
|
|
|
81
108
|
f"QR code expired {MAX_QR_REFRESH_COUNT} times — login aborted"
|
|
82
109
|
)
|
|
83
110
|
|
|
84
|
-
qr = await api.get_qr_code(FIXED_QR_BASE_URL)
|
|
111
|
+
qr = await api.get_qr_code(FIXED_QR_BASE_URL, local_token_list)
|
|
85
112
|
qr_url = qr["qrcode_img_content"]
|
|
86
113
|
|
|
87
114
|
if on_qr_url:
|
|
@@ -91,13 +118,19 @@ async def login(
|
|
|
91
118
|
|
|
92
119
|
last_status = ""
|
|
93
120
|
current_poll_base_url = FIXED_QR_BASE_URL
|
|
121
|
+
# Pairing code awaiting server verification (pair-code login flow)
|
|
122
|
+
pending_verify_code: str | None = None
|
|
94
123
|
while True:
|
|
95
|
-
status = await api.poll_qr_status(
|
|
96
|
-
|
|
124
|
+
status = await api.poll_qr_status(
|
|
125
|
+
current_poll_base_url, qr["qrcode"], pending_verify_code
|
|
126
|
+
)
|
|
127
|
+
current = status.get("status", "wait")
|
|
97
128
|
|
|
98
129
|
if current != last_status:
|
|
99
130
|
last_status = current
|
|
100
131
|
if current == "scaned":
|
|
132
|
+
# A pending pairing code that leads back to scaned was accepted
|
|
133
|
+
pending_verify_code = None
|
|
101
134
|
if on_scanned:
|
|
102
135
|
on_scanned()
|
|
103
136
|
else:
|
|
@@ -129,6 +162,38 @@ async def login(
|
|
|
129
162
|
await save_credentials(creds, cred_path)
|
|
130
163
|
return creds
|
|
131
164
|
|
|
165
|
+
# Pair-code challenge: ask the user for the digits shown in WeChat
|
|
166
|
+
if status_needs_verify_code(current):
|
|
167
|
+
is_retry = pending_verify_code is not None
|
|
168
|
+
if on_verify_code:
|
|
169
|
+
pending_verify_code = on_verify_code(is_retry)
|
|
170
|
+
else:
|
|
171
|
+
pending_verify_code = await _read_verify_code(is_retry)
|
|
172
|
+
continue # Re-poll immediately with the code attached
|
|
173
|
+
|
|
174
|
+
# Too many wrong pairing codes: server blocked this QR — get a new one
|
|
175
|
+
if current == "verify_code_blocked":
|
|
176
|
+
print(
|
|
177
|
+
"[wechatbot] Pairing code blocked after repeated mismatches "
|
|
178
|
+
"— requesting new QR",
|
|
179
|
+
file=sys.stderr,
|
|
180
|
+
)
|
|
181
|
+
pending_verify_code = None
|
|
182
|
+
break # Outer loop requests a new QR (counts toward refresh limit)
|
|
183
|
+
|
|
184
|
+
# Already bound to this client: reuse existing local credentials
|
|
185
|
+
if current == "binded_redirect":
|
|
186
|
+
if stored:
|
|
187
|
+
print(
|
|
188
|
+
"[wechatbot] Bot already bound — reusing stored credentials",
|
|
189
|
+
file=sys.stderr,
|
|
190
|
+
)
|
|
191
|
+
return stored
|
|
192
|
+
raise AuthError(
|
|
193
|
+
"Server reports this bot is already bound to this client "
|
|
194
|
+
"(binded_redirect), but no local credentials were found"
|
|
195
|
+
)
|
|
196
|
+
|
|
132
197
|
# Handle IDC redirect
|
|
133
198
|
if current == "scaned_but_redirect":
|
|
134
199
|
redirect_host = status.get("redirect_host")
|
|
@@ -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,
|
|
@@ -77,6 +79,11 @@ class WeChatBot:
|
|
|
77
79
|
on_scanned: Callable[[], None] | None = None,
|
|
78
80
|
on_expired: Callable[[], None] | None = None,
|
|
79
81
|
on_error: Callable[[Exception], None] | None = None,
|
|
82
|
+
on_verify_code: Callable[[bool], str] | None = None,
|
|
83
|
+
bot_agent: str | None = None,
|
|
84
|
+
message_cache_size: int = 1000,
|
|
85
|
+
route_tag: str | None = None,
|
|
86
|
+
verify_pin: bool = False,
|
|
80
87
|
) -> None:
|
|
81
88
|
self._base_url = base_url or DEFAULT_BASE_URL
|
|
82
89
|
self._cred_path = Path(cred_path) if cred_path else None
|
|
@@ -84,8 +91,13 @@ class WeChatBot:
|
|
|
84
91
|
self._on_scanned = on_scanned
|
|
85
92
|
self._on_expired = on_expired
|
|
86
93
|
self._on_error = on_error
|
|
94
|
+
self._on_verify_code = on_verify_code
|
|
87
95
|
|
|
88
|
-
|
|
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)
|
|
89
101
|
self._credentials: Credentials | None = None
|
|
90
102
|
self._context_tokens: dict[str, str] = {}
|
|
91
103
|
self._handlers: list[MessageHandler] = []
|
|
@@ -104,6 +116,7 @@ class WeChatBot:
|
|
|
104
116
|
on_qr_url=self._on_qr_url,
|
|
105
117
|
on_scanned=self._on_scanned,
|
|
106
118
|
on_expired=self._on_expired,
|
|
119
|
+
on_verify_code=self._on_verify_code,
|
|
107
120
|
)
|
|
108
121
|
self._credentials = creds
|
|
109
122
|
self._base_url = creds.base_url
|
|
@@ -122,19 +135,20 @@ class WeChatBot:
|
|
|
122
135
|
|
|
123
136
|
# ── Sending ───────────────────────────────────────────────────────
|
|
124
137
|
|
|
125
|
-
async def reply(self, msg: IncomingMessage, text: str) ->
|
|
138
|
+
async def reply(self, msg: IncomingMessage, text: str) -> SendResult:
|
|
126
139
|
"""Reply to an incoming message with text.
|
|
127
140
|
|
|
128
141
|
For media (images, files, video), use :meth:`reply_media`.
|
|
129
142
|
"""
|
|
130
143
|
self._context_tokens[msg.user_id] = msg._context_token
|
|
131
|
-
await self._send_content(msg.user_id, msg._context_token, text)
|
|
144
|
+
result = await self._send_content(msg.user_id, msg._context_token, text)
|
|
132
145
|
try:
|
|
133
146
|
await self.stop_typing(msg.user_id)
|
|
134
147
|
except Exception:
|
|
135
148
|
pass
|
|
149
|
+
return result
|
|
136
150
|
|
|
137
|
-
async def reply_media(self, msg: IncomingMessage, content: SendContent) ->
|
|
151
|
+
async def reply_media(self, msg: IncomingMessage, content: SendContent) -> SendResult:
|
|
138
152
|
"""Reply to an incoming message with media content.
|
|
139
153
|
|
|
140
154
|
Accepts text string or media dict::
|
|
@@ -144,13 +158,14 @@ class WeChatBot:
|
|
|
144
158
|
await bot.reply_media(msg, {"video": mp4_bytes, "caption": "Check this"})
|
|
145
159
|
"""
|
|
146
160
|
self._context_tokens[msg.user_id] = msg._context_token
|
|
147
|
-
await self._send_content(msg.user_id, msg._context_token, content)
|
|
161
|
+
result = await self._send_content(msg.user_id, msg._context_token, content)
|
|
148
162
|
try:
|
|
149
163
|
await self.stop_typing(msg.user_id)
|
|
150
164
|
except Exception:
|
|
151
165
|
pass
|
|
166
|
+
return result
|
|
152
167
|
|
|
153
|
-
async def send(self, user_id: str, text: str) ->
|
|
168
|
+
async def send(self, user_id: str, text: str) -> SendResult:
|
|
154
169
|
"""Send a text message to a user (requires prior context_token).
|
|
155
170
|
|
|
156
171
|
For media (images, files, video), use :meth:`send_media`.
|
|
@@ -158,14 +173,14 @@ class WeChatBot:
|
|
|
158
173
|
ct = self._context_tokens.get(user_id)
|
|
159
174
|
if not ct:
|
|
160
175
|
raise NoContextError(user_id)
|
|
161
|
-
await self._send_content(user_id, ct, text)
|
|
176
|
+
return await self._send_content(user_id, ct, text)
|
|
162
177
|
|
|
163
|
-
async def send_media(self, user_id: str, content: SendContent) ->
|
|
178
|
+
async def send_media(self, user_id: str, content: SendContent) -> SendResult:
|
|
164
179
|
"""Send media content to a user (requires prior context_token)."""
|
|
165
180
|
ct = self._context_tokens.get(user_id)
|
|
166
181
|
if not ct:
|
|
167
182
|
raise NoContextError(user_id)
|
|
168
|
-
await self._send_content(user_id, ct, content)
|
|
183
|
+
return await self._send_content(user_id, ct, content)
|
|
169
184
|
|
|
170
185
|
# ── Download ───────────────────────────────────────────────────
|
|
171
186
|
|
|
@@ -252,6 +267,13 @@ class WeChatBot:
|
|
|
252
267
|
"""Start the long-poll loop. Blocks until stop() is called."""
|
|
253
268
|
creds = self._require_creds()
|
|
254
269
|
self._stopped = False
|
|
270
|
+
|
|
271
|
+
# Tell the server we're coming online (non-fatal)
|
|
272
|
+
try:
|
|
273
|
+
await self._api.notify_start(creds.base_url, creds.token)
|
|
274
|
+
except Exception as e:
|
|
275
|
+
self._log(f"notify_start failed (ignored): {e}")
|
|
276
|
+
|
|
255
277
|
self._log("Long-poll started")
|
|
256
278
|
retry_delay = 1.0
|
|
257
279
|
|
|
@@ -271,6 +293,11 @@ class WeChatBot:
|
|
|
271
293
|
self._remember_context(raw)
|
|
272
294
|
msg = self._parse_message(raw)
|
|
273
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
|
+
)
|
|
274
301
|
await self._dispatch(msg)
|
|
275
302
|
|
|
276
303
|
except ApiError as e:
|
|
@@ -301,6 +328,14 @@ class WeChatBot:
|
|
|
301
328
|
await asyncio.sleep(retry_delay)
|
|
302
329
|
retry_delay = min(retry_delay * 2, 10.0)
|
|
303
330
|
|
|
331
|
+
# Tell the server we're going offline (non-fatal).
|
|
332
|
+
# Credentials may have rotated after a mid-poll re-login, so re-read them.
|
|
333
|
+
try:
|
|
334
|
+
creds = self._require_creds()
|
|
335
|
+
await self._api.notify_stop(creds.base_url, creds.token)
|
|
336
|
+
except Exception as e:
|
|
337
|
+
self._log(f"notify_stop failed (ignored): {e}")
|
|
338
|
+
|
|
304
339
|
self._log("Long-poll stopped")
|
|
305
340
|
|
|
306
341
|
def stop(self) -> None:
|
|
@@ -319,20 +354,20 @@ class WeChatBot:
|
|
|
319
354
|
|
|
320
355
|
async def _send_content(
|
|
321
356
|
self, user_id: str, context_token: str, content: SendContent,
|
|
322
|
-
) ->
|
|
357
|
+
) -> SendResult:
|
|
323
358
|
# String shorthand → text
|
|
324
359
|
if isinstance(content, str):
|
|
325
|
-
await self._send_text(user_id, content, context_token)
|
|
326
|
-
return
|
|
360
|
+
return SendResult(message_id=await self._send_text(user_id, content, context_token))
|
|
327
361
|
|
|
328
362
|
# {"text": ...}
|
|
329
363
|
if "text" in content:
|
|
330
|
-
|
|
331
|
-
|
|
364
|
+
return SendResult(
|
|
365
|
+
message_id=await self._send_text(user_id, content["text"], context_token)
|
|
366
|
+
)
|
|
332
367
|
|
|
333
368
|
# {"image": bytes}
|
|
334
369
|
if "image" in content:
|
|
335
|
-
await self._send_media_buffer(
|
|
370
|
+
return await self._send_media_buffer(
|
|
336
371
|
user_id, context_token, content["image"],
|
|
337
372
|
MediaType.IMAGE,
|
|
338
373
|
lambda result: {"type": int(MessageItemType.IMAGE), "image_item": {
|
|
@@ -341,11 +376,10 @@ class WeChatBot:
|
|
|
341
376
|
}},
|
|
342
377
|
content.get("caption"),
|
|
343
378
|
)
|
|
344
|
-
return
|
|
345
379
|
|
|
346
380
|
# {"video": bytes}
|
|
347
381
|
if "video" in content:
|
|
348
|
-
await self._send_media_buffer(
|
|
382
|
+
return await self._send_media_buffer(
|
|
349
383
|
user_id, context_token, content["video"],
|
|
350
384
|
MediaType.VIDEO,
|
|
351
385
|
lambda result: {"type": int(MessageItemType.VIDEO), "video_item": {
|
|
@@ -354,7 +388,6 @@ class WeChatBot:
|
|
|
354
388
|
}},
|
|
355
389
|
content.get("caption"),
|
|
356
390
|
)
|
|
357
|
-
return
|
|
358
391
|
|
|
359
392
|
# {"file": bytes, "file_name": str}
|
|
360
393
|
if "file" in content:
|
|
@@ -362,23 +395,18 @@ class WeChatBot:
|
|
|
362
395
|
category = _categorize_by_extension(file_name)
|
|
363
396
|
|
|
364
397
|
if category == "image":
|
|
365
|
-
await self._send_content(user_id, context_token, {
|
|
398
|
+
return await self._send_content(user_id, context_token, {
|
|
366
399
|
"image": content["file"], "caption": content.get("caption"),
|
|
367
400
|
})
|
|
368
|
-
return
|
|
369
401
|
|
|
370
402
|
if category == "video":
|
|
371
|
-
await self._send_content(user_id, context_token, {
|
|
403
|
+
return await self._send_content(user_id, context_token, {
|
|
372
404
|
"video": content["file"], "caption": content.get("caption"),
|
|
373
405
|
})
|
|
374
|
-
return
|
|
375
406
|
|
|
376
407
|
# Generic file
|
|
377
|
-
caption = content.get("caption")
|
|
378
|
-
if caption:
|
|
379
|
-
await self._send_text(user_id, caption, context_token)
|
|
380
408
|
raw_data = content["file"]
|
|
381
|
-
await self._send_media_buffer(
|
|
409
|
+
return await self._send_media_buffer(
|
|
382
410
|
user_id, context_token, raw_data,
|
|
383
411
|
MediaType.FILE,
|
|
384
412
|
lambda result: {"type": int(MessageItemType.FILE), "file_item": {
|
|
@@ -386,8 +414,8 @@ class WeChatBot:
|
|
|
386
414
|
"file_name": file_name,
|
|
387
415
|
"len": str(len(raw_data)),
|
|
388
416
|
}},
|
|
417
|
+
content.get("caption"),
|
|
389
418
|
)
|
|
390
|
-
return
|
|
391
419
|
|
|
392
420
|
raise ValueError(f"Unsupported content type: {content!r}")
|
|
393
421
|
|
|
@@ -399,16 +427,21 @@ class WeChatBot:
|
|
|
399
427
|
media_type: int,
|
|
400
428
|
build_item: Callable[[UploadResult], dict[str, Any]],
|
|
401
429
|
caption: str | None = None,
|
|
402
|
-
) ->
|
|
430
|
+
) -> SendResult:
|
|
403
431
|
creds = self._require_creds()
|
|
404
432
|
result = await self._cdn_upload(creds, data, user_id, media_type)
|
|
405
|
-
|
|
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
|
|
406
436
|
if caption:
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
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))
|
|
411
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)
|
|
412
445
|
|
|
413
446
|
# ── Internal: CDN download ─────────────────────────────────────
|
|
414
447
|
|
|
@@ -494,13 +527,18 @@ class WeChatBot:
|
|
|
494
527
|
|
|
495
528
|
# ── Internal: text ─────────────────────────────────────────────
|
|
496
529
|
|
|
497
|
-
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."""
|
|
498
532
|
if not text:
|
|
499
533
|
raise ValueError("Message text cannot be empty")
|
|
500
534
|
creds = self._require_creds()
|
|
535
|
+
message_id = None
|
|
501
536
|
for chunk in _chunk_text(text, 4000):
|
|
502
537
|
msg = self._api.build_text_message(user_id, context_token, chunk)
|
|
503
|
-
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
|
|
504
542
|
|
|
505
543
|
def _remember_context(self, raw: dict[str, Any]) -> None:
|
|
506
544
|
mt = raw.get("message_type")
|
|
@@ -554,9 +592,7 @@ class WeChatBot:
|
|
|
554
592
|
duration_ms=vi.get("play_length"),
|
|
555
593
|
))
|
|
556
594
|
if item.get("ref_msg"):
|
|
557
|
-
|
|
558
|
-
qt = ref.get("message_item", {}).get("text_item", {}).get("text")
|
|
559
|
-
quoted = QuotedMessage(title=ref.get("title"), text=qt)
|
|
595
|
+
quoted = _parse_ref_message(item["ref_msg"])
|
|
560
596
|
|
|
561
597
|
return IncomingMessage(
|
|
562
598
|
user_id=raw["from_user_id"],
|
|
@@ -568,6 +604,7 @@ class WeChatBot:
|
|
|
568
604
|
images=images, voices=voices, files=files, videos=videos,
|
|
569
605
|
quoted_message=quoted, raw=raw,
|
|
570
606
|
_context_token=raw.get("context_token", ""),
|
|
607
|
+
message_id=_id_str(raw.get("message_id")),
|
|
571
608
|
)
|
|
572
609
|
|
|
573
610
|
async def _dispatch(self, msg: IncomingMessage) -> None:
|
|
@@ -593,6 +630,34 @@ class WeChatBot:
|
|
|
593
630
|
print(f"[wechatbot] {msg}", file=sys.stderr)
|
|
594
631
|
|
|
595
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
|
+
|
|
596
661
|
def _detect_type(items: list[dict[str, Any]]) -> str:
|
|
597
662
|
if not items:
|
|
598
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,9 +2,11 @@
|
|
|
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
|
|
9
|
+
import re
|
|
8
10
|
import struct
|
|
9
11
|
from importlib.metadata import version as pkg_version
|
|
10
12
|
from typing import Any
|
|
@@ -19,19 +21,40 @@ from .types import MediaType, MessageItemType, MessageState, MessageType
|
|
|
19
21
|
DEFAULT_BASE_URL = "https://ilinkai.weixin.qq.com"
|
|
20
22
|
CDN_BASE_URL = "https://novac2c.cdn.weixin.qq.com/c2c"
|
|
21
23
|
|
|
22
|
-
#
|
|
24
|
+
# This SDK's own package version.
|
|
23
25
|
try:
|
|
24
|
-
|
|
26
|
+
SDK_VERSION = pkg_version("wechatbot-sdk")
|
|
25
27
|
except Exception:
|
|
26
|
-
|
|
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
|
+
)
|
|
27
50
|
|
|
28
51
|
# iLink-App-Id header value
|
|
29
52
|
ILINK_APP_ID = "bot"
|
|
30
53
|
|
|
31
54
|
|
|
32
55
|
def _build_client_version() -> str:
|
|
33
|
-
"""Encode version as 0x00MMNNPP uint32 string."""
|
|
34
|
-
parts =
|
|
56
|
+
"""Encode the upstream version as a 0x00MMNNPP uint32 string."""
|
|
57
|
+
parts = UPSTREAM_PROTOCOL_VERSION.split(".")
|
|
35
58
|
try:
|
|
36
59
|
major = int(parts[0]) & 0xFF if len(parts) > 0 else 0
|
|
37
60
|
minor = int(parts[1]) & 0xFF if len(parts) > 1 else 0
|
|
@@ -49,26 +72,73 @@ def random_wechat_uin() -> str:
|
|
|
49
72
|
return base64.b64encode(str(val).encode("utf-8")).decode("ascii")
|
|
50
73
|
|
|
51
74
|
|
|
52
|
-
def _common_headers() -> dict[str, str]:
|
|
75
|
+
def _common_headers(route_tag: str | None = None) -> dict[str, str]:
|
|
53
76
|
"""Headers included in both GET and POST requests."""
|
|
54
|
-
|
|
77
|
+
headers = {
|
|
55
78
|
"iLink-App-Id": ILINK_APP_ID,
|
|
56
79
|
"iLink-App-ClientVersion": ILINK_APP_CLIENT_VERSION,
|
|
57
80
|
}
|
|
81
|
+
if route_tag:
|
|
82
|
+
headers["SKRouteTag"] = route_tag
|
|
83
|
+
return headers
|
|
58
84
|
|
|
59
85
|
|
|
60
|
-
def
|
|
61
|
-
|
|
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 = {
|
|
62
89
|
"Content-Type": "application/json",
|
|
63
90
|
"AuthorizationType": "ilink_bot_token",
|
|
64
|
-
"Authorization": f"Bearer {token}",
|
|
65
91
|
"X-WECHAT-UIN": random_wechat_uin(),
|
|
66
|
-
**_common_headers(),
|
|
92
|
+
**_common_headers(route_tag),
|
|
67
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")
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
# Default bot_agent when none is configured or the configured value is invalid.
|
|
117
|
+
DEFAULT_BOT_AGENT = f"WeChatBot/{SDK_VERSION}"
|
|
118
|
+
|
|
119
|
+
# Maximum length (bytes) of the sanitized bot_agent string.
|
|
120
|
+
_BOT_AGENT_MAX_LEN = 256
|
|
121
|
+
|
|
122
|
+
# UA-style grammar (matches openclaw-weixin):
|
|
123
|
+
# bot_agent = product *( SP product )
|
|
124
|
+
# product = name "/" version [ SP "(" comment ")" ]
|
|
125
|
+
_PRODUCT = r"[A-Za-z0-9_.\-]{1,32}/[A-Za-z0-9_.+\-]{1,32}(?: \([\x20-\x27\x2A-\x7E]{1,64}\))?"
|
|
126
|
+
_BOT_AGENT_RE = re.compile(rf"^{_PRODUCT}(?: {_PRODUCT})*$")
|
|
68
127
|
|
|
69
128
|
|
|
70
|
-
def
|
|
71
|
-
|
|
129
|
+
def sanitize_bot_agent(raw: str | None) -> str:
|
|
130
|
+
"""Validate a user-supplied bot_agent into a wire-safe string.
|
|
131
|
+
|
|
132
|
+
Unlike upstream openclaw-weixin (which salvages the valid tokens out of a
|
|
133
|
+
partially invalid string), any invalid input falls back to
|
|
134
|
+
DEFAULT_BOT_AGENT wholesale — simpler and just as safe on the wire.
|
|
135
|
+
"""
|
|
136
|
+
if not raw:
|
|
137
|
+
return DEFAULT_BOT_AGENT
|
|
138
|
+
normalized = " ".join(raw.split())
|
|
139
|
+
if not normalized or len(normalized.encode("utf-8")) > _BOT_AGENT_MAX_LEN:
|
|
140
|
+
return DEFAULT_BOT_AGENT
|
|
141
|
+
return normalized if _BOT_AGENT_RE.match(normalized) else DEFAULT_BOT_AGENT
|
|
72
142
|
|
|
73
143
|
|
|
74
144
|
async def _parse_response(resp: aiohttp.ClientResponse, label: str) -> dict[str, Any]:
|
|
@@ -97,34 +167,92 @@ async def _parse_response(resp: aiohttp.ClientResponse, label: str) -> dict[str,
|
|
|
97
167
|
class ILinkApi:
|
|
98
168
|
"""Low-level iLink API client. Each method maps 1:1 to an endpoint."""
|
|
99
169
|
|
|
100
|
-
def __init__(
|
|
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:
|
|
101
177
|
self._timeout = aiohttp.ClientTimeout(total=45)
|
|
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='')}"
|
|
190
|
+
|
|
191
|
+
def _base_info(self) -> dict[str, str]:
|
|
192
|
+
return {"channel_version": CHANNEL_VERSION, "bot_agent": self._bot_agent}
|
|
193
|
+
|
|
194
|
+
async def get_qr_code(
|
|
195
|
+
self, base_url: str, local_token_list: list[str] | None = None
|
|
196
|
+
) -> dict[str, Any]:
|
|
197
|
+
"""Request a login QR code.
|
|
102
198
|
|
|
103
|
-
|
|
104
|
-
|
|
199
|
+
local_token_list carries up to 10 known local bot tokens (newest
|
|
200
|
+
first) so the server can answer binded_redirect for an already-bound
|
|
201
|
+
bot instead of issuing a duplicate session.
|
|
202
|
+
"""
|
|
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
|
|
105
207
|
async with aiohttp.ClientSession() as session:
|
|
106
|
-
async with session.
|
|
208
|
+
async with session.post(
|
|
209
|
+
url, headers=post_headers(None, self._route_tag), json=body
|
|
210
|
+
) as resp:
|
|
107
211
|
return await _parse_response(resp, "get_bot_qrcode")
|
|
108
212
|
|
|
109
|
-
async def poll_qr_status(
|
|
213
|
+
async def poll_qr_status(
|
|
214
|
+
self, base_url: str, qrcode: str, verify_code: str | None = None
|
|
215
|
+
) -> dict[str, Any]:
|
|
216
|
+
"""Poll the QR scan status.
|
|
217
|
+
|
|
218
|
+
verify_code submits a pairing code after the server answered
|
|
219
|
+
need_verifycode (the digits shown in WeChat on the user's phone).
|
|
220
|
+
"""
|
|
110
221
|
url = f"{base_url}/ilink/bot/get_qrcode_status?qrcode={quote(qrcode, safe='')}"
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
222
|
+
if verify_code:
|
|
223
|
+
url += f"&verify_code={quote(verify_code, safe='')}"
|
|
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"}
|
|
116
234
|
|
|
117
235
|
async def get_updates(
|
|
118
236
|
self, base_url: str, token: str, cursor: str
|
|
119
237
|
) -> dict[str, Any]:
|
|
120
|
-
body = {"get_updates_buf": cursor, "base_info": _base_info()}
|
|
238
|
+
body = {"get_updates_buf": cursor, "base_info": self._base_info()}
|
|
121
239
|
return await self._post(base_url, "/ilink/bot/getupdates", token, body, 45)
|
|
122
240
|
|
|
123
241
|
async def send_message(
|
|
124
242
|
self, base_url: str, token: str, msg: dict[str, Any]
|
|
125
243
|
) -> dict[str, Any]:
|
|
126
|
-
body = {"msg": msg, "base_info": _base_info()}
|
|
127
|
-
|
|
244
|
+
body = {"msg": msg, "base_info": self._base_info()}
|
|
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
|
|
128
256
|
|
|
129
257
|
async def get_config(
|
|
130
258
|
self, base_url: str, token: str, user_id: str, context_token: str
|
|
@@ -132,7 +260,7 @@ class ILinkApi:
|
|
|
132
260
|
body = {
|
|
133
261
|
"ilink_user_id": user_id,
|
|
134
262
|
"context_token": context_token,
|
|
135
|
-
"base_info": _base_info(),
|
|
263
|
+
"base_info": self._base_info(),
|
|
136
264
|
}
|
|
137
265
|
return await self._post(base_url, "/ilink/bot/getconfig", token, body)
|
|
138
266
|
|
|
@@ -148,10 +276,20 @@ class ILinkApi:
|
|
|
148
276
|
"ilink_user_id": user_id,
|
|
149
277
|
"typing_ticket": ticket,
|
|
150
278
|
"status": status,
|
|
151
|
-
"base_info": _base_info(),
|
|
279
|
+
"base_info": self._base_info(),
|
|
152
280
|
}
|
|
153
281
|
return await self._post(base_url, "/ilink/bot/sendtyping", token, body)
|
|
154
282
|
|
|
283
|
+
async def notify_start(self, base_url: str, token: str) -> dict[str, Any]:
|
|
284
|
+
"""Notify the server that this client is starting (coming online)."""
|
|
285
|
+
body = {"base_info": self._base_info()}
|
|
286
|
+
return await self._post(base_url, "/ilink/bot/msg/notifystart", token, body)
|
|
287
|
+
|
|
288
|
+
async def notify_stop(self, base_url: str, token: str) -> dict[str, Any]:
|
|
289
|
+
"""Notify the server that this client is stopping (going offline)."""
|
|
290
|
+
body = {"base_info": self._base_info()}
|
|
291
|
+
return await self._post(base_url, "/ilink/bot/msg/notifystop", token, body)
|
|
292
|
+
|
|
155
293
|
@staticmethod
|
|
156
294
|
def build_media_message(
|
|
157
295
|
user_id: str,
|
|
@@ -176,11 +314,11 @@ class ILinkApi:
|
|
|
176
314
|
body: dict[str, Any],
|
|
177
315
|
timeout_secs: int = 15,
|
|
178
316
|
) -> dict[str, Any]:
|
|
179
|
-
url = f"{base_url.rstrip('/')}{endpoint}"
|
|
317
|
+
url = self._route(f"{base_url.rstrip('/')}{endpoint}")
|
|
180
318
|
timeout = aiohttp.ClientTimeout(total=timeout_secs)
|
|
181
319
|
async with aiohttp.ClientSession(timeout=timeout) as session:
|
|
182
320
|
async with session.post(
|
|
183
|
-
url, headers=auth_headers(token), json=body
|
|
321
|
+
url, headers=auth_headers(token, self._route_tag), json=body
|
|
184
322
|
) as resp:
|
|
185
323
|
return await _parse_response(resp, endpoint)
|
|
186
324
|
|
|
@@ -207,7 +345,7 @@ class ILinkApi:
|
|
|
207
345
|
"filesize": filesize,
|
|
208
346
|
"no_need_thumb": no_need_thumb,
|
|
209
347
|
"aeskey": aeskey,
|
|
210
|
-
"base_info": _base_info(),
|
|
348
|
+
"base_info": self._base_info(),
|
|
211
349
|
}
|
|
212
350
|
return await self._post(base_url, "/ilink/bot/getuploadurl", token, body)
|
|
213
351
|
|
|
@@ -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
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|