mirror of
https://github.com/langbot-app/LangBot.git
synced 2026-06-02 03:55:55 +00:00
feat(officialaccount): add eba adapter
This commit is contained in:
@@ -22,6 +22,7 @@ Current acceptance report: [EBA Adapter Acceptance Report](./acceptance-report.m
|
|||||||
| Lark / Feishu | Migrated; partial live text E2E, media-inbound gap remains | [Lark / Feishu](./lark.md) |
|
| Lark / Feishu | Migrated; partial live text E2E, media-inbound gap remains | [Lark / Feishu](./lark.md) |
|
||||||
| WeCom | Migrated; private text plugin E2E verified, media/group gaps remain | [WeCom](./wecom.md) |
|
| WeCom | Migrated; private text plugin E2E verified, media/group gaps remain | [WeCom](./wecom.md) |
|
||||||
| WeComBot | Migrated; private text and outbound/API plugin E2E verified, feedback/group gaps remain | [WeComBot](./wecombot.md) |
|
| WeComBot | Migrated; private text and outbound/API plugin E2E verified, feedback/group gaps remain | [WeComBot](./wecombot.md) |
|
||||||
|
| Official Account | Migrated; private text plugin E2E verified, proactive outbound not supported | [Official Account](./officialaccount.md) |
|
||||||
|
|
||||||
## Documentation Checklist
|
## Documentation Checklist
|
||||||
|
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ Scope:
|
|||||||
- `wecom-eba`
|
- `wecom-eba`
|
||||||
- `wecombot-eba`
|
- `wecombot-eba`
|
||||||
- `wecomcs-eba`
|
- `wecomcs-eba`
|
||||||
|
- `officialaccount-eba`
|
||||||
|
|
||||||
This report follows `acceptance-checklist.md`. Evidence levels are intentionally strict:
|
This report follows `acceptance-checklist.md`. Evidence levels are intentionally strict:
|
||||||
|
|
||||||
@@ -34,6 +35,7 @@ This report follows `acceptance-checklist.md`. Evidence levels are intentionally
|
|||||||
| WeCom | Partial EBA acceptance | Regular WeCom application-message adapter is split into the EBA directory with manifest, converters, API mixin, platform API map, and unit tests. Private text reached `EBAEventProbe` through standalone runtime and the real WeCom client; safe plugin APIs passed. Real inbound media and broader event coverage remain pending. |
|
| WeCom | Partial EBA acceptance | Regular WeCom application-message adapter is split into the EBA directory with manifest, converters, API mixin, platform API map, and unit tests. Private text reached `EBAEventProbe` through standalone runtime and the real WeCom client; safe plugin APIs passed. Real inbound media and broader event coverage remain pending. |
|
||||||
| WeComBot | Partial EBA acceptance | WeCom AI Bot is split into the EBA directory with WebSocket long connection mode and optional webhook mode, EBA message/feedback/platform-specific conversion, cache-backed common APIs, platform API map, unit tests, and a direct live probe. Private text, outbound component sweep, safe common APIs, and all declared WeComBot platform APIs reached `EBAEventProbe`; group, real inbound media, and feedback callback evidence remain pending. |
|
| WeComBot | Partial EBA acceptance | WeCom AI Bot is split into the EBA directory with WebSocket long connection mode and optional webhook mode, EBA message/feedback/platform-specific conversion, cache-backed common APIs, platform API map, unit tests, and a direct live probe. Private text, outbound component sweep, safe common APIs, and all declared WeComBot platform APIs reached `EBAEventProbe`; group, real inbound media, and feedback callback evidence remain pending. |
|
||||||
| WeCom Customer Service | Partial EBA acceptance | WeCom Customer Service is split into the EBA directory with manifest, converters, API mixin, platform API map, unit tests, docs, and a direct live probe scaffold. Real WeChat customer-side UI text reached `EBAEventProbe`; plugin outbound text/image and safe cache-backed common APIs passed. Inbound media and platform-specific API live coverage remain pending; later fallback text sends were blocked by WeCom `95001 send msg count limit`. |
|
| WeCom Customer Service | Partial EBA acceptance | WeCom Customer Service is split into the EBA directory with manifest, converters, API mixin, platform API map, unit tests, docs, and a direct live probe scaffold. Real WeChat customer-side UI text reached `EBAEventProbe`; plugin outbound text/image and safe cache-backed common APIs passed. Inbound media and platform-specific API live coverage remain pending; later fallback text sends were blocked by WeCom `95001 send msg count limit`. |
|
||||||
|
| Official Account | Partial EBA acceptance | WeChat Official Account is split into the EBA directory with manifest, converters, cache-backed safe APIs, platform API map, unit tests, and a direct live probe scaffold. Real WeChat Official Account UI private text reached `EBAEventProbe`; safe cache-backed common APIs and declared platform APIs passed. Proactive outbound `send_message` is not supported because replies must be tied to inbound webhook windows; inbound image/voice live UI evidence remains pending. |
|
||||||
|
|
||||||
Telegram and DingTalk now have real user-side UI image/file upload evidence in plugin JSONL. Discord and aiocqhttp do not yet have real UI inbound image/file evidence.
|
Telegram and DingTalk now have real user-side UI image/file upload evidence in plugin JSONL. Discord and aiocqhttp do not yet have real UI inbound image/file evidence.
|
||||||
|
|
||||||
@@ -52,6 +54,7 @@ Telegram and DingTalk now have real user-side UI image/file upload evidence in p
|
|||||||
| Lark / Feishu unit | local mocked Feishu SDK/client paths | `tests/unit_tests/platform/test_lark_eba_adapter.py` |
|
| Lark / Feishu unit | local mocked Feishu SDK/client paths | `tests/unit_tests/platform/test_lark_eba_adapter.py` |
|
||||||
| Lark / Feishu partial live | Feishu Mac, LangBot organization `LangBotDev` private chat | `data/temp/lark-plugin-e2e-ws.jsonl` |
|
| Lark / Feishu partial live | Feishu Mac, LangBot organization `LangBotDev` private chat | `data/temp/lark-plugin-e2e-ws.jsonl` |
|
||||||
| WeCom Customer Service | WeChat customer-side UI, `客服消息 -> 浪波智能客服` on `dev.rockchin.top` | `/home/wgc/LangBotxg/LangBotEbaTest/data/temp/wecomcs_eba_plugin_probe.jsonl` |
|
| WeCom Customer Service | WeChat customer-side UI, `客服消息 -> 浪波智能客服` on `dev.rockchin.top` | `/home/wgc/LangBotxg/LangBotEbaTest/data/temp/wecomcs_eba_plugin_probe.jsonl` |
|
||||||
|
| Official Account | WeChat desktop client, subscribed Official Account on `dev.rockchin.top` | `/home/wgc/LangBotxg/LangBotEbaTest/data/temp/officialaccount_eba_plugin_probe.jsonl` |
|
||||||
|
|
||||||
All plugin runs used SDK standalone runtime ports `5400/5401`, LangBot `--standalone-runtime`, and the real plugin at `langbot-plugin-demo/EBAEventProbe`.
|
All plugin runs used SDK standalone runtime ports `5400/5401`, LangBot `--standalone-runtime`, and the real plugin at `langbot-plugin-demo/EBAEventProbe`.
|
||||||
|
|
||||||
|
|||||||
101
docs/event-based-agents/adapters/officialaccount.md
Normal file
101
docs/event-based-agents/adapters/officialaccount.md
Normal file
@@ -0,0 +1,101 @@
|
|||||||
|
# OfficialAccount EBA Adapter
|
||||||
|
|
||||||
|
Adapter directory: `src/langbot/pkg/platform/adapters/officialaccount/`
|
||||||
|
|
||||||
|
Manifest name: `officialaccount-eba`
|
||||||
|
|
||||||
|
Status: partial migration. Unit/API-shape coverage is present, and private text `plugin-e2e-ui` plus safe API evidence has been verified against the `dev.rockchin.top` Official Account fixture. Proactive outbound `send_message` remains not supported by this adapter because WeChat Official Account replies must be tied to inbound webhook windows.
|
||||||
|
|
||||||
|
## Config
|
||||||
|
|
||||||
|
| Field | Required | Notes |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| `webhook_url` | no | Generated by LangBot and copied into the Official Account callback settings. |
|
||||||
|
| `token` | yes | WeChat callback token. |
|
||||||
|
| `EncodingAESKey` | yes | WeChat message encryption key. |
|
||||||
|
| `AppID` | yes | Official Account app ID. |
|
||||||
|
| `AppSecret` | yes | Official Account app secret. |
|
||||||
|
| `Mode` | yes | `drop` waits for an in-callback reply; `passive` returns the loading text first and queues the answer for the user's next message. |
|
||||||
|
| `LoadingMessage` | no | Only used by `passive` mode. |
|
||||||
|
| `api_base_url` | no | Optional API base URL for proxy deployments. |
|
||||||
|
|
||||||
|
## Events
|
||||||
|
|
||||||
|
| Event | Evidence | Notes |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| `message.received` | plugin-e2e-ui, unit | Text UI message verified through WeChat Official Account on `dev.rockchin.top`; image and voice webhook payloads are covered by unit tests. |
|
||||||
|
| `platform.specific` | unit | Subscribe/menu/etc. native events are emitted as structured `PlatformSpecificEvent`. |
|
||||||
|
|
||||||
|
## Common APIs
|
||||||
|
|
||||||
|
| API | Evidence | Notes |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| `reply_message` | unit | Queues/passively returns text through the inbound webhook source event. |
|
||||||
|
| `get_message` | plugin-e2e-ui, unit | Cached inbound message retrieved by `EBAEventProbe` platform API sweep. |
|
||||||
|
| `get_user_info` | plugin-e2e-ui, unit | Cached inbound sender retrieved by `EBAEventProbe` platform API sweep. |
|
||||||
|
| `get_friend_list` | plugin-e2e-ui, unit | Cached inbound sender list retrieved by `EBAEventProbe` platform API sweep. |
|
||||||
|
| `call_platform_api` | plugin-e2e-ui, unit | Safe diagnostic actions verified through `get_mode` and `get_cached_response_status`. |
|
||||||
|
| `send_message` | not-supported | Official Account customer-service proactive messaging is not implemented by the existing SDK adapter; only webhook reply is supported here. |
|
||||||
|
|
||||||
|
## Platform APIs
|
||||||
|
|
||||||
|
| Action | Evidence | Notes |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| `get_mode` | plugin-e2e-ui, unit | Returned `{"mode": "drop", "longer_response": false}` in live probe. |
|
||||||
|
| `get_cached_response_status` | plugin-e2e-ui, unit | Returned `{"pending": false}` in live probe. |
|
||||||
|
|
||||||
|
## Components
|
||||||
|
|
||||||
|
| Receive Component | Evidence | Notes |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| `Source` | plugin-e2e-ui, unit | Uses `MsgId` and `CreateTime`; live UI text message included `Source`. |
|
||||||
|
| `Plain` | plugin-e2e-ui, unit | Live UI text message mapped to `Plain`. |
|
||||||
|
| `Image` | unit | `PicUrl` and `MediaId` map to common `Image`. |
|
||||||
|
| `Voice` | unit | `MediaId` maps to common `Voice`. |
|
||||||
|
| `Unknown` | unit | Unsupported message/event types do not crash. |
|
||||||
|
| `At`, `AtAll`, `File`, `Quote`, `Face`, `Forward`, mixed chain | not-supported | WeChat Official Account inbound webhook payloads used by the current SDK do not expose these as common structured components. |
|
||||||
|
|
||||||
|
| Send Component | Evidence | Notes |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| `Plain` | unit | Sent as webhook reply text. |
|
||||||
|
| `Image`, `Voice`, `File`, `Quote`, `At`, `AtAll`, `Face`, `Forward`, mixed chain | not-supported | Existing SDK reply path is text XML only; non-text components degrade to readable placeholders in tests and are not declared as supported outbound components. |
|
||||||
|
|
||||||
|
## Verification Record
|
||||||
|
|
||||||
|
Test date: 2026-05-28
|
||||||
|
|
||||||
|
Endpoint/simulator: `dev.rockchin.top` with WeChat desktop client and a real subscribed Official Account conversation. The running EBA test stack used SDK standalone runtime ports `5400/5401`, LangBot from `/home/wgc/LangBotxg/LangBotEbaTest`, and `EBAEventProbe`.
|
||||||
|
|
||||||
|
Verified UI message: `EBA officialaccount single probe 2026-05-28 16:53`
|
||||||
|
|
||||||
|
Observed event/API evidence:
|
||||||
|
|
||||||
|
- `MessageReceived`: `bot_uuid=d7c46880-a9f8-431a-9172-5d3e0d663dbc`, `adapter_name=officialaccount-eba`, `chat_type=private`, `chat_id=ovH9L7OW6hNpWZWvp_NMmypVh26w`, `message_chain=[Source, Plain]`.
|
||||||
|
- Common safe APIs through probe platform sweep: `get_message`, `get_user_info`, `get_friend_list`.
|
||||||
|
- Platform APIs through `call_platform_api`: `get_mode`, `get_cached_response_status`.
|
||||||
|
- `send_message` and outbound component sweep returned explicit `NotSupportedError: send_message:official_account_requires_inbound_webhook_reply`, as expected for this adapter.
|
||||||
|
|
||||||
|
Standalone runtime command:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd langbot-plugin-sdk
|
||||||
|
uv run python -m langbot_plugin.cli.__init__ rt --debug-only --ws-control-port 5400 --ws-debug-port 5401 --skip-deps-check
|
||||||
|
```
|
||||||
|
|
||||||
|
Probe plugin: `data/plugins/LangBot__EBAEventProbe` when live credentials are available.
|
||||||
|
|
||||||
|
Adapter live probe:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
uv run python -m py_compile tests/e2e/live_officialaccount_eba_probe.py
|
||||||
|
OFFICIALACCOUNT_TOKEN=... OFFICIALACCOUNT_ENCODING_AES_KEY=... OFFICIALACCOUNT_APP_SECRET=... OFFICIALACCOUNT_APP_ID=... uv run python tests/e2e/live_officialaccount_eba_probe.py
|
||||||
|
```
|
||||||
|
|
||||||
|
Evidence JSONL path: `/home/wgc/LangBotxg/LangBotEbaTest/data/temp/officialaccount_eba_plugin_probe.jsonl` for plugin E2E, or `data/temp/officialaccount_eba_probe.jsonl` for direct adapter live probe.
|
||||||
|
|
||||||
|
Destructive operations: none.
|
||||||
|
|
||||||
|
Blocked items:
|
||||||
|
|
||||||
|
- `plugin-e2e-outbound`: proactive `send_message` is not supported for this adapter; Official Account responses must be produced through the inbound webhook reply window.
|
||||||
|
- Inbound image and voice live UI evidence remains pending; webhook conversion is covered by unit tests.
|
||||||
@@ -93,15 +93,30 @@ class OAClient:
|
|||||||
raise Exception('msg_signature不在请求体中')
|
raise Exception('msg_signature不在请求体中')
|
||||||
|
|
||||||
if req.method == 'GET':
|
if req.method == 'GET':
|
||||||
# 校验签名
|
if msg_signature:
|
||||||
|
wxcpt = WXBizMsgCrypt(self.token, self.aes, self.appid)
|
||||||
|
ret, reply_echo = wxcpt.VerifyURL(msg_signature, timestamp, nonce, echostr)
|
||||||
|
if ret == 0:
|
||||||
|
return reply_echo
|
||||||
|
await self.logger.error(
|
||||||
|
'OfficialAccount encrypted URL verification failed: '
|
||||||
|
f'ret={ret}, timestamp_present={bool(timestamp)}, nonce_present={bool(nonce)}, '
|
||||||
|
f'echostr_present={bool(echostr)}'
|
||||||
|
)
|
||||||
|
|
||||||
|
# Plaintext callback verification.
|
||||||
check_str = ''.join(sorted([self.token, timestamp, nonce]))
|
check_str = ''.join(sorted([self.token, timestamp, nonce]))
|
||||||
check_signature = hashlib.sha1(check_str.encode('utf-8')).hexdigest()
|
check_signature = hashlib.sha1(check_str.encode('utf-8')).hexdigest()
|
||||||
|
|
||||||
if check_signature == signature:
|
if check_signature == signature:
|
||||||
return echostr # 验证成功返回echostr
|
return echostr # 验证成功返回echostr
|
||||||
else:
|
else:
|
||||||
await self.logger.error('拒绝请求')
|
await self.logger.error(
|
||||||
raise Exception('拒绝请求')
|
'OfficialAccount plaintext URL verification failed: '
|
||||||
|
f'signature_present={bool(signature)}, timestamp_present={bool(timestamp)}, '
|
||||||
|
f'nonce_present={bool(nonce)}, echostr_present={bool(echostr)}'
|
||||||
|
)
|
||||||
|
return 'signature verification failed', 403
|
||||||
elif req.method == 'POST':
|
elif req.method == 'POST':
|
||||||
encryt_msg = await req.data
|
encryt_msg = await req.data
|
||||||
wxcpt = WXBizMsgCrypt(self.token, self.aes, self.appid)
|
wxcpt = WXBizMsgCrypt(self.token, self.aes, self.appid)
|
||||||
@@ -279,9 +294,27 @@ class OAClientForLongerResponse:
|
|||||||
raise Exception('msg_signature不在请求体中')
|
raise Exception('msg_signature不在请求体中')
|
||||||
|
|
||||||
if req.method == 'GET':
|
if req.method == 'GET':
|
||||||
|
if msg_signature:
|
||||||
|
wxcpt = WXBizMsgCrypt(self.token, self.aes, self.appid)
|
||||||
|
ret, reply_echo = wxcpt.VerifyURL(msg_signature, timestamp, nonce, echostr)
|
||||||
|
if ret == 0:
|
||||||
|
return reply_echo
|
||||||
|
await self.logger.error(
|
||||||
|
'OfficialAccount encrypted URL verification failed: '
|
||||||
|
f'ret={ret}, timestamp_present={bool(timestamp)}, nonce_present={bool(nonce)}, '
|
||||||
|
f'echostr_present={bool(echostr)}'
|
||||||
|
)
|
||||||
|
|
||||||
check_str = ''.join(sorted([self.token, timestamp, nonce]))
|
check_str = ''.join(sorted([self.token, timestamp, nonce]))
|
||||||
check_signature = hashlib.sha1(check_str.encode('utf-8')).hexdigest()
|
check_signature = hashlib.sha1(check_str.encode('utf-8')).hexdigest()
|
||||||
return echostr if check_signature == signature else '拒绝请求'
|
if check_signature == signature:
|
||||||
|
return echostr
|
||||||
|
await self.logger.error(
|
||||||
|
'OfficialAccount plaintext URL verification failed: '
|
||||||
|
f'signature_present={bool(signature)}, timestamp_present={bool(timestamp)}, '
|
||||||
|
f'nonce_present={bool(nonce)}, echostr_present={bool(echostr)}'
|
||||||
|
)
|
||||||
|
return 'signature verification failed', 403
|
||||||
|
|
||||||
elif req.method == 'POST':
|
elif req.method == 'POST':
|
||||||
encryt_msg = await req.data
|
encryt_msg = await req.data
|
||||||
|
|||||||
@@ -0,0 +1,5 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from langbot.pkg.platform.adapters.officialaccount.adapter import OfficialAccountAdapter
|
||||||
|
|
||||||
|
__all__ = ['OfficialAccountAdapter']
|
||||||
195
src/langbot/pkg/platform/adapters/officialaccount/adapter.py
Normal file
195
src/langbot/pkg/platform/adapters/officialaccount/adapter.py
Normal file
@@ -0,0 +1,195 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
import traceback
|
||||||
|
import typing
|
||||||
|
|
||||||
|
import pydantic
|
||||||
|
|
||||||
|
from langbot.libs.official_account_api.api import OAClient, OAClientForLongerResponse
|
||||||
|
from langbot.libs.official_account_api.oaevent import OAEvent
|
||||||
|
from langbot.pkg.platform.adapters.officialaccount.api_impl import OfficialAccountAPIMixin
|
||||||
|
from langbot.pkg.platform.adapters.officialaccount.event_converter import OfficialAccountEventConverter
|
||||||
|
from langbot.pkg.platform.adapters.officialaccount.errors import NotSupportedError
|
||||||
|
from langbot.pkg.platform.adapters.officialaccount.message_converter import OfficialAccountMessageConverter
|
||||||
|
from langbot.pkg.platform.adapters.officialaccount.platform_api import PLATFORM_API_MAP
|
||||||
|
import langbot_plugin.api.definition.abstract.platform.adapter as abstract_platform_adapter
|
||||||
|
import langbot_plugin.api.definition.abstract.platform.event_logger as abstract_platform_logger
|
||||||
|
from langbot_plugin.api.entities.builtin.platform import entities as platform_entities
|
||||||
|
from langbot_plugin.api.entities.builtin.platform import events as platform_events
|
||||||
|
from langbot_plugin.api.entities.builtin.platform import message as platform_message
|
||||||
|
|
||||||
|
|
||||||
|
class OfficialAccountAdapter(OfficialAccountAPIMixin, abstract_platform_adapter.AbstractPlatformAdapter):
|
||||||
|
bot: typing.Any = pydantic.Field(exclude=True)
|
||||||
|
|
||||||
|
message_converter: OfficialAccountMessageConverter = OfficialAccountMessageConverter()
|
||||||
|
event_converter: OfficialAccountEventConverter = OfficialAccountEventConverter()
|
||||||
|
|
||||||
|
config: dict
|
||||||
|
bot_uuid: str | None = None
|
||||||
|
listeners: dict[
|
||||||
|
typing.Type[platform_events.Event],
|
||||||
|
typing.Callable[[platform_events.Event, abstract_platform_adapter.AbstractMessagePlatformAdapter], None],
|
||||||
|
] = {}
|
||||||
|
_message_cache: dict[str, platform_events.MessageReceivedEvent] = {}
|
||||||
|
_user_cache: dict[str, platform_entities.User] = {}
|
||||||
|
|
||||||
|
class Config:
|
||||||
|
arbitrary_types_allowed = True
|
||||||
|
|
||||||
|
def __init__(self, config: dict, logger: abstract_platform_logger.AbstractEventLogger):
|
||||||
|
required_keys = ['token', 'EncodingAESKey', 'AppSecret', 'AppID', 'Mode']
|
||||||
|
missing_keys = [key for key in required_keys if not config.get(key)]
|
||||||
|
if missing_keys:
|
||||||
|
raise Exception(f'OfficialAccount EBA adapter missing config: {missing_keys}')
|
||||||
|
|
||||||
|
mode = config['Mode']
|
||||||
|
common_kwargs = {
|
||||||
|
'token': config['token'],
|
||||||
|
'EncodingAESKey': config['EncodingAESKey'],
|
||||||
|
'Appsecret': config['AppSecret'],
|
||||||
|
'AppID': config['AppID'],
|
||||||
|
'logger': logger,
|
||||||
|
'unified_mode': True,
|
||||||
|
'api_base_url': config.get('api_base_url', 'https://api.weixin.qq.com'),
|
||||||
|
}
|
||||||
|
if mode == 'drop':
|
||||||
|
bot = OAClient(**common_kwargs)
|
||||||
|
elif mode == 'passive':
|
||||||
|
bot = OAClientForLongerResponse(
|
||||||
|
**common_kwargs,
|
||||||
|
LoadingMessage=config.get('LoadingMessage', ''),
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
raise KeyError('OfficialAccount Mode must be "drop" or "passive"')
|
||||||
|
|
||||||
|
super().__init__(
|
||||||
|
config=config,
|
||||||
|
logger=logger,
|
||||||
|
bot=bot,
|
||||||
|
bot_account_id=config.get('AppID', ''),
|
||||||
|
bot_uuid=None,
|
||||||
|
listeners={},
|
||||||
|
_message_cache={},
|
||||||
|
_user_cache={},
|
||||||
|
)
|
||||||
|
self._register_native_handlers()
|
||||||
|
|
||||||
|
def set_bot_uuid(self, bot_uuid: str):
|
||||||
|
self.bot_uuid = bot_uuid
|
||||||
|
|
||||||
|
def get_supported_events(self) -> list[str]:
|
||||||
|
return [
|
||||||
|
'message.received',
|
||||||
|
'platform.specific',
|
||||||
|
]
|
||||||
|
|
||||||
|
def get_supported_apis(self) -> list[str]:
|
||||||
|
return [
|
||||||
|
'reply_message',
|
||||||
|
'get_message',
|
||||||
|
'get_user_info',
|
||||||
|
'get_friend_list',
|
||||||
|
'call_platform_api',
|
||||||
|
]
|
||||||
|
|
||||||
|
async def send_message(
|
||||||
|
self,
|
||||||
|
target_type: str,
|
||||||
|
target_id: str,
|
||||||
|
message: platform_message.MessageChain,
|
||||||
|
) -> platform_events.MessageResult:
|
||||||
|
raise NotSupportedError('send_message:official_account_requires_inbound_webhook_reply')
|
||||||
|
|
||||||
|
async def reply_message(
|
||||||
|
self,
|
||||||
|
message_source: platform_events.MessageEvent,
|
||||||
|
message: platform_message.MessageChain,
|
||||||
|
quote_origin: bool = False,
|
||||||
|
) -> platform_events.MessageResult:
|
||||||
|
source = await OfficialAccountEventConverter.yiri2target(message_source)
|
||||||
|
if not isinstance(source, OAEvent):
|
||||||
|
raise ValueError('OfficialAccount reply_message requires an OAEvent source object')
|
||||||
|
content = await OfficialAccountMessageConverter.yiri2target(message)
|
||||||
|
if self.config.get('Mode') == 'passive':
|
||||||
|
await self.bot.set_message(source.user_id, source.message_id, content)
|
||||||
|
else:
|
||||||
|
await self.bot.set_message(source.message_id, content)
|
||||||
|
return platform_events.MessageResult(message_id=source.message_id, raw={'queued': True})
|
||||||
|
|
||||||
|
async def call_platform_api(self, action: str, params: dict = {}) -> dict:
|
||||||
|
handler = PLATFORM_API_MAP.get(action)
|
||||||
|
if handler is None:
|
||||||
|
raise NotSupportedError(f'call_platform_api:{action}')
|
||||||
|
params = dict(params or {})
|
||||||
|
params.setdefault('mode', self.config.get('Mode'))
|
||||||
|
return await handler(self.bot, params)
|
||||||
|
|
||||||
|
def register_listener(
|
||||||
|
self,
|
||||||
|
event_type: typing.Type[platform_events.Event],
|
||||||
|
callback: typing.Callable[
|
||||||
|
[platform_events.Event, abstract_platform_adapter.AbstractMessagePlatformAdapter], None
|
||||||
|
],
|
||||||
|
):
|
||||||
|
self.listeners[event_type] = callback
|
||||||
|
|
||||||
|
def unregister_listener(
|
||||||
|
self,
|
||||||
|
event_type: typing.Type[platform_events.Event],
|
||||||
|
callback: typing.Callable[
|
||||||
|
[platform_events.Event, abstract_platform_adapter.AbstractMessagePlatformAdapter], None
|
||||||
|
],
|
||||||
|
):
|
||||||
|
registered = self.listeners.get(event_type)
|
||||||
|
if registered is callback:
|
||||||
|
self.listeners.pop(event_type, None)
|
||||||
|
|
||||||
|
async def handle_unified_webhook(self, bot_uuid: str, path: str, request):
|
||||||
|
return await self.bot.handle_unified_webhook(request)
|
||||||
|
|
||||||
|
async def run_async(self):
|
||||||
|
async def keep_alive():
|
||||||
|
while True:
|
||||||
|
await asyncio.sleep(1)
|
||||||
|
|
||||||
|
await self.logger.info('OfficialAccount EBA adapter running in unified webhook mode')
|
||||||
|
await keep_alive()
|
||||||
|
|
||||||
|
async def kill(self) -> bool:
|
||||||
|
return True
|
||||||
|
|
||||||
|
async def is_muted(self, group_id: int | None = None) -> bool:
|
||||||
|
return False
|
||||||
|
|
||||||
|
def _register_native_handlers(self):
|
||||||
|
for msg_type in ('text', 'image', 'voice', 'event'):
|
||||||
|
self.bot.on_message(msg_type)(self._handle_native_event)
|
||||||
|
|
||||||
|
async def _handle_native_event(self, event: OAEvent):
|
||||||
|
self.bot_account_id = event.receiver_id or self.bot_account_id
|
||||||
|
try:
|
||||||
|
if platform_events.FriendMessage in self.listeners:
|
||||||
|
legacy_event = await self.event_converter.target2legacy(event)
|
||||||
|
if legacy_event and platform_events.FriendMessage in self.listeners:
|
||||||
|
await self.listeners[platform_events.FriendMessage](legacy_event, self)
|
||||||
|
|
||||||
|
eba_event = await self.event_converter.target2yiri(event)
|
||||||
|
if eba_event:
|
||||||
|
self._cache_event(eba_event)
|
||||||
|
await self._dispatch_eba_event(eba_event)
|
||||||
|
except Exception:
|
||||||
|
await self.logger.error(f'Error in officialaccount native event: {traceback.format_exc()}')
|
||||||
|
|
||||||
|
async def _dispatch_eba_event(self, event: platform_events.EBAEvent):
|
||||||
|
for event_type in (type(event), platform_events.EBAEvent, platform_events.Event):
|
||||||
|
callback = self.listeners.get(event_type)
|
||||||
|
if callback:
|
||||||
|
await callback(event, self)
|
||||||
|
return
|
||||||
|
|
||||||
|
def _cache_event(self, event: platform_events.Event):
|
||||||
|
if isinstance(event, platform_events.MessageReceivedEvent):
|
||||||
|
self._message_cache[str(event.message_id)] = event
|
||||||
|
self._user_cache[str(event.sender.id)] = event.sender
|
||||||
@@ -0,0 +1,85 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import typing
|
||||||
|
|
||||||
|
from langbot_plugin.api.entities.builtin.platform import entities as platform_entities
|
||||||
|
from langbot_plugin.api.entities.builtin.platform import events as platform_events
|
||||||
|
from langbot_plugin.api.entities.builtin.platform import message as platform_message
|
||||||
|
from langbot.pkg.platform.adapters.officialaccount.errors import NotSupportedError
|
||||||
|
|
||||||
|
|
||||||
|
class OfficialAccountAPIMixin:
|
||||||
|
_message_cache: dict[str, platform_events.MessageReceivedEvent]
|
||||||
|
_user_cache: dict[str, platform_entities.User]
|
||||||
|
|
||||||
|
async def get_message(
|
||||||
|
self,
|
||||||
|
chat_type: str,
|
||||||
|
chat_id: typing.Union[int, str],
|
||||||
|
message_id: typing.Union[int, str],
|
||||||
|
) -> platform_events.MessageReceivedEvent:
|
||||||
|
event = self._message_cache.get(str(message_id))
|
||||||
|
if event is None:
|
||||||
|
raise NotSupportedError('get_message:message_not_cached')
|
||||||
|
return event
|
||||||
|
|
||||||
|
async def get_user_info(self, user_id: typing.Union[int, str]) -> platform_entities.User:
|
||||||
|
user = self._user_cache.get(str(user_id))
|
||||||
|
if user is None:
|
||||||
|
raise NotSupportedError('get_user_info:not_cached')
|
||||||
|
return user
|
||||||
|
|
||||||
|
async def get_friend_list(self) -> list[platform_entities.User]:
|
||||||
|
return list(self._user_cache.values())
|
||||||
|
|
||||||
|
async def edit_message(
|
||||||
|
self,
|
||||||
|
chat_type: str,
|
||||||
|
chat_id: typing.Union[int, str],
|
||||||
|
message_id: typing.Union[int, str],
|
||||||
|
new_content: platform_message.MessageChain,
|
||||||
|
) -> None:
|
||||||
|
raise NotSupportedError('edit_message')
|
||||||
|
|
||||||
|
async def delete_message(
|
||||||
|
self,
|
||||||
|
chat_type: str,
|
||||||
|
chat_id: typing.Union[int, str],
|
||||||
|
message_id: typing.Union[int, str],
|
||||||
|
) -> None:
|
||||||
|
raise NotSupportedError('delete_message')
|
||||||
|
|
||||||
|
async def forward_message(
|
||||||
|
self,
|
||||||
|
from_chat_type: str,
|
||||||
|
from_chat_id: typing.Union[int, str],
|
||||||
|
message_id: typing.Union[int, str],
|
||||||
|
to_chat_type: str,
|
||||||
|
to_chat_id: typing.Union[int, str],
|
||||||
|
) -> platform_events.MessageResult:
|
||||||
|
raise NotSupportedError('forward_message')
|
||||||
|
|
||||||
|
async def upload_file(self, file_data: bytes, filename: str) -> str:
|
||||||
|
raise NotSupportedError('upload_file')
|
||||||
|
|
||||||
|
async def get_file_url(self, file_id: str) -> str:
|
||||||
|
raise NotSupportedError('get_file_url')
|
||||||
|
|
||||||
|
async def get_group_info(self, group_id: typing.Union[int, str]) -> platform_entities.UserGroup:
|
||||||
|
raise NotSupportedError('get_group_info')
|
||||||
|
|
||||||
|
async def get_group_list(self) -> list[platform_entities.UserGroup]:
|
||||||
|
raise NotSupportedError('get_group_list')
|
||||||
|
|
||||||
|
async def get_group_member_list(
|
||||||
|
self,
|
||||||
|
group_id: typing.Union[int, str],
|
||||||
|
) -> list[platform_entities.UserGroupMember]:
|
||||||
|
raise NotSupportedError('get_group_member_list')
|
||||||
|
|
||||||
|
async def get_group_member_info(
|
||||||
|
self,
|
||||||
|
group_id: typing.Union[int, str],
|
||||||
|
user_id: typing.Union[int, str],
|
||||||
|
) -> platform_entities.UserGroupMember:
|
||||||
|
raise NotSupportedError('get_group_member_info')
|
||||||
10
src/langbot/pkg/platform/adapters/officialaccount/errors.py
Normal file
10
src/langbot/pkg/platform/adapters/officialaccount/errors.py
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
try:
|
||||||
|
from langbot_plugin.api.entities.builtin.platform.errors import NotSupportedError
|
||||||
|
except ModuleNotFoundError:
|
||||||
|
|
||||||
|
class NotSupportedError(Exception):
|
||||||
|
def __init__(self, api_name: str, *args):
|
||||||
|
super().__init__(f"API '{api_name}' is not supported by this adapter", *args)
|
||||||
|
self.api_name = api_name
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import time
|
||||||
|
import typing
|
||||||
|
|
||||||
|
from langbot.libs.official_account_api.oaevent import OAEvent
|
||||||
|
from langbot.pkg.platform.adapters.officialaccount.message_converter import OfficialAccountMessageConverter
|
||||||
|
from langbot.pkg.platform.adapters.officialaccount.types import ADAPTER_NAME
|
||||||
|
import langbot_plugin.api.definition.abstract.platform.adapter as abstract_platform_adapter
|
||||||
|
from langbot_plugin.api.entities.builtin.platform import entities as platform_entities
|
||||||
|
from langbot_plugin.api.entities.builtin.platform import events as platform_events
|
||||||
|
|
||||||
|
|
||||||
|
class OfficialAccountEventConverter(abstract_platform_adapter.AbstractEventConverter):
|
||||||
|
@staticmethod
|
||||||
|
async def yiri2target(event: platform_events.Event) -> typing.Any:
|
||||||
|
return getattr(event, 'source_platform_object', None)
|
||||||
|
|
||||||
|
async def target2legacy(self, event: OAEvent) -> platform_events.FriendMessage | None:
|
||||||
|
eba_event = await self.target2yiri(event)
|
||||||
|
if not isinstance(eba_event, platform_events.MessageReceivedEvent):
|
||||||
|
return None
|
||||||
|
return platform_events.FriendMessage(
|
||||||
|
sender=platform_entities.Friend(
|
||||||
|
id=eba_event.sender.id,
|
||||||
|
nickname=eba_event.sender.nickname,
|
||||||
|
remark='',
|
||||||
|
),
|
||||||
|
message_chain=eba_event.message_chain,
|
||||||
|
time=eba_event.timestamp,
|
||||||
|
source_platform_object=event,
|
||||||
|
)
|
||||||
|
|
||||||
|
async def target2yiri(self, event: OAEvent) -> platform_events.Event | None:
|
||||||
|
if event.type in {'text', 'image', 'voice'}:
|
||||||
|
return await self.message_to_eba(event)
|
||||||
|
return self.platform_specific(event, f'officialaccount.{event.detail_type or event.type or "unknown"}')
|
||||||
|
|
||||||
|
async def message_to_eba(self, event: OAEvent) -> platform_events.MessageReceivedEvent:
|
||||||
|
sender_id = event.user_id or ''
|
||||||
|
timestamp = float(event.timestamp or time.time())
|
||||||
|
return platform_events.MessageReceivedEvent(
|
||||||
|
type='message.received',
|
||||||
|
adapter_name=ADAPTER_NAME,
|
||||||
|
message_id=event.message_id or f'{sender_id}:{int(timestamp)}',
|
||||||
|
message_chain=await OfficialAccountMessageConverter.target2yiri(event),
|
||||||
|
sender=platform_entities.User(
|
||||||
|
id=sender_id,
|
||||||
|
nickname=sender_id,
|
||||||
|
),
|
||||||
|
chat_type=platform_entities.ChatType.PRIVATE,
|
||||||
|
chat_id=sender_id,
|
||||||
|
timestamp=timestamp,
|
||||||
|
source_platform_object=event,
|
||||||
|
)
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def platform_specific(event: OAEvent, action: str) -> platform_events.PlatformSpecificEvent:
|
||||||
|
return platform_events.PlatformSpecificEvent(
|
||||||
|
type='platform.specific',
|
||||||
|
adapter_name=ADAPTER_NAME,
|
||||||
|
action=action,
|
||||||
|
data=dict(event),
|
||||||
|
timestamp=float(event.timestamp or time.time()),
|
||||||
|
source_platform_object=event,
|
||||||
|
)
|
||||||
123
src/langbot/pkg/platform/adapters/officialaccount/manifest.yaml
Normal file
123
src/langbot/pkg/platform/adapters/officialaccount/manifest.yaml
Normal file
@@ -0,0 +1,123 @@
|
|||||||
|
apiVersion: v1
|
||||||
|
kind: MessagePlatformAdapter
|
||||||
|
|
||||||
|
metadata:
|
||||||
|
name: officialaccount-eba
|
||||||
|
label:
|
||||||
|
en_US: Official Account (EBA)
|
||||||
|
zh_Hans: 微信公众号 (EBA)
|
||||||
|
zh_Hant: 微信公眾號 (EBA)
|
||||||
|
description:
|
||||||
|
en_US: WeChat Official Account adapter with Event-Based Agents support
|
||||||
|
zh_Hans: 微信公众号适配器(EBA 架构版本),通过统一 Webhook 接收公众号消息
|
||||||
|
zh_Hant: 微信公眾號適配器(EBA 架構版本),透過統一 Webhook 接收公眾號訊息
|
||||||
|
icon: officialaccount.png
|
||||||
|
|
||||||
|
spec:
|
||||||
|
categories:
|
||||||
|
- china
|
||||||
|
help_links:
|
||||||
|
zh: https://link.langbot.app/zh/platforms/officialaccount
|
||||||
|
en: https://link.langbot.app/en/platforms/officialaccount
|
||||||
|
ja: https://link.langbot.app/ja/platforms/officialaccount
|
||||||
|
config:
|
||||||
|
- name: webhook_url
|
||||||
|
label:
|
||||||
|
en_US: Webhook Callback URL
|
||||||
|
zh_Hans: Webhook 回调地址
|
||||||
|
zh_Hant: Webhook 回調地址
|
||||||
|
description:
|
||||||
|
en_US: Copy this URL and paste it into your Official Account webhook configuration.
|
||||||
|
zh_Hans: 复制此地址并粘贴到微信公众号的 Webhook 配置中。
|
||||||
|
zh_Hant: 複製此地址並貼到微信公眾號的 Webhook 設定中。
|
||||||
|
type: webhook-url
|
||||||
|
required: false
|
||||||
|
default: ""
|
||||||
|
- name: token
|
||||||
|
label:
|
||||||
|
en_US: Token
|
||||||
|
zh_Hans: 令牌
|
||||||
|
zh_Hant: 令牌
|
||||||
|
type: string
|
||||||
|
required: true
|
||||||
|
default: ""
|
||||||
|
- name: EncodingAESKey
|
||||||
|
label:
|
||||||
|
en_US: EncodingAESKey
|
||||||
|
zh_Hans: 消息加解密密钥
|
||||||
|
zh_Hant: 訊息加解密密鑰
|
||||||
|
type: string
|
||||||
|
required: true
|
||||||
|
default: ""
|
||||||
|
- name: AppID
|
||||||
|
label:
|
||||||
|
en_US: App ID
|
||||||
|
zh_Hans: 应用 ID
|
||||||
|
zh_Hant: 應用 ID
|
||||||
|
type: string
|
||||||
|
required: true
|
||||||
|
default: ""
|
||||||
|
- name: AppSecret
|
||||||
|
label:
|
||||||
|
en_US: App Secret
|
||||||
|
zh_Hans: 应用密钥
|
||||||
|
zh_Hant: 應用密鑰
|
||||||
|
type: string
|
||||||
|
required: true
|
||||||
|
default: ""
|
||||||
|
- name: Mode
|
||||||
|
label:
|
||||||
|
en_US: Mode
|
||||||
|
zh_Hans: 接入模式
|
||||||
|
zh_Hant: 接入模式
|
||||||
|
description:
|
||||||
|
en_US: "drop replies within the current callback; passive returns a loading message first and queues the real reply for the user's next message."
|
||||||
|
zh_Hans: "drop 会在当前回调内等待回复;passive 会先返回加载提示,并将真实回复排队到用户下一条消息。"
|
||||||
|
zh_Hant: "drop 會在目前回調內等待回覆;passive 會先回傳載入提示,並將真實回覆排隊到使用者下一則訊息。"
|
||||||
|
type: string
|
||||||
|
required: true
|
||||||
|
default: "drop"
|
||||||
|
- name: LoadingMessage
|
||||||
|
label:
|
||||||
|
en_US: Loading Message
|
||||||
|
zh_Hans: 加载消息
|
||||||
|
zh_Hant: 載入訊息
|
||||||
|
type: string
|
||||||
|
required: false
|
||||||
|
default: "AI正在思考中,请发送任意内容获取回复。"
|
||||||
|
- name: api_base_url
|
||||||
|
label:
|
||||||
|
en_US: API Base URL
|
||||||
|
zh_Hans: API 基础 URL
|
||||||
|
zh_Hant: API 基礎 URL
|
||||||
|
description:
|
||||||
|
en_US: Optional Official Account API base URL, useful when routing through a reverse proxy.
|
||||||
|
zh_Hans: 可选,若通过反向代理访问微信公众号 API,可修改此项。
|
||||||
|
zh_Hant: 可選,若透過反向代理存取微信公眾號 API,可修改此項。
|
||||||
|
type: string
|
||||||
|
required: false
|
||||||
|
default: "https://api.weixin.qq.com"
|
||||||
|
|
||||||
|
supported_events:
|
||||||
|
- message.received
|
||||||
|
- platform.specific
|
||||||
|
|
||||||
|
supported_apis:
|
||||||
|
required:
|
||||||
|
- reply_message
|
||||||
|
optional:
|
||||||
|
- get_message
|
||||||
|
- get_user_info
|
||||||
|
- get_friend_list
|
||||||
|
- call_platform_api
|
||||||
|
|
||||||
|
platform_specific_apis:
|
||||||
|
- action: get_mode
|
||||||
|
description: { en_US: "Return the configured Official Account reply mode", zh_Hans: "返回当前微信公众号回复模式" }
|
||||||
|
- action: get_cached_response_status
|
||||||
|
description: { en_US: "Inspect cached passive/drop reply state for diagnostics", zh_Hans: "查看被动回复缓存状态,用于诊断" }
|
||||||
|
|
||||||
|
execution:
|
||||||
|
python:
|
||||||
|
path: ./adapter.py
|
||||||
|
attr: OfficialAccountAdapter
|
||||||
@@ -0,0 +1,72 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import datetime
|
||||||
|
|
||||||
|
from langbot.libs.official_account_api.oaevent import OAEvent
|
||||||
|
import langbot_plugin.api.definition.abstract.platform.adapter as abstract_platform_adapter
|
||||||
|
from langbot_plugin.api.entities.builtin.platform import message as platform_message
|
||||||
|
|
||||||
|
|
||||||
|
class OfficialAccountMessageConverter(abstract_platform_adapter.AbstractMessageConverter):
|
||||||
|
@staticmethod
|
||||||
|
async def yiri2target(message_chain: platform_message.MessageChain) -> str:
|
||||||
|
content_parts: list[str] = []
|
||||||
|
for component in message_chain:
|
||||||
|
if isinstance(component, platform_message.Source):
|
||||||
|
continue
|
||||||
|
if isinstance(component, platform_message.Plain):
|
||||||
|
content_parts.append(component.text)
|
||||||
|
elif isinstance(component, platform_message.At):
|
||||||
|
content_parts.append(f'@{component.display or component.target}')
|
||||||
|
elif isinstance(component, platform_message.AtAll):
|
||||||
|
content_parts.append('@all')
|
||||||
|
elif isinstance(component, platform_message.Image):
|
||||||
|
content_parts.append('[Image]')
|
||||||
|
elif isinstance(component, platform_message.Voice):
|
||||||
|
content_parts.append('[Voice]')
|
||||||
|
elif isinstance(component, platform_message.File):
|
||||||
|
content_parts.append(f'[File: {component.name or component.id or component.url or "file"}]')
|
||||||
|
elif isinstance(component, platform_message.Quote):
|
||||||
|
if component.id is not None:
|
||||||
|
content_parts.append(f'[Quote {component.id}]')
|
||||||
|
if component.origin:
|
||||||
|
content_parts.append(await OfficialAccountMessageConverter.yiri2target(component.origin))
|
||||||
|
elif isinstance(component, platform_message.Forward):
|
||||||
|
for node in component.node_list:
|
||||||
|
if node.message_chain:
|
||||||
|
content_parts.append(await OfficialAccountMessageConverter.yiri2target(node.message_chain))
|
||||||
|
else:
|
||||||
|
content_parts.append(str(component))
|
||||||
|
return '\n'.join(part for part in content_parts if part)
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
async def target2yiri(event: OAEvent) -> platform_message.MessageChain:
|
||||||
|
timestamp = event.timestamp or int(datetime.datetime.now().timestamp())
|
||||||
|
components: list[platform_message.MessageComponent] = [
|
||||||
|
platform_message.Source(
|
||||||
|
id=event.message_id or f'{event.user_id}:{timestamp}',
|
||||||
|
time=datetime.datetime.fromtimestamp(timestamp),
|
||||||
|
)
|
||||||
|
]
|
||||||
|
|
||||||
|
if event.type == 'text' and event.message:
|
||||||
|
components.append(platform_message.Plain(text=event.message))
|
||||||
|
elif event.type == 'image':
|
||||||
|
image_kwargs = {}
|
||||||
|
if event.picurl:
|
||||||
|
image_kwargs['url'] = event.picurl
|
||||||
|
if event.media_id:
|
||||||
|
image_kwargs['image_id'] = event.media_id
|
||||||
|
if image_kwargs:
|
||||||
|
components.append(platform_message.Image(**image_kwargs))
|
||||||
|
elif event.type == 'voice':
|
||||||
|
if event.media_id:
|
||||||
|
components.append(platform_message.Voice(voice_id=event.media_id))
|
||||||
|
else:
|
||||||
|
components.append(platform_message.Unknown(text='[officialaccount voice message without media id]'))
|
||||||
|
elif event.type == 'event':
|
||||||
|
components.append(platform_message.Unknown(text=f'[officialaccount event: {event.detail_type or "unknown"}]'))
|
||||||
|
else:
|
||||||
|
components.append(platform_message.Unknown(text=f'[unsupported officialaccount msgtype: {event.type or "unknown"}]'))
|
||||||
|
|
||||||
|
return platform_message.MessageChain(components)
|
||||||
Binary file not shown.
|
After Width: | Height: | Size: 1.9 KiB |
@@ -0,0 +1,27 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import typing
|
||||||
|
|
||||||
|
|
||||||
|
async def get_mode(bot, params: dict) -> dict:
|
||||||
|
return {
|
||||||
|
'mode': params.get('mode') or ('passive' if hasattr(bot, 'msg_queue') else 'drop'),
|
||||||
|
'longer_response': hasattr(bot, 'msg_queue'),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
async def get_cached_response_status(bot, params: dict) -> dict:
|
||||||
|
message_id = params.get('message_id') or params.get('msg_id')
|
||||||
|
user_id = params.get('user_id') or params.get('from_user')
|
||||||
|
if hasattr(bot, 'generated_content'):
|
||||||
|
return {'pending': str(message_id) in {str(key) for key in bot.generated_content}}
|
||||||
|
if hasattr(bot, 'msg_queue'):
|
||||||
|
queue = bot.msg_queue.get(str(user_id), []) if user_id is not None else []
|
||||||
|
return {'queued': len(queue)}
|
||||||
|
return {'pending': False}
|
||||||
|
|
||||||
|
|
||||||
|
PLATFORM_API_MAP: dict[str, typing.Callable[[typing.Any, dict], typing.Awaitable[dict]]] = {
|
||||||
|
'get_mode': get_mode,
|
||||||
|
'get_cached_response_status': get_cached_response_status,
|
||||||
|
}
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
ADAPTER_NAME = 'officialaccount-eba'
|
||||||
158
tests/e2e/live_officialaccount_eba_probe.py
Normal file
158
tests/e2e/live_officialaccount_eba_probe.py
Normal file
@@ -0,0 +1,158 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import asyncio
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from quart import Quart, request
|
||||||
|
|
||||||
|
from langbot.pkg.platform.adapters.officialaccount.adapter import OfficialAccountAdapter
|
||||||
|
from langbot_plugin.api.definition.abstract.platform.event_logger import AbstractEventLogger
|
||||||
|
from langbot_plugin.api.entities.builtin.platform import events as platform_events
|
||||||
|
from langbot_plugin.api.entities.builtin.platform import message as platform_message
|
||||||
|
|
||||||
|
|
||||||
|
class ProbeLogger(AbstractEventLogger):
|
||||||
|
async def info(self, text, images=None, message_session_id=None, no_throw=True):
|
||||||
|
print(f'[info] {text}')
|
||||||
|
|
||||||
|
async def debug(self, text, images=None, message_session_id=None, no_throw=True):
|
||||||
|
print(f'[debug] {text}')
|
||||||
|
|
||||||
|
async def warning(self, text, images=None, message_session_id=None, no_throw=True):
|
||||||
|
print(f'[warning] {text}')
|
||||||
|
|
||||||
|
async def error(self, text, images=None, message_session_id=None, no_throw=True):
|
||||||
|
print(f'[error] {text}')
|
||||||
|
|
||||||
|
|
||||||
|
def redact(value: Any) -> Any:
|
||||||
|
if isinstance(value, dict):
|
||||||
|
return {
|
||||||
|
key: '<redacted>' if key.lower() in {'secret', 'token', 'encodingaeskey', 'encrypt', 'appsecret'} else redact(item)
|
||||||
|
for key, item in value.items()
|
||||||
|
}
|
||||||
|
if isinstance(value, list):
|
||||||
|
return [redact(item) for item in value]
|
||||||
|
return value
|
||||||
|
|
||||||
|
|
||||||
|
def summarize_event(event: platform_events.EBAEvent) -> dict:
|
||||||
|
data = {
|
||||||
|
'type': event.type,
|
||||||
|
'adapter_name': event.adapter_name,
|
||||||
|
'timestamp': event.timestamp,
|
||||||
|
}
|
||||||
|
for field in ('message_id', 'chat_id', 'chat_type', 'action', 'data'):
|
||||||
|
if hasattr(event, field):
|
||||||
|
value = getattr(event, field)
|
||||||
|
if hasattr(value, 'value'):
|
||||||
|
value = value.value
|
||||||
|
data[field] = redact(value)
|
||||||
|
if hasattr(event, 'sender') and event.sender is not None:
|
||||||
|
data['sender'] = event.sender.model_dump()
|
||||||
|
if hasattr(event, 'message_chain') and event.message_chain is not None:
|
||||||
|
data['message_chain'] = event.message_chain.model_dump()
|
||||||
|
return data
|
||||||
|
|
||||||
|
|
||||||
|
def record_api(results: list[dict[str, Any]], name: str, ok: bool, result: Any = None, error: Exception | None = None):
|
||||||
|
entry = {'name': name, 'ok': ok}
|
||||||
|
if result is not None:
|
||||||
|
entry['result'] = redact(result)
|
||||||
|
if error is not None:
|
||||||
|
entry['error'] = repr(error)
|
||||||
|
results.append(entry)
|
||||||
|
print('OFFICIALACCOUNT_EBA_API', json.dumps(entry, ensure_ascii=False, default=str))
|
||||||
|
|
||||||
|
|
||||||
|
async def run_api(results: list[dict[str, Any]], name: str, func):
|
||||||
|
try:
|
||||||
|
result = await func()
|
||||||
|
record_api(results, name, True, result)
|
||||||
|
return result
|
||||||
|
except Exception as exc:
|
||||||
|
record_api(results, name, False, error=exc)
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def config_from_env() -> dict:
|
||||||
|
config = {
|
||||||
|
'token': os.getenv('OFFICIALACCOUNT_TOKEN', ''),
|
||||||
|
'EncodingAESKey': os.getenv('OFFICIALACCOUNT_ENCODING_AES_KEY', ''),
|
||||||
|
'AppSecret': os.getenv('OFFICIALACCOUNT_APP_SECRET', ''),
|
||||||
|
'AppID': os.getenv('OFFICIALACCOUNT_APP_ID', ''),
|
||||||
|
'Mode': os.getenv('OFFICIALACCOUNT_MODE', 'drop'),
|
||||||
|
'LoadingMessage': os.getenv('OFFICIALACCOUNT_LOADING_MESSAGE', 'AI正在思考中,请发送任意内容获取回复。'),
|
||||||
|
'api_base_url': os.getenv('OFFICIALACCOUNT_API_BASE_URL', 'https://api.weixin.qq.com'),
|
||||||
|
}
|
||||||
|
missing = [key for key in ('token', 'EncodingAESKey', 'AppSecret', 'AppID', 'Mode') if not config.get(key)]
|
||||||
|
if missing:
|
||||||
|
raise RuntimeError(f'Missing required OfficialAccount env vars for fields: {missing}')
|
||||||
|
return config
|
||||||
|
|
||||||
|
|
||||||
|
async def run_probe(args: argparse.Namespace):
|
||||||
|
adapter = OfficialAccountAdapter(config_from_env(), ProbeLogger())
|
||||||
|
events: list[platform_events.EBAEvent] = []
|
||||||
|
api_results: list[dict[str, Any]] = []
|
||||||
|
first_message = asyncio.Event()
|
||||||
|
log_path = Path(args.log)
|
||||||
|
log_path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
|
||||||
|
async def listener(event, adapter):
|
||||||
|
events.append(event)
|
||||||
|
with log_path.open('a', encoding='utf-8') as fp:
|
||||||
|
fp.write(json.dumps(summarize_event(event), ensure_ascii=False, default=str) + '\n')
|
||||||
|
print('OFFICIALACCOUNT_EBA_EVENT', json.dumps(summarize_event(event), ensure_ascii=False, default=str))
|
||||||
|
if isinstance(event, platform_events.MessageReceivedEvent):
|
||||||
|
first_message.set()
|
||||||
|
|
||||||
|
adapter.register_listener(platform_events.EBAEvent, listener)
|
||||||
|
|
||||||
|
app = Quart(__name__)
|
||||||
|
|
||||||
|
@app.route('/callback', methods=['GET', 'POST'])
|
||||||
|
async def callback():
|
||||||
|
return await adapter.handle_unified_webhook('probe', '', request)
|
||||||
|
|
||||||
|
server_task = asyncio.create_task(app.run_task(host=args.host, port=args.port))
|
||||||
|
try:
|
||||||
|
await asyncio.wait_for(first_message.wait(), timeout=args.timeout)
|
||||||
|
first = next(event for event in events if isinstance(event, platform_events.MessageReceivedEvent))
|
||||||
|
await run_api(api_results, 'reply_message', lambda: adapter.reply_message(first, platform_message.MessageChain([platform_message.Plain(text=args.reply_text)])))
|
||||||
|
await run_api(api_results, 'get_message', lambda: adapter.get_message(first.chat_type.value, first.chat_id, first.message_id))
|
||||||
|
await run_api(api_results, 'get_user_info', lambda: adapter.get_user_info(first.sender.id))
|
||||||
|
await run_api(api_results, 'get_friend_list', adapter.get_friend_list)
|
||||||
|
await run_api(api_results, 'call_platform_api.get_mode', lambda: adapter.call_platform_api('get_mode', {}))
|
||||||
|
finally:
|
||||||
|
server_task.cancel()
|
||||||
|
try:
|
||||||
|
await server_task
|
||||||
|
except asyncio.CancelledError:
|
||||||
|
pass
|
||||||
|
|
||||||
|
summary = {
|
||||||
|
'events': [event.type for event in events],
|
||||||
|
'api_results': api_results,
|
||||||
|
'log': str(log_path),
|
||||||
|
}
|
||||||
|
print('OFFICIALACCOUNT_EBA_SUMMARY', json.dumps(summary, ensure_ascii=False, default=str))
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
parser = argparse.ArgumentParser(description='Live OfficialAccount EBA adapter probe')
|
||||||
|
parser.add_argument('--host', default='127.0.0.1')
|
||||||
|
parser.add_argument('--port', type=int, default=5311)
|
||||||
|
parser.add_argument('--timeout', type=float, default=300)
|
||||||
|
parser.add_argument('--log', default='data/temp/officialaccount_eba_probe.jsonl')
|
||||||
|
parser.add_argument('--reply-text', default='OfficialAccount EBA probe reply')
|
||||||
|
args = parser.parse_args()
|
||||||
|
asyncio.run(run_probe(args))
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
main()
|
||||||
213
tests/unit_tests/platform/test_officialaccount_eba_adapter.py
Normal file
213
tests/unit_tests/platform/test_officialaccount_eba_adapter.py
Normal file
@@ -0,0 +1,213 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import pathlib
|
||||||
|
from unittest.mock import AsyncMock, patch
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
import yaml
|
||||||
|
|
||||||
|
from langbot.libs.official_account_api.oaevent import OAEvent
|
||||||
|
from langbot.pkg.platform.adapters.officialaccount.adapter import OfficialAccountAdapter
|
||||||
|
from langbot.pkg.platform.adapters.officialaccount.errors import NotSupportedError
|
||||||
|
from langbot.pkg.platform.adapters.officialaccount.event_converter import OfficialAccountEventConverter
|
||||||
|
from langbot.pkg.platform.adapters.officialaccount.message_converter import OfficialAccountMessageConverter
|
||||||
|
from langbot.pkg.platform.adapters.officialaccount.platform_api import PLATFORM_API_MAP
|
||||||
|
from langbot_plugin.api.definition.abstract.platform.event_logger import AbstractEventLogger
|
||||||
|
from langbot_plugin.api.entities.builtin.platform import entities as platform_entities
|
||||||
|
from langbot_plugin.api.entities.builtin.platform import events as platform_events
|
||||||
|
from langbot_plugin.api.entities.builtin.platform import message as platform_message
|
||||||
|
|
||||||
|
|
||||||
|
class DummyLogger(AbstractEventLogger):
|
||||||
|
async def info(self, text, images=None, message_session_id=None, no_throw=True):
|
||||||
|
pass
|
||||||
|
|
||||||
|
async def debug(self, text, images=None, message_session_id=None, no_throw=True):
|
||||||
|
pass
|
||||||
|
|
||||||
|
async def warning(self, text, images=None, message_session_id=None, no_throw=True):
|
||||||
|
pass
|
||||||
|
|
||||||
|
async def error(self, text, images=None, message_session_id=None, no_throw=True):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class DummyOAClient:
|
||||||
|
def __init__(self, *args, **kwargs):
|
||||||
|
self.token = kwargs['token']
|
||||||
|
self.aes = kwargs['EncodingAESKey']
|
||||||
|
self.appid = kwargs['AppID']
|
||||||
|
self.appsecret = kwargs['Appsecret']
|
||||||
|
self.base_url = kwargs.get('api_base_url')
|
||||||
|
self._message_handlers = {}
|
||||||
|
self.generated_content = {}
|
||||||
|
self.handle_unified_webhook = AsyncMock(return_value='success')
|
||||||
|
self.set_message = AsyncMock(return_value=None)
|
||||||
|
|
||||||
|
def on_message(self, msg_type: str):
|
||||||
|
def decorator(func):
|
||||||
|
self._message_handlers.setdefault(msg_type, []).append(func)
|
||||||
|
return func
|
||||||
|
|
||||||
|
return decorator
|
||||||
|
|
||||||
|
|
||||||
|
class DummyLongerOAClient(DummyOAClient):
|
||||||
|
def __init__(self, *args, **kwargs):
|
||||||
|
super().__init__(*args, **kwargs)
|
||||||
|
self.loading_message = kwargs['LoadingMessage']
|
||||||
|
self.msg_queue = {}
|
||||||
|
|
||||||
|
|
||||||
|
def manifest() -> dict:
|
||||||
|
manifest_path = (
|
||||||
|
pathlib.Path(__file__).parents[3]
|
||||||
|
/ 'src'
|
||||||
|
/ 'langbot'
|
||||||
|
/ 'pkg'
|
||||||
|
/ 'platform'
|
||||||
|
/ 'adapters'
|
||||||
|
/ 'officialaccount'
|
||||||
|
/ 'manifest.yaml'
|
||||||
|
)
|
||||||
|
return yaml.safe_load(manifest_path.read_text())
|
||||||
|
|
||||||
|
|
||||||
|
def make_adapter(mode: str = 'drop') -> OfficialAccountAdapter:
|
||||||
|
config = {
|
||||||
|
'token': 'token',
|
||||||
|
'EncodingAESKey': 'encoding-key',
|
||||||
|
'AppSecret': 'secret',
|
||||||
|
'AppID': 'app-id',
|
||||||
|
'Mode': mode,
|
||||||
|
'LoadingMessage': 'loading',
|
||||||
|
}
|
||||||
|
with (
|
||||||
|
patch('langbot.pkg.platform.adapters.officialaccount.adapter.OAClient', DummyOAClient),
|
||||||
|
patch('langbot.pkg.platform.adapters.officialaccount.adapter.OAClientForLongerResponse', DummyLongerOAClient),
|
||||||
|
):
|
||||||
|
return OfficialAccountAdapter(config, DummyLogger())
|
||||||
|
|
||||||
|
|
||||||
|
def oa_event(**overrides) -> OAEvent:
|
||||||
|
payload = {
|
||||||
|
'ToUserName': overrides.get('to_user', 'gh_app'),
|
||||||
|
'FromUserName': overrides.get('from_user', 'openid-1'),
|
||||||
|
'CreateTime': overrides.get('timestamp', 1710000000),
|
||||||
|
'MsgType': overrides.get('msgtype', 'text'),
|
||||||
|
'Content': overrides.get('content', 'hello'),
|
||||||
|
'MsgId': overrides.get('message_id', 123),
|
||||||
|
}
|
||||||
|
if payload['MsgType'] == 'image':
|
||||||
|
payload.update({'PicUrl': 'https://example.test/a.jpg', 'MediaId': 'media-1', 'Content': None})
|
||||||
|
if payload['MsgType'] == 'voice':
|
||||||
|
payload.update({'MediaId': 'voice-1', 'Content': None})
|
||||||
|
if payload['MsgType'] == 'event':
|
||||||
|
payload.update({'Event': overrides.get('event', 'subscribe'), 'EventKey': 'qrscene_1', 'Content': None})
|
||||||
|
return OAEvent(payload)
|
||||||
|
|
||||||
|
|
||||||
|
def test_officialaccount_supported_events_match_manifest():
|
||||||
|
assert make_adapter().get_supported_events() == manifest()['spec']['supported_events']
|
||||||
|
|
||||||
|
|
||||||
|
def test_officialaccount_supported_apis_match_manifest():
|
||||||
|
supported_apis = make_adapter().get_supported_apis()
|
||||||
|
manifest_apis = manifest()['spec']['supported_apis']
|
||||||
|
|
||||||
|
assert supported_apis == manifest_apis['required'] + manifest_apis['optional']
|
||||||
|
|
||||||
|
|
||||||
|
def test_officialaccount_platform_api_map_matches_manifest():
|
||||||
|
manifest_actions = {item['action'] for item in manifest()['spec']['platform_specific_apis']}
|
||||||
|
|
||||||
|
assert set(PLATFORM_API_MAP) == manifest_actions
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_officialaccount_message_converter_maps_components_to_passive_text():
|
||||||
|
content = await OfficialAccountMessageConverter.yiri2target(
|
||||||
|
platform_message.MessageChain(
|
||||||
|
[
|
||||||
|
platform_message.Plain(text='hi'),
|
||||||
|
platform_message.Image(url='https://example.test/a.png'),
|
||||||
|
platform_message.File(name='a.txt', url='https://example.test/a.txt'),
|
||||||
|
platform_message.Quote(origin=platform_message.MessageChain([platform_message.Plain(text='quoted')])),
|
||||||
|
]
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
assert 'hi' in content
|
||||||
|
assert '[Image]' in content
|
||||||
|
assert '[File: a.txt]' in content
|
||||||
|
assert 'quoted' in content
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_officialaccount_event_converter_maps_text_image_voice_and_platform_event():
|
||||||
|
text_event = await OfficialAccountEventConverter().target2yiri(oa_event(content='hello'))
|
||||||
|
image_event = await OfficialAccountEventConverter().target2yiri(oa_event(msgtype='image'))
|
||||||
|
voice_event = await OfficialAccountEventConverter().target2yiri(oa_event(msgtype='voice'))
|
||||||
|
subscribe_event = await OfficialAccountEventConverter().target2yiri(oa_event(msgtype='event', event='subscribe'))
|
||||||
|
|
||||||
|
assert isinstance(text_event, platform_events.MessageReceivedEvent)
|
||||||
|
assert text_event.adapter_name == 'officialaccount-eba'
|
||||||
|
assert text_event.chat_type == platform_entities.ChatType.PRIVATE
|
||||||
|
assert text_event.chat_id == 'openid-1'
|
||||||
|
assert str(text_event.message_chain) == 'hello'
|
||||||
|
|
||||||
|
assert isinstance(image_event.message_chain[1], platform_message.Image)
|
||||||
|
assert image_event.message_chain[1].image_id == 'media-1'
|
||||||
|
assert isinstance(voice_event.message_chain[1], platform_message.Voice)
|
||||||
|
assert voice_event.message_chain[1].voice_id == 'voice-1'
|
||||||
|
assert isinstance(subscribe_event, platform_events.PlatformSpecificEvent)
|
||||||
|
assert subscribe_event.action == 'officialaccount.subscribe'
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_officialaccount_adapter_dispatches_eba_and_legacy_and_caches_message_event():
|
||||||
|
adapter = make_adapter()
|
||||||
|
eba_calls: list[platform_events.Event] = []
|
||||||
|
legacy_calls: list[platform_events.Event] = []
|
||||||
|
|
||||||
|
async def eba_listener(event, adapter):
|
||||||
|
eba_calls.append(event)
|
||||||
|
|
||||||
|
async def legacy_listener(event, adapter):
|
||||||
|
legacy_calls.append(event)
|
||||||
|
|
||||||
|
adapter.register_listener(platform_events.MessageReceivedEvent, eba_listener)
|
||||||
|
adapter.register_listener(platform_events.FriendMessage, legacy_listener)
|
||||||
|
await adapter._handle_native_event(oa_event())
|
||||||
|
|
||||||
|
assert len(eba_calls) == 1
|
||||||
|
assert len(legacy_calls) == 1
|
||||||
|
received = eba_calls[0]
|
||||||
|
assert isinstance(received, platform_events.MessageReceivedEvent)
|
||||||
|
assert await adapter.get_message('private', 'openid-1', 123) == received
|
||||||
|
assert (await adapter.get_user_info('openid-1')).nickname == 'openid-1'
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_officialaccount_reply_platform_api_and_unsupported_send():
|
||||||
|
adapter = make_adapter()
|
||||||
|
source_event = await OfficialAccountEventConverter().target2yiri(oa_event())
|
||||||
|
message = platform_message.MessageChain([platform_message.Plain(text='reply')])
|
||||||
|
|
||||||
|
await adapter.reply_message(source_event, message)
|
||||||
|
adapter.bot.set_message.assert_awaited_once_with(123, 'reply')
|
||||||
|
|
||||||
|
assert await adapter.call_platform_api('get_mode', {}) == {'mode': 'drop', 'longer_response': False}
|
||||||
|
|
||||||
|
with pytest.raises(NotSupportedError):
|
||||||
|
await adapter.send_message('person', 'openid-1', message)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_officialaccount_passive_mode_reply_queues_by_user():
|
||||||
|
adapter = make_adapter(mode='passive')
|
||||||
|
source_event = await OfficialAccountEventConverter().target2yiri(oa_event())
|
||||||
|
|
||||||
|
await adapter.reply_message(source_event, platform_message.MessageChain([platform_message.Plain(text='reply')]))
|
||||||
|
|
||||||
|
adapter.bot.set_message.assert_awaited_once_with('openid-1', 123, 'reply')
|
||||||
Reference in New Issue
Block a user